View.java revision a8a8ff000b2902eb4e187e62be39fd9535c6c839
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(), this);
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(), this);
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            refreshDrawableState();
4912        }
4913    }
4914
4915    /**
4916     * Populates <code>outRect</code> with the hotspot bounds. By default,
4917     * the hotspot bounds are identical to the screen bounds.
4918     *
4919     * @param outRect rect to populate with hotspot bounds
4920     * @hide Only for internal use by views and widgets.
4921     */
4922    public void getHotspotBounds(Rect outRect) {
4923        final Drawable background = getBackground();
4924        if (background != null) {
4925            background.getHotspotBounds(outRect);
4926        } else {
4927            getBoundsOnScreen(outRect);
4928        }
4929    }
4930
4931    /**
4932     * Request that a rectangle of this view be visible on the screen,
4933     * scrolling if necessary just enough.
4934     *
4935     * <p>A View should call this if it maintains some notion of which part
4936     * of its content is interesting.  For example, a text editing view
4937     * should call this when its cursor moves.
4938     *
4939     * @param rectangle The rectangle.
4940     * @return Whether any parent scrolled.
4941     */
4942    public boolean requestRectangleOnScreen(Rect rectangle) {
4943        return requestRectangleOnScreen(rectangle, false);
4944    }
4945
4946    /**
4947     * Request that a rectangle of this view be visible on the screen,
4948     * scrolling if necessary just enough.
4949     *
4950     * <p>A View should call this if it maintains some notion of which part
4951     * of its content is interesting.  For example, a text editing view
4952     * should call this when its cursor moves.
4953     *
4954     * <p>When <code>immediate</code> is set to true, scrolling will not be
4955     * animated.
4956     *
4957     * @param rectangle The rectangle.
4958     * @param immediate True to forbid animated scrolling, false otherwise
4959     * @return Whether any parent scrolled.
4960     */
4961    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
4962        if (mParent == null) {
4963            return false;
4964        }
4965
4966        View child = this;
4967
4968        RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF();
4969        position.set(rectangle);
4970
4971        ViewParent parent = mParent;
4972        boolean scrolled = false;
4973        while (parent != null) {
4974            rectangle.set((int) position.left, (int) position.top,
4975                    (int) position.right, (int) position.bottom);
4976
4977            scrolled |= parent.requestChildRectangleOnScreen(child,
4978                    rectangle, immediate);
4979
4980            if (!child.hasIdentityMatrix()) {
4981                child.getMatrix().mapRect(position);
4982            }
4983
4984            position.offset(child.mLeft, child.mTop);
4985
4986            if (!(parent instanceof View)) {
4987                break;
4988            }
4989
4990            View parentView = (View) parent;
4991
4992            position.offset(-parentView.getScrollX(), -parentView.getScrollY());
4993
4994            child = parentView;
4995            parent = child.getParent();
4996        }
4997
4998        return scrolled;
4999    }
5000
5001    /**
5002     * Called when this view wants to give up focus. If focus is cleared
5003     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
5004     * <p>
5005     * <strong>Note:</strong> When a View clears focus the framework is trying
5006     * to give focus to the first focusable View from the top. Hence, if this
5007     * View is the first from the top that can take focus, then all callbacks
5008     * related to clearing focus will be invoked after wich the framework will
5009     * give focus to this view.
5010     * </p>
5011     */
5012    public void clearFocus() {
5013        if (DBG) {
5014            System.out.println(this + " clearFocus()");
5015        }
5016
5017        clearFocusInternal(null, true, true);
5018    }
5019
5020    /**
5021     * Clears focus from the view, optionally propagating the change up through
5022     * the parent hierarchy and requesting that the root view place new focus.
5023     *
5024     * @param propagate whether to propagate the change up through the parent
5025     *            hierarchy
5026     * @param refocus when propagate is true, specifies whether to request the
5027     *            root view place new focus
5028     */
5029    void clearFocusInternal(View focused, boolean propagate, boolean refocus) {
5030        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
5031            mPrivateFlags &= ~PFLAG_FOCUSED;
5032
5033            if (propagate && mParent != null) {
5034                mParent.clearChildFocus(this);
5035            }
5036
5037            onFocusChanged(false, 0, null);
5038            refreshDrawableState();
5039
5040            if (propagate && (!refocus || !rootViewRequestFocus())) {
5041                notifyGlobalFocusCleared(this);
5042            }
5043        }
5044    }
5045
5046    void notifyGlobalFocusCleared(View oldFocus) {
5047        if (oldFocus != null && mAttachInfo != null) {
5048            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
5049        }
5050    }
5051
5052    boolean rootViewRequestFocus() {
5053        final View root = getRootView();
5054        return root != null && root.requestFocus();
5055    }
5056
5057    /**
5058     * Called internally by the view system when a new view is getting focus.
5059     * This is what clears the old focus.
5060     * <p>
5061     * <b>NOTE:</b> The parent view's focused child must be updated manually
5062     * after calling this method. Otherwise, the view hierarchy may be left in
5063     * an inconstent state.
5064     */
5065    void unFocus(View focused) {
5066        if (DBG) {
5067            System.out.println(this + " unFocus()");
5068        }
5069
5070        clearFocusInternal(focused, false, false);
5071    }
5072
5073    /**
5074     * Returns true if this view has focus iteself, or is the ancestor of the
5075     * view that has focus.
5076     *
5077     * @return True if this view has or contains focus, false otherwise.
5078     */
5079    @ViewDebug.ExportedProperty(category = "focus")
5080    public boolean hasFocus() {
5081        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
5082    }
5083
5084    /**
5085     * Returns true if this view is focusable or if it contains a reachable View
5086     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
5087     * is a View whose parents do not block descendants focus.
5088     *
5089     * Only {@link #VISIBLE} views are considered focusable.
5090     *
5091     * @return True if the view is focusable or if the view contains a focusable
5092     *         View, false otherwise.
5093     *
5094     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
5095     * @see ViewGroup#getTouchscreenBlocksFocus()
5096     */
5097    public boolean hasFocusable() {
5098        if (!isFocusableInTouchMode()) {
5099            for (ViewParent p = mParent; p instanceof ViewGroup; p = p.getParent()) {
5100                final ViewGroup g = (ViewGroup) p;
5101                if (g.shouldBlockFocusForTouchscreen()) {
5102                    return false;
5103                }
5104            }
5105        }
5106        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
5107    }
5108
5109    /**
5110     * Called by the view system when the focus state of this view changes.
5111     * When the focus change event is caused by directional navigation, direction
5112     * and previouslyFocusedRect provide insight into where the focus is coming from.
5113     * When overriding, be sure to call up through to the super class so that
5114     * the standard focus handling will occur.
5115     *
5116     * @param gainFocus True if the View has focus; false otherwise.
5117     * @param direction The direction focus has moved when requestFocus()
5118     *                  is called to give this view focus. Values are
5119     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
5120     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
5121     *                  It may not always apply, in which case use the default.
5122     * @param previouslyFocusedRect The rectangle, in this view's coordinate
5123     *        system, of the previously focused view.  If applicable, this will be
5124     *        passed in as finer grained information about where the focus is coming
5125     *        from (in addition to direction).  Will be <code>null</code> otherwise.
5126     */
5127    protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction,
5128            @Nullable Rect previouslyFocusedRect) {
5129        if (gainFocus) {
5130            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
5131        } else {
5132            notifyViewAccessibilityStateChangedIfNeeded(
5133                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
5134        }
5135
5136        InputMethodManager imm = InputMethodManager.peekInstance();
5137        if (!gainFocus) {
5138            if (isPressed()) {
5139                setPressed(false);
5140            }
5141            if (imm != null && mAttachInfo != null
5142                    && mAttachInfo.mHasWindowFocus) {
5143                imm.focusOut(this);
5144            }
5145            onFocusLost();
5146        } else if (imm != null && mAttachInfo != null
5147                && mAttachInfo.mHasWindowFocus) {
5148            imm.focusIn(this);
5149        }
5150
5151        invalidate(true);
5152        ListenerInfo li = mListenerInfo;
5153        if (li != null && li.mOnFocusChangeListener != null) {
5154            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
5155        }
5156
5157        if (mAttachInfo != null) {
5158            mAttachInfo.mKeyDispatchState.reset(this);
5159        }
5160    }
5161
5162    /**
5163     * Sends an accessibility event of the given type. If accessibility is
5164     * not enabled this method has no effect. The default implementation calls
5165     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
5166     * to populate information about the event source (this View), then calls
5167     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
5168     * populate the text content of the event source including its descendants,
5169     * and last calls
5170     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
5171     * on its parent to resuest sending of the event to interested parties.
5172     * <p>
5173     * If an {@link AccessibilityDelegate} has been specified via calling
5174     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5175     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
5176     * responsible for handling this call.
5177     * </p>
5178     *
5179     * @param eventType The type of the event to send, as defined by several types from
5180     * {@link android.view.accessibility.AccessibilityEvent}, such as
5181     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
5182     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
5183     *
5184     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
5185     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5186     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
5187     * @see AccessibilityDelegate
5188     */
5189    public void sendAccessibilityEvent(int eventType) {
5190        if (mAccessibilityDelegate != null) {
5191            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
5192        } else {
5193            sendAccessibilityEventInternal(eventType);
5194        }
5195    }
5196
5197    /**
5198     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
5199     * {@link AccessibilityEvent} to make an announcement which is related to some
5200     * sort of a context change for which none of the events representing UI transitions
5201     * is a good fit. For example, announcing a new page in a book. If accessibility
5202     * is not enabled this method does nothing.
5203     *
5204     * @param text The announcement text.
5205     */
5206    public void announceForAccessibility(CharSequence text) {
5207        if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) {
5208            AccessibilityEvent event = AccessibilityEvent.obtain(
5209                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
5210            onInitializeAccessibilityEvent(event);
5211            event.getText().add(text);
5212            event.setContentDescription(null);
5213            mParent.requestSendAccessibilityEvent(this, event);
5214        }
5215    }
5216
5217    /**
5218     * @see #sendAccessibilityEvent(int)
5219     *
5220     * Note: Called from the default {@link AccessibilityDelegate}.
5221     */
5222    void sendAccessibilityEventInternal(int eventType) {
5223        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
5224            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
5225        }
5226    }
5227
5228    /**
5229     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
5230     * takes as an argument an empty {@link AccessibilityEvent} and does not
5231     * perform a check whether accessibility is enabled.
5232     * <p>
5233     * If an {@link AccessibilityDelegate} has been specified via calling
5234     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5235     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
5236     * is responsible for handling this call.
5237     * </p>
5238     *
5239     * @param event The event to send.
5240     *
5241     * @see #sendAccessibilityEvent(int)
5242     */
5243    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
5244        if (mAccessibilityDelegate != null) {
5245            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
5246        } else {
5247            sendAccessibilityEventUncheckedInternal(event);
5248        }
5249    }
5250
5251    /**
5252     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
5253     *
5254     * Note: Called from the default {@link AccessibilityDelegate}.
5255     */
5256    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
5257        if (!isShown()) {
5258            return;
5259        }
5260        onInitializeAccessibilityEvent(event);
5261        // Only a subset of accessibility events populates text content.
5262        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
5263            dispatchPopulateAccessibilityEvent(event);
5264        }
5265        // In the beginning we called #isShown(), so we know that getParent() is not null.
5266        getParent().requestSendAccessibilityEvent(this, event);
5267    }
5268
5269    /**
5270     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
5271     * to its children for adding their text content to the event. Note that the
5272     * event text is populated in a separate dispatch path since we add to the
5273     * event not only the text of the source but also the text of all its descendants.
5274     * A typical implementation will call
5275     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
5276     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
5277     * on each child. Override this method if custom population of the event text
5278     * content is required.
5279     * <p>
5280     * If an {@link AccessibilityDelegate} has been specified via calling
5281     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5282     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
5283     * is responsible for handling this call.
5284     * </p>
5285     * <p>
5286     * <em>Note:</em> Accessibility events of certain types are not dispatched for
5287     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
5288     * </p>
5289     *
5290     * @param event The event.
5291     *
5292     * @return True if the event population was completed.
5293     */
5294    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
5295        if (mAccessibilityDelegate != null) {
5296            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
5297        } else {
5298            return dispatchPopulateAccessibilityEventInternal(event);
5299        }
5300    }
5301
5302    /**
5303     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5304     *
5305     * Note: Called from the default {@link AccessibilityDelegate}.
5306     */
5307    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
5308        onPopulateAccessibilityEvent(event);
5309        return false;
5310    }
5311
5312    /**
5313     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
5314     * giving a chance to this View to populate the accessibility event with its
5315     * text content. While this method is free to modify event
5316     * attributes other than text content, doing so should normally be performed in
5317     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
5318     * <p>
5319     * Example: Adding formatted date string to an accessibility event in addition
5320     *          to the text added by the super implementation:
5321     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
5322     *     super.onPopulateAccessibilityEvent(event);
5323     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
5324     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
5325     *         mCurrentDate.getTimeInMillis(), flags);
5326     *     event.getText().add(selectedDateUtterance);
5327     * }</pre>
5328     * <p>
5329     * If an {@link AccessibilityDelegate} has been specified via calling
5330     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5331     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
5332     * is responsible for handling this call.
5333     * </p>
5334     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
5335     * information to the event, in case the default implementation has basic information to add.
5336     * </p>
5337     *
5338     * @param event The accessibility event which to populate.
5339     *
5340     * @see #sendAccessibilityEvent(int)
5341     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5342     */
5343    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
5344        if (mAccessibilityDelegate != null) {
5345            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
5346        } else {
5347            onPopulateAccessibilityEventInternal(event);
5348        }
5349    }
5350
5351    /**
5352     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
5353     *
5354     * Note: Called from the default {@link AccessibilityDelegate}.
5355     */
5356    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
5357    }
5358
5359    /**
5360     * Initializes an {@link AccessibilityEvent} with information about
5361     * this View which is the event source. In other words, the source of
5362     * an accessibility event is the view whose state change triggered firing
5363     * the event.
5364     * <p>
5365     * Example: Setting the password property of an event in addition
5366     *          to properties set by the super implementation:
5367     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
5368     *     super.onInitializeAccessibilityEvent(event);
5369     *     event.setPassword(true);
5370     * }</pre>
5371     * <p>
5372     * If an {@link AccessibilityDelegate} has been specified via calling
5373     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5374     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
5375     * is responsible for handling this call.
5376     * </p>
5377     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
5378     * information to the event, in case the default implementation has basic information to add.
5379     * </p>
5380     * @param event The event to initialize.
5381     *
5382     * @see #sendAccessibilityEvent(int)
5383     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5384     */
5385    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
5386        if (mAccessibilityDelegate != null) {
5387            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
5388        } else {
5389            onInitializeAccessibilityEventInternal(event);
5390        }
5391    }
5392
5393    /**
5394     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
5395     *
5396     * Note: Called from the default {@link AccessibilityDelegate}.
5397     */
5398    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
5399        event.setSource(this);
5400        event.setClassName(View.class.getName());
5401        event.setPackageName(getContext().getPackageName());
5402        event.setEnabled(isEnabled());
5403        event.setContentDescription(mContentDescription);
5404
5405        switch (event.getEventType()) {
5406            case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
5407                ArrayList<View> focusablesTempList = (mAttachInfo != null)
5408                        ? mAttachInfo.mTempArrayList : new ArrayList<View>();
5409                getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
5410                event.setItemCount(focusablesTempList.size());
5411                event.setCurrentItemIndex(focusablesTempList.indexOf(this));
5412                if (mAttachInfo != null) {
5413                    focusablesTempList.clear();
5414                }
5415            } break;
5416            case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: {
5417                CharSequence text = getIterableTextForAccessibility();
5418                if (text != null && text.length() > 0) {
5419                    event.setFromIndex(getAccessibilitySelectionStart());
5420                    event.setToIndex(getAccessibilitySelectionEnd());
5421                    event.setItemCount(text.length());
5422                }
5423            } break;
5424        }
5425    }
5426
5427    /**
5428     * Returns an {@link AccessibilityNodeInfo} representing this view from the
5429     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
5430     * This method is responsible for obtaining an accessibility node info from a
5431     * pool of reusable instances and calling
5432     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
5433     * initialize the former.
5434     * <p>
5435     * Note: The client is responsible for recycling the obtained instance by calling
5436     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
5437     * </p>
5438     *
5439     * @return A populated {@link AccessibilityNodeInfo}.
5440     *
5441     * @see AccessibilityNodeInfo
5442     */
5443    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
5444        if (mAccessibilityDelegate != null) {
5445            return mAccessibilityDelegate.createAccessibilityNodeInfo(this);
5446        } else {
5447            return createAccessibilityNodeInfoInternal();
5448        }
5449    }
5450
5451    /**
5452     * @see #createAccessibilityNodeInfo()
5453     */
5454    AccessibilityNodeInfo createAccessibilityNodeInfoInternal() {
5455        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
5456        if (provider != null) {
5457            return provider.createAccessibilityNodeInfo(View.NO_ID);
5458        } else {
5459            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
5460            onInitializeAccessibilityNodeInfo(info);
5461            return info;
5462        }
5463    }
5464
5465    /**
5466     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
5467     * The base implementation sets:
5468     * <ul>
5469     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
5470     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
5471     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
5472     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
5473     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
5474     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
5475     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
5476     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
5477     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
5478     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
5479     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
5480     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
5481     * </ul>
5482     * <p>
5483     * Subclasses should override this method, call the super implementation,
5484     * and set additional attributes.
5485     * </p>
5486     * <p>
5487     * If an {@link AccessibilityDelegate} has been specified via calling
5488     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5489     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
5490     * is responsible for handling this call.
5491     * </p>
5492     *
5493     * @param info The instance to initialize.
5494     */
5495    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
5496        if (mAccessibilityDelegate != null) {
5497            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
5498        } else {
5499            onInitializeAccessibilityNodeInfoInternal(info);
5500        }
5501    }
5502
5503    /**
5504     * Gets the location of this view in screen coordintates.
5505     *
5506     * @param outRect The output location
5507     * @hide
5508     */
5509    public void getBoundsOnScreen(Rect outRect) {
5510        if (mAttachInfo == null) {
5511            return;
5512        }
5513
5514        RectF position = mAttachInfo.mTmpTransformRect;
5515        position.set(0, 0, mRight - mLeft, mBottom - mTop);
5516
5517        if (!hasIdentityMatrix()) {
5518            getMatrix().mapRect(position);
5519        }
5520
5521        position.offset(mLeft, mTop);
5522
5523        ViewParent parent = mParent;
5524        while (parent instanceof View) {
5525            View parentView = (View) parent;
5526
5527            position.offset(-parentView.mScrollX, -parentView.mScrollY);
5528
5529            if (!parentView.hasIdentityMatrix()) {
5530                parentView.getMatrix().mapRect(position);
5531            }
5532
5533            position.offset(parentView.mLeft, parentView.mTop);
5534
5535            parent = parentView.mParent;
5536        }
5537
5538        if (parent instanceof ViewRootImpl) {
5539            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
5540            position.offset(0, -viewRootImpl.mCurScrollY);
5541        }
5542
5543        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
5544
5545        outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f),
5546                (int) (position.right + 0.5f), (int) (position.bottom + 0.5f));
5547    }
5548
5549    /**
5550     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
5551     *
5552     * Note: Called from the default {@link AccessibilityDelegate}.
5553     */
5554    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
5555        Rect bounds = mAttachInfo.mTmpInvalRect;
5556
5557        getDrawingRect(bounds);
5558        info.setBoundsInParent(bounds);
5559
5560        getBoundsOnScreen(bounds);
5561        info.setBoundsInScreen(bounds);
5562
5563        ViewParent parent = getParentForAccessibility();
5564        if (parent instanceof View) {
5565            info.setParent((View) parent);
5566        }
5567
5568        if (mID != View.NO_ID) {
5569            View rootView = getRootView();
5570            if (rootView == null) {
5571                rootView = this;
5572            }
5573            View label = rootView.findLabelForView(this, mID);
5574            if (label != null) {
5575                info.setLabeledBy(label);
5576            }
5577
5578            if ((mAttachInfo.mAccessibilityFetchFlags
5579                    & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0
5580                    && Resources.resourceHasPackage(mID)) {
5581                try {
5582                    String viewId = getResources().getResourceName(mID);
5583                    info.setViewIdResourceName(viewId);
5584                } catch (Resources.NotFoundException nfe) {
5585                    /* ignore */
5586                }
5587            }
5588        }
5589
5590        if (mLabelForId != View.NO_ID) {
5591            View rootView = getRootView();
5592            if (rootView == null) {
5593                rootView = this;
5594            }
5595            View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId);
5596            if (labeled != null) {
5597                info.setLabelFor(labeled);
5598            }
5599        }
5600
5601        info.setVisibleToUser(isVisibleToUser());
5602
5603        info.setPackageName(mContext.getPackageName());
5604        info.setClassName(View.class.getName());
5605        info.setContentDescription(getContentDescription());
5606
5607        info.setEnabled(isEnabled());
5608        info.setClickable(isClickable());
5609        info.setFocusable(isFocusable());
5610        info.setFocused(isFocused());
5611        info.setAccessibilityFocused(isAccessibilityFocused());
5612        info.setSelected(isSelected());
5613        info.setLongClickable(isLongClickable());
5614        info.setLiveRegion(getAccessibilityLiveRegion());
5615
5616        // TODO: These make sense only if we are in an AdapterView but all
5617        // views can be selected. Maybe from accessibility perspective
5618        // we should report as selectable view in an AdapterView.
5619        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
5620        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
5621
5622        if (isFocusable()) {
5623            if (isFocused()) {
5624                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
5625            } else {
5626                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
5627            }
5628        }
5629
5630        if (!isAccessibilityFocused()) {
5631            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
5632        } else {
5633            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
5634        }
5635
5636        if (isClickable() && isEnabled()) {
5637            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
5638        }
5639
5640        if (isLongClickable() && isEnabled()) {
5641            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
5642        }
5643
5644        CharSequence text = getIterableTextForAccessibility();
5645        if (text != null && text.length() > 0) {
5646            info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd());
5647
5648            info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION);
5649            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
5650            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
5651            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
5652                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
5653                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
5654        }
5655    }
5656
5657    private View findLabelForView(View view, int labeledId) {
5658        if (mMatchLabelForPredicate == null) {
5659            mMatchLabelForPredicate = new MatchLabelForPredicate();
5660        }
5661        mMatchLabelForPredicate.mLabeledId = labeledId;
5662        return findViewByPredicateInsideOut(view, mMatchLabelForPredicate);
5663    }
5664
5665    /**
5666     * Computes whether this view is visible to the user. Such a view is
5667     * attached, visible, all its predecessors are visible, it is not clipped
5668     * entirely by its predecessors, and has an alpha greater than zero.
5669     *
5670     * @return Whether the view is visible on the screen.
5671     *
5672     * @hide
5673     */
5674    protected boolean isVisibleToUser() {
5675        return isVisibleToUser(null);
5676    }
5677
5678    /**
5679     * Computes whether the given portion of this view is visible to the user.
5680     * Such a view is attached, visible, all its predecessors are visible,
5681     * has an alpha greater than zero, and the specified portion is not
5682     * clipped entirely by its predecessors.
5683     *
5684     * @param boundInView the portion of the view to test; coordinates should be relative; may be
5685     *                    <code>null</code>, and the entire view will be tested in this case.
5686     *                    When <code>true</code> is returned by the function, the actual visible
5687     *                    region will be stored in this parameter; that is, if boundInView is fully
5688     *                    contained within the view, no modification will be made, otherwise regions
5689     *                    outside of the visible area of the view will be clipped.
5690     *
5691     * @return Whether the specified portion of the view is visible on the screen.
5692     *
5693     * @hide
5694     */
5695    protected boolean isVisibleToUser(Rect boundInView) {
5696        if (mAttachInfo != null) {
5697            // Attached to invisible window means this view is not visible.
5698            if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
5699                return false;
5700            }
5701            // An invisible predecessor or one with alpha zero means
5702            // that this view is not visible to the user.
5703            Object current = this;
5704            while (current instanceof View) {
5705                View view = (View) current;
5706                // We have attach info so this view is attached and there is no
5707                // need to check whether we reach to ViewRootImpl on the way up.
5708                if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 ||
5709                        view.getVisibility() != VISIBLE) {
5710                    return false;
5711                }
5712                current = view.mParent;
5713            }
5714            // Check if the view is entirely covered by its predecessors.
5715            Rect visibleRect = mAttachInfo.mTmpInvalRect;
5716            Point offset = mAttachInfo.mPoint;
5717            if (!getGlobalVisibleRect(visibleRect, offset)) {
5718                return false;
5719            }
5720            // Check if the visible portion intersects the rectangle of interest.
5721            if (boundInView != null) {
5722                visibleRect.offset(-offset.x, -offset.y);
5723                return boundInView.intersect(visibleRect);
5724            }
5725            return true;
5726        }
5727        return false;
5728    }
5729
5730    /**
5731     * Returns the delegate for implementing accessibility support via
5732     * composition. For more details see {@link AccessibilityDelegate}.
5733     *
5734     * @return The delegate, or null if none set.
5735     *
5736     * @hide
5737     */
5738    public AccessibilityDelegate getAccessibilityDelegate() {
5739        return mAccessibilityDelegate;
5740    }
5741
5742    /**
5743     * Sets a delegate for implementing accessibility support via composition as
5744     * opposed to inheritance. The delegate's primary use is for implementing
5745     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
5746     *
5747     * @param delegate The delegate instance.
5748     *
5749     * @see AccessibilityDelegate
5750     */
5751    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
5752        mAccessibilityDelegate = delegate;
5753    }
5754
5755    /**
5756     * Gets the provider for managing a virtual view hierarchy rooted at this View
5757     * and reported to {@link android.accessibilityservice.AccessibilityService}s
5758     * that explore the window content.
5759     * <p>
5760     * If this method returns an instance, this instance is responsible for managing
5761     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
5762     * View including the one representing the View itself. Similarly the returned
5763     * instance is responsible for performing accessibility actions on any virtual
5764     * view or the root view itself.
5765     * </p>
5766     * <p>
5767     * If an {@link AccessibilityDelegate} has been specified via calling
5768     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5769     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
5770     * is responsible for handling this call.
5771     * </p>
5772     *
5773     * @return The provider.
5774     *
5775     * @see AccessibilityNodeProvider
5776     */
5777    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
5778        if (mAccessibilityDelegate != null) {
5779            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
5780        } else {
5781            return null;
5782        }
5783    }
5784
5785    /**
5786     * Gets the unique identifier of this view on the screen for accessibility purposes.
5787     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
5788     *
5789     * @return The view accessibility id.
5790     *
5791     * @hide
5792     */
5793    public int getAccessibilityViewId() {
5794        if (mAccessibilityViewId == NO_ID) {
5795            mAccessibilityViewId = sNextAccessibilityViewId++;
5796        }
5797        return mAccessibilityViewId;
5798    }
5799
5800    /**
5801     * Gets the unique identifier of the window in which this View reseides.
5802     *
5803     * @return The window accessibility id.
5804     *
5805     * @hide
5806     */
5807    public int getAccessibilityWindowId() {
5808        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId
5809                : AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
5810    }
5811
5812    /**
5813     * Gets the {@link View} description. It briefly describes the view and is
5814     * primarily used for accessibility support. Set this property to enable
5815     * better accessibility support for your application. This is especially
5816     * true for views that do not have textual representation (For example,
5817     * ImageButton).
5818     *
5819     * @return The content description.
5820     *
5821     * @attr ref android.R.styleable#View_contentDescription
5822     */
5823    @ViewDebug.ExportedProperty(category = "accessibility")
5824    public CharSequence getContentDescription() {
5825        return mContentDescription;
5826    }
5827
5828    /**
5829     * Sets the {@link View} description. It briefly describes the view and is
5830     * primarily used for accessibility support. Set this property to enable
5831     * better accessibility support for your application. This is especially
5832     * true for views that do not have textual representation (For example,
5833     * ImageButton).
5834     *
5835     * @param contentDescription The content description.
5836     *
5837     * @attr ref android.R.styleable#View_contentDescription
5838     */
5839    @RemotableViewMethod
5840    public void setContentDescription(CharSequence contentDescription) {
5841        if (mContentDescription == null) {
5842            if (contentDescription == null) {
5843                return;
5844            }
5845        } else if (mContentDescription.equals(contentDescription)) {
5846            return;
5847        }
5848        mContentDescription = contentDescription;
5849        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
5850        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
5851            setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
5852            notifySubtreeAccessibilityStateChangedIfNeeded();
5853        } else {
5854            notifyViewAccessibilityStateChangedIfNeeded(
5855                    AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION);
5856        }
5857    }
5858
5859    /**
5860     * Gets the id of a view for which this view serves as a label for
5861     * accessibility purposes.
5862     *
5863     * @return The labeled view id.
5864     */
5865    @ViewDebug.ExportedProperty(category = "accessibility")
5866    public int getLabelFor() {
5867        return mLabelForId;
5868    }
5869
5870    /**
5871     * Sets the id of a view for which this view serves as a label for
5872     * accessibility purposes.
5873     *
5874     * @param id The labeled view id.
5875     */
5876    @RemotableViewMethod
5877    public void setLabelFor(int id) {
5878        mLabelForId = id;
5879        if (mLabelForId != View.NO_ID
5880                && mID == View.NO_ID) {
5881            mID = generateViewId();
5882        }
5883    }
5884
5885    /**
5886     * Invoked whenever this view loses focus, either by losing window focus or by losing
5887     * focus within its window. This method can be used to clear any state tied to the
5888     * focus. For instance, if a button is held pressed with the trackball and the window
5889     * loses focus, this method can be used to cancel the press.
5890     *
5891     * Subclasses of View overriding this method should always call super.onFocusLost().
5892     *
5893     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
5894     * @see #onWindowFocusChanged(boolean)
5895     *
5896     * @hide pending API council approval
5897     */
5898    protected void onFocusLost() {
5899        resetPressedState();
5900    }
5901
5902    private void resetPressedState() {
5903        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
5904            return;
5905        }
5906
5907        if (isPressed()) {
5908            setPressed(false);
5909
5910            if (!mHasPerformedLongPress) {
5911                removeLongPressCallback();
5912            }
5913        }
5914    }
5915
5916    /**
5917     * Returns true if this view has focus
5918     *
5919     * @return True if this view has focus, false otherwise.
5920     */
5921    @ViewDebug.ExportedProperty(category = "focus")
5922    public boolean isFocused() {
5923        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
5924    }
5925
5926    /**
5927     * Find the view in the hierarchy rooted at this view that currently has
5928     * focus.
5929     *
5930     * @return The view that currently has focus, or null if no focused view can
5931     *         be found.
5932     */
5933    public View findFocus() {
5934        return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
5935    }
5936
5937    /**
5938     * Indicates whether this view is one of the set of scrollable containers in
5939     * its window.
5940     *
5941     * @return whether this view is one of the set of scrollable containers in
5942     * its window
5943     *
5944     * @attr ref android.R.styleable#View_isScrollContainer
5945     */
5946    public boolean isScrollContainer() {
5947        return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0;
5948    }
5949
5950    /**
5951     * Change whether this view is one of the set of scrollable containers in
5952     * its window.  This will be used to determine whether the window can
5953     * resize or must pan when a soft input area is open -- scrollable
5954     * containers allow the window to use resize mode since the container
5955     * will appropriately shrink.
5956     *
5957     * @attr ref android.R.styleable#View_isScrollContainer
5958     */
5959    public void setScrollContainer(boolean isScrollContainer) {
5960        if (isScrollContainer) {
5961            if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) {
5962                mAttachInfo.mScrollContainers.add(this);
5963                mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
5964            }
5965            mPrivateFlags |= PFLAG_SCROLL_CONTAINER;
5966        } else {
5967            if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
5968                mAttachInfo.mScrollContainers.remove(this);
5969            }
5970            mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED);
5971        }
5972    }
5973
5974    /**
5975     * Returns the quality of the drawing cache.
5976     *
5977     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5978     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5979     *
5980     * @see #setDrawingCacheQuality(int)
5981     * @see #setDrawingCacheEnabled(boolean)
5982     * @see #isDrawingCacheEnabled()
5983     *
5984     * @attr ref android.R.styleable#View_drawingCacheQuality
5985     */
5986    @DrawingCacheQuality
5987    public int getDrawingCacheQuality() {
5988        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
5989    }
5990
5991    /**
5992     * Set the drawing cache quality of this view. This value is used only when the
5993     * drawing cache is enabled
5994     *
5995     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5996     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5997     *
5998     * @see #getDrawingCacheQuality()
5999     * @see #setDrawingCacheEnabled(boolean)
6000     * @see #isDrawingCacheEnabled()
6001     *
6002     * @attr ref android.R.styleable#View_drawingCacheQuality
6003     */
6004    public void setDrawingCacheQuality(@DrawingCacheQuality int quality) {
6005        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
6006    }
6007
6008    /**
6009     * Returns whether the screen should remain on, corresponding to the current
6010     * value of {@link #KEEP_SCREEN_ON}.
6011     *
6012     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
6013     *
6014     * @see #setKeepScreenOn(boolean)
6015     *
6016     * @attr ref android.R.styleable#View_keepScreenOn
6017     */
6018    public boolean getKeepScreenOn() {
6019        return (mViewFlags & KEEP_SCREEN_ON) != 0;
6020    }
6021
6022    /**
6023     * Controls whether the screen should remain on, modifying the
6024     * value of {@link #KEEP_SCREEN_ON}.
6025     *
6026     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
6027     *
6028     * @see #getKeepScreenOn()
6029     *
6030     * @attr ref android.R.styleable#View_keepScreenOn
6031     */
6032    public void setKeepScreenOn(boolean keepScreenOn) {
6033        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
6034    }
6035
6036    /**
6037     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
6038     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6039     *
6040     * @attr ref android.R.styleable#View_nextFocusLeft
6041     */
6042    public int getNextFocusLeftId() {
6043        return mNextFocusLeftId;
6044    }
6045
6046    /**
6047     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
6048     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
6049     * decide automatically.
6050     *
6051     * @attr ref android.R.styleable#View_nextFocusLeft
6052     */
6053    public void setNextFocusLeftId(int nextFocusLeftId) {
6054        mNextFocusLeftId = nextFocusLeftId;
6055    }
6056
6057    /**
6058     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
6059     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6060     *
6061     * @attr ref android.R.styleable#View_nextFocusRight
6062     */
6063    public int getNextFocusRightId() {
6064        return mNextFocusRightId;
6065    }
6066
6067    /**
6068     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
6069     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
6070     * decide automatically.
6071     *
6072     * @attr ref android.R.styleable#View_nextFocusRight
6073     */
6074    public void setNextFocusRightId(int nextFocusRightId) {
6075        mNextFocusRightId = nextFocusRightId;
6076    }
6077
6078    /**
6079     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
6080     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6081     *
6082     * @attr ref android.R.styleable#View_nextFocusUp
6083     */
6084    public int getNextFocusUpId() {
6085        return mNextFocusUpId;
6086    }
6087
6088    /**
6089     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
6090     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
6091     * decide automatically.
6092     *
6093     * @attr ref android.R.styleable#View_nextFocusUp
6094     */
6095    public void setNextFocusUpId(int nextFocusUpId) {
6096        mNextFocusUpId = nextFocusUpId;
6097    }
6098
6099    /**
6100     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
6101     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6102     *
6103     * @attr ref android.R.styleable#View_nextFocusDown
6104     */
6105    public int getNextFocusDownId() {
6106        return mNextFocusDownId;
6107    }
6108
6109    /**
6110     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
6111     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
6112     * decide automatically.
6113     *
6114     * @attr ref android.R.styleable#View_nextFocusDown
6115     */
6116    public void setNextFocusDownId(int nextFocusDownId) {
6117        mNextFocusDownId = nextFocusDownId;
6118    }
6119
6120    /**
6121     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
6122     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6123     *
6124     * @attr ref android.R.styleable#View_nextFocusForward
6125     */
6126    public int getNextFocusForwardId() {
6127        return mNextFocusForwardId;
6128    }
6129
6130    /**
6131     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
6132     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
6133     * decide automatically.
6134     *
6135     * @attr ref android.R.styleable#View_nextFocusForward
6136     */
6137    public void setNextFocusForwardId(int nextFocusForwardId) {
6138        mNextFocusForwardId = nextFocusForwardId;
6139    }
6140
6141    /**
6142     * Returns the visibility of this view and all of its ancestors
6143     *
6144     * @return True if this view and all of its ancestors are {@link #VISIBLE}
6145     */
6146    public boolean isShown() {
6147        View current = this;
6148        //noinspection ConstantConditions
6149        do {
6150            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6151                return false;
6152            }
6153            ViewParent parent = current.mParent;
6154            if (parent == null) {
6155                return false; // We are not attached to the view root
6156            }
6157            if (!(parent instanceof View)) {
6158                return true;
6159            }
6160            current = (View) parent;
6161        } while (current != null);
6162
6163        return false;
6164    }
6165
6166    /**
6167     * Called by the view hierarchy when the content insets for a window have
6168     * changed, to allow it to adjust its content to fit within those windows.
6169     * The content insets tell you the space that the status bar, input method,
6170     * and other system windows infringe on the application's window.
6171     *
6172     * <p>You do not normally need to deal with this function, since the default
6173     * window decoration given to applications takes care of applying it to the
6174     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
6175     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
6176     * and your content can be placed under those system elements.  You can then
6177     * use this method within your view hierarchy if you have parts of your UI
6178     * which you would like to ensure are not being covered.
6179     *
6180     * <p>The default implementation of this method simply applies the content
6181     * insets to the view's padding, consuming that content (modifying the
6182     * insets to be 0), and returning true.  This behavior is off by default, but can
6183     * be enabled through {@link #setFitsSystemWindows(boolean)}.
6184     *
6185     * <p>This function's traversal down the hierarchy is depth-first.  The same content
6186     * insets object is propagated down the hierarchy, so any changes made to it will
6187     * be seen by all following views (including potentially ones above in
6188     * the hierarchy since this is a depth-first traversal).  The first view
6189     * that returns true will abort the entire traversal.
6190     *
6191     * <p>The default implementation works well for a situation where it is
6192     * used with a container that covers the entire window, allowing it to
6193     * apply the appropriate insets to its content on all edges.  If you need
6194     * a more complicated layout (such as two different views fitting system
6195     * windows, one on the top of the window, and one on the bottom),
6196     * you can override the method and handle the insets however you would like.
6197     * Note that the insets provided by the framework are always relative to the
6198     * far edges of the window, not accounting for the location of the called view
6199     * within that window.  (In fact when this method is called you do not yet know
6200     * where the layout will place the view, as it is done before layout happens.)
6201     *
6202     * <p>Note: unlike many View methods, there is no dispatch phase to this
6203     * call.  If you are overriding it in a ViewGroup and want to allow the
6204     * call to continue to your children, you must be sure to call the super
6205     * implementation.
6206     *
6207     * <p>Here is a sample layout that makes use of fitting system windows
6208     * to have controls for a video view placed inside of the window decorations
6209     * that it hides and shows.  This can be used with code like the second
6210     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
6211     *
6212     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
6213     *
6214     * @param insets Current content insets of the window.  Prior to
6215     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
6216     * the insets or else you and Android will be unhappy.
6217     *
6218     * @return {@code true} if this view applied the insets and it should not
6219     * continue propagating further down the hierarchy, {@code false} otherwise.
6220     * @see #getFitsSystemWindows()
6221     * @see #setFitsSystemWindows(boolean)
6222     * @see #setSystemUiVisibility(int)
6223     *
6224     * @deprecated As of API XX use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply
6225     * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use
6226     * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)}
6227     * to implement handling their own insets.
6228     */
6229    protected boolean fitSystemWindows(Rect insets) {
6230        if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) {
6231            if (insets == null) {
6232                // Null insets by definition have already been consumed.
6233                // This call cannot apply insets since there are none to apply,
6234                // so return false.
6235                return false;
6236            }
6237            // If we're not in the process of dispatching the newer apply insets call,
6238            // that means we're not in the compatibility path. Dispatch into the newer
6239            // apply insets path and take things from there.
6240            try {
6241                mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS;
6242                return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed();
6243            } finally {
6244                mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS;
6245            }
6246        } else {
6247            // We're being called from the newer apply insets path.
6248            // Perform the standard fallback behavior.
6249            return fitSystemWindowsInt(insets);
6250        }
6251    }
6252
6253    private boolean fitSystemWindowsInt(Rect insets) {
6254        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
6255            mUserPaddingStart = UNDEFINED_PADDING;
6256            mUserPaddingEnd = UNDEFINED_PADDING;
6257            Rect localInsets = sThreadLocal.get();
6258            if (localInsets == null) {
6259                localInsets = new Rect();
6260                sThreadLocal.set(localInsets);
6261            }
6262            boolean res = computeFitSystemWindows(insets, localInsets);
6263            mUserPaddingLeftInitial = localInsets.left;
6264            mUserPaddingRightInitial = localInsets.right;
6265            internalSetPadding(localInsets.left, localInsets.top,
6266                    localInsets.right, localInsets.bottom);
6267            return res;
6268        }
6269        return false;
6270    }
6271
6272    /**
6273     * Called when the view should apply {@link WindowInsets} according to its internal policy.
6274     *
6275     * <p>This method should be overridden by views that wish to apply a policy different from or
6276     * in addition to the default behavior. Clients that wish to force a view subtree
6277     * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p>
6278     *
6279     * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set
6280     * it will be called during dispatch instead of this method. The listener may optionally
6281     * call this method from its own implementation if it wishes to apply the view's default
6282     * insets policy in addition to its own.</p>
6283     *
6284     * <p>Implementations of this method should either return the insets parameter unchanged
6285     * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed
6286     * that this view applied itself. This allows new inset types added in future platform
6287     * versions to pass through existing implementations unchanged without being erroneously
6288     * consumed.</p>
6289     *
6290     * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows}
6291     * property is set then the view will consume the system window insets and apply them
6292     * as padding for the view.</p>
6293     *
6294     * @param insets Insets to apply
6295     * @return The supplied insets with any applied insets consumed
6296     */
6297    public WindowInsets onApplyWindowInsets(WindowInsets insets) {
6298        if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) {
6299            // We weren't called from within a direct call to fitSystemWindows,
6300            // call into it as a fallback in case we're in a class that overrides it
6301            // and has logic to perform.
6302            if (fitSystemWindows(insets.getSystemWindowInsets())) {
6303                return insets.consumeSystemWindowInsets();
6304            }
6305        } else {
6306            // We were called from within a direct call to fitSystemWindows.
6307            if (fitSystemWindowsInt(insets.getSystemWindowInsets())) {
6308                return insets.consumeSystemWindowInsets();
6309            }
6310        }
6311        return insets;
6312    }
6313
6314    /**
6315     * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying
6316     * window insets to this view. The listener's
6317     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
6318     * method will be called instead of the view's
6319     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
6320     *
6321     * @param listener Listener to set
6322     *
6323     * @see #onApplyWindowInsets(WindowInsets)
6324     */
6325    public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) {
6326        getListenerInfo().mOnApplyWindowInsetsListener = listener;
6327    }
6328
6329    /**
6330     * Request to apply the given window insets to this view or another view in its subtree.
6331     *
6332     * <p>This method should be called by clients wishing to apply insets corresponding to areas
6333     * obscured by window decorations or overlays. This can include the status and navigation bars,
6334     * action bars, input methods and more. New inset categories may be added in the future.
6335     * The method returns the insets provided minus any that were applied by this view or its
6336     * children.</p>
6337     *
6338     * <p>Clients wishing to provide custom behavior should override the
6339     * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a
6340     * {@link OnApplyWindowInsetsListener} via the
6341     * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener}
6342     * method.</p>
6343     *
6344     * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method.
6345     * </p>
6346     *
6347     * @param insets Insets to apply
6348     * @return The provided insets minus the insets that were consumed
6349     */
6350    public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) {
6351        try {
6352            mPrivateFlags3 |= PFLAG3_APPLYING_INSETS;
6353            if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) {
6354                return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets);
6355            } else {
6356                return onApplyWindowInsets(insets);
6357            }
6358        } finally {
6359            mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS;
6360        }
6361    }
6362
6363    /**
6364     * @hide Compute the insets that should be consumed by this view and the ones
6365     * that should propagate to those under it.
6366     */
6367    protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) {
6368        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
6369                || mAttachInfo == null
6370                || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0
6371                        && !mAttachInfo.mOverscanRequested)) {
6372            outLocalInsets.set(inoutInsets);
6373            inoutInsets.set(0, 0, 0, 0);
6374            return true;
6375        } else {
6376            // The application wants to take care of fitting system window for
6377            // the content...  however we still need to take care of any overscan here.
6378            final Rect overscan = mAttachInfo.mOverscanInsets;
6379            outLocalInsets.set(overscan);
6380            inoutInsets.left -= overscan.left;
6381            inoutInsets.top -= overscan.top;
6382            inoutInsets.right -= overscan.right;
6383            inoutInsets.bottom -= overscan.bottom;
6384            return false;
6385        }
6386    }
6387
6388    /**
6389     * Sets whether or not this view should account for system screen decorations
6390     * such as the status bar and inset its content; that is, controlling whether
6391     * the default implementation of {@link #fitSystemWindows(Rect)} will be
6392     * executed.  See that method for more details.
6393     *
6394     * <p>Note that if you are providing your own implementation of
6395     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
6396     * flag to true -- your implementation will be overriding the default
6397     * implementation that checks this flag.
6398     *
6399     * @param fitSystemWindows If true, then the default implementation of
6400     * {@link #fitSystemWindows(Rect)} will be executed.
6401     *
6402     * @attr ref android.R.styleable#View_fitsSystemWindows
6403     * @see #getFitsSystemWindows()
6404     * @see #fitSystemWindows(Rect)
6405     * @see #setSystemUiVisibility(int)
6406     */
6407    public void setFitsSystemWindows(boolean fitSystemWindows) {
6408        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
6409    }
6410
6411    /**
6412     * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method
6413     * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)}
6414     * will be executed.
6415     *
6416     * @return {@code true} if the default implementation of
6417     * {@link #fitSystemWindows(Rect)} will be executed.
6418     *
6419     * @attr ref android.R.styleable#View_fitsSystemWindows
6420     * @see #setFitsSystemWindows(boolean)
6421     * @see #fitSystemWindows(Rect)
6422     * @see #setSystemUiVisibility(int)
6423     */
6424    public boolean getFitsSystemWindows() {
6425        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
6426    }
6427
6428    /** @hide */
6429    public boolean fitsSystemWindows() {
6430        return getFitsSystemWindows();
6431    }
6432
6433    /**
6434     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
6435     * @deprecated Use {@link #requestApplyInsets()} for newer platform versions.
6436     */
6437    public void requestFitSystemWindows() {
6438        if (mParent != null) {
6439            mParent.requestFitSystemWindows();
6440        }
6441    }
6442
6443    /**
6444     * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed.
6445     */
6446    public void requestApplyInsets() {
6447        requestFitSystemWindows();
6448    }
6449
6450    /**
6451     * For use by PhoneWindow to make its own system window fitting optional.
6452     * @hide
6453     */
6454    public void makeOptionalFitsSystemWindows() {
6455        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
6456    }
6457
6458    /**
6459     * Returns the visibility status for this view.
6460     *
6461     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
6462     * @attr ref android.R.styleable#View_visibility
6463     */
6464    @ViewDebug.ExportedProperty(mapping = {
6465        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
6466        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
6467        @ViewDebug.IntToString(from = GONE,      to = "GONE")
6468    })
6469    @Visibility
6470    public int getVisibility() {
6471        return mViewFlags & VISIBILITY_MASK;
6472    }
6473
6474    /**
6475     * Set the enabled state of this view.
6476     *
6477     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
6478     * @attr ref android.R.styleable#View_visibility
6479     */
6480    @RemotableViewMethod
6481    public void setVisibility(@Visibility int visibility) {
6482        setFlags(visibility, VISIBILITY_MASK);
6483        if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false);
6484    }
6485
6486    /**
6487     * Returns the enabled status for this view. The interpretation of the
6488     * enabled state varies by subclass.
6489     *
6490     * @return True if this view is enabled, false otherwise.
6491     */
6492    @ViewDebug.ExportedProperty
6493    public boolean isEnabled() {
6494        return (mViewFlags & ENABLED_MASK) == ENABLED;
6495    }
6496
6497    /**
6498     * Set the enabled state of this view. The interpretation of the enabled
6499     * state varies by subclass.
6500     *
6501     * @param enabled True if this view is enabled, false otherwise.
6502     */
6503    @RemotableViewMethod
6504    public void setEnabled(boolean enabled) {
6505        if (enabled == isEnabled()) return;
6506
6507        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
6508
6509        /*
6510         * The View most likely has to change its appearance, so refresh
6511         * the drawable state.
6512         */
6513        refreshDrawableState();
6514
6515        // Invalidate too, since the default behavior for views is to be
6516        // be drawn at 50% alpha rather than to change the drawable.
6517        invalidate(true);
6518
6519        if (!enabled) {
6520            cancelPendingInputEvents();
6521        }
6522    }
6523
6524    /**
6525     * Set whether this view can receive the focus.
6526     *
6527     * Setting this to false will also ensure that this view is not focusable
6528     * in touch mode.
6529     *
6530     * @param focusable If true, this view can receive the focus.
6531     *
6532     * @see #setFocusableInTouchMode(boolean)
6533     * @attr ref android.R.styleable#View_focusable
6534     */
6535    public void setFocusable(boolean focusable) {
6536        if (!focusable) {
6537            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
6538        }
6539        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
6540    }
6541
6542    /**
6543     * Set whether this view can receive focus while in touch mode.
6544     *
6545     * Setting this to true will also ensure that this view is focusable.
6546     *
6547     * @param focusableInTouchMode If true, this view can receive the focus while
6548     *   in touch mode.
6549     *
6550     * @see #setFocusable(boolean)
6551     * @attr ref android.R.styleable#View_focusableInTouchMode
6552     */
6553    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
6554        // Focusable in touch mode should always be set before the focusable flag
6555        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
6556        // which, in touch mode, will not successfully request focus on this view
6557        // because the focusable in touch mode flag is not set
6558        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
6559        if (focusableInTouchMode) {
6560            setFlags(FOCUSABLE, FOCUSABLE_MASK);
6561        }
6562    }
6563
6564    /**
6565     * Set whether this view should have sound effects enabled for events such as
6566     * clicking and touching.
6567     *
6568     * <p>You may wish to disable sound effects for a view if you already play sounds,
6569     * for instance, a dial key that plays dtmf tones.
6570     *
6571     * @param soundEffectsEnabled whether sound effects are enabled for this view.
6572     * @see #isSoundEffectsEnabled()
6573     * @see #playSoundEffect(int)
6574     * @attr ref android.R.styleable#View_soundEffectsEnabled
6575     */
6576    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
6577        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
6578    }
6579
6580    /**
6581     * @return whether this view should have sound effects enabled for events such as
6582     *     clicking and touching.
6583     *
6584     * @see #setSoundEffectsEnabled(boolean)
6585     * @see #playSoundEffect(int)
6586     * @attr ref android.R.styleable#View_soundEffectsEnabled
6587     */
6588    @ViewDebug.ExportedProperty
6589    public boolean isSoundEffectsEnabled() {
6590        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
6591    }
6592
6593    /**
6594     * Set whether this view should have haptic feedback for events such as
6595     * long presses.
6596     *
6597     * <p>You may wish to disable haptic feedback if your view already controls
6598     * its own haptic feedback.
6599     *
6600     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
6601     * @see #isHapticFeedbackEnabled()
6602     * @see #performHapticFeedback(int)
6603     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
6604     */
6605    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
6606        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
6607    }
6608
6609    /**
6610     * @return whether this view should have haptic feedback enabled for events
6611     * long presses.
6612     *
6613     * @see #setHapticFeedbackEnabled(boolean)
6614     * @see #performHapticFeedback(int)
6615     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
6616     */
6617    @ViewDebug.ExportedProperty
6618    public boolean isHapticFeedbackEnabled() {
6619        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
6620    }
6621
6622    /**
6623     * Returns the layout direction for this view.
6624     *
6625     * @return One of {@link #LAYOUT_DIRECTION_LTR},
6626     *   {@link #LAYOUT_DIRECTION_RTL},
6627     *   {@link #LAYOUT_DIRECTION_INHERIT} or
6628     *   {@link #LAYOUT_DIRECTION_LOCALE}.
6629     *
6630     * @attr ref android.R.styleable#View_layoutDirection
6631     *
6632     * @hide
6633     */
6634    @ViewDebug.ExportedProperty(category = "layout", mapping = {
6635        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
6636        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
6637        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
6638        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
6639    })
6640    @LayoutDir
6641    public int getRawLayoutDirection() {
6642        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
6643    }
6644
6645    /**
6646     * Set the layout direction for this view. This will propagate a reset of layout direction
6647     * resolution to the view's children and resolve layout direction for this view.
6648     *
6649     * @param layoutDirection the layout direction to set. Should be one of:
6650     *
6651     * {@link #LAYOUT_DIRECTION_LTR},
6652     * {@link #LAYOUT_DIRECTION_RTL},
6653     * {@link #LAYOUT_DIRECTION_INHERIT},
6654     * {@link #LAYOUT_DIRECTION_LOCALE}.
6655     *
6656     * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution
6657     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
6658     * will return the default {@link #LAYOUT_DIRECTION_LTR}.
6659     *
6660     * @attr ref android.R.styleable#View_layoutDirection
6661     */
6662    @RemotableViewMethod
6663    public void setLayoutDirection(@LayoutDir int layoutDirection) {
6664        if (getRawLayoutDirection() != layoutDirection) {
6665            // Reset the current layout direction and the resolved one
6666            mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK;
6667            resetRtlProperties();
6668            // Set the new layout direction (filtered)
6669            mPrivateFlags2 |=
6670                    ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK);
6671            // We need to resolve all RTL properties as they all depend on layout direction
6672            resolveRtlPropertiesIfNeeded();
6673            requestLayout();
6674            invalidate(true);
6675        }
6676    }
6677
6678    /**
6679     * Returns the resolved layout direction for this view.
6680     *
6681     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
6682     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
6683     *
6684     * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version
6685     * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}.
6686     *
6687     * @attr ref android.R.styleable#View_layoutDirection
6688     */
6689    @ViewDebug.ExportedProperty(category = "layout", mapping = {
6690        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
6691        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
6692    })
6693    @ResolvedLayoutDir
6694    public int getLayoutDirection() {
6695        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
6696        if (targetSdkVersion < JELLY_BEAN_MR1) {
6697            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
6698            return LAYOUT_DIRECTION_RESOLVED_DEFAULT;
6699        }
6700        return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ==
6701                PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
6702    }
6703
6704    /**
6705     * Indicates whether or not this view's layout is right-to-left. This is resolved from
6706     * layout attribute and/or the inherited value from the parent
6707     *
6708     * @return true if the layout is right-to-left.
6709     *
6710     * @hide
6711     */
6712    @ViewDebug.ExportedProperty(category = "layout")
6713    public boolean isLayoutRtl() {
6714        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
6715    }
6716
6717    /**
6718     * Indicates whether the view is currently tracking transient state that the
6719     * app should not need to concern itself with saving and restoring, but that
6720     * the framework should take special note to preserve when possible.
6721     *
6722     * <p>A view with transient state cannot be trivially rebound from an external
6723     * data source, such as an adapter binding item views in a list. This may be
6724     * because the view is performing an animation, tracking user selection
6725     * of content, or similar.</p>
6726     *
6727     * @return true if the view has transient state
6728     */
6729    @ViewDebug.ExportedProperty(category = "layout")
6730    public boolean hasTransientState() {
6731        return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE;
6732    }
6733
6734    /**
6735     * Set whether this view is currently tracking transient state that the
6736     * framework should attempt to preserve when possible. This flag is reference counted,
6737     * so every call to setHasTransientState(true) should be paired with a later call
6738     * to setHasTransientState(false).
6739     *
6740     * <p>A view with transient state cannot be trivially rebound from an external
6741     * data source, such as an adapter binding item views in a list. This may be
6742     * because the view is performing an animation, tracking user selection
6743     * of content, or similar.</p>
6744     *
6745     * @param hasTransientState true if this view has transient state
6746     */
6747    public void setHasTransientState(boolean hasTransientState) {
6748        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
6749                mTransientStateCount - 1;
6750        if (mTransientStateCount < 0) {
6751            mTransientStateCount = 0;
6752            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
6753                    "unmatched pair of setHasTransientState calls");
6754        } else if ((hasTransientState && mTransientStateCount == 1) ||
6755                (!hasTransientState && mTransientStateCount == 0)) {
6756            // update flag if we've just incremented up from 0 or decremented down to 0
6757            mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) |
6758                    (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0);
6759            if (mParent != null) {
6760                try {
6761                    mParent.childHasTransientStateChanged(this, hasTransientState);
6762                } catch (AbstractMethodError e) {
6763                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
6764                            " does not fully implement ViewParent", e);
6765                }
6766            }
6767        }
6768    }
6769
6770    /**
6771     * Returns true if this view is currently attached to a window.
6772     */
6773    public boolean isAttachedToWindow() {
6774        return mAttachInfo != null;
6775    }
6776
6777    /**
6778     * Returns true if this view has been through at least one layout since it
6779     * was last attached to or detached from a window.
6780     */
6781    public boolean isLaidOut() {
6782        return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT;
6783    }
6784
6785    /**
6786     * If this view doesn't do any drawing on its own, set this flag to
6787     * allow further optimizations. By default, this flag is not set on
6788     * View, but could be set on some View subclasses such as ViewGroup.
6789     *
6790     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
6791     * you should clear this flag.
6792     *
6793     * @param willNotDraw whether or not this View draw on its own
6794     */
6795    public void setWillNotDraw(boolean willNotDraw) {
6796        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
6797    }
6798
6799    /**
6800     * Returns whether or not this View draws on its own.
6801     *
6802     * @return true if this view has nothing to draw, false otherwise
6803     */
6804    @ViewDebug.ExportedProperty(category = "drawing")
6805    public boolean willNotDraw() {
6806        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
6807    }
6808
6809    /**
6810     * When a View's drawing cache is enabled, drawing is redirected to an
6811     * offscreen bitmap. Some views, like an ImageView, must be able to
6812     * bypass this mechanism if they already draw a single bitmap, to avoid
6813     * unnecessary usage of the memory.
6814     *
6815     * @param willNotCacheDrawing true if this view does not cache its
6816     *        drawing, false otherwise
6817     */
6818    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
6819        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
6820    }
6821
6822    /**
6823     * Returns whether or not this View can cache its drawing or not.
6824     *
6825     * @return true if this view does not cache its drawing, false otherwise
6826     */
6827    @ViewDebug.ExportedProperty(category = "drawing")
6828    public boolean willNotCacheDrawing() {
6829        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
6830    }
6831
6832    /**
6833     * Indicates whether this view reacts to click events or not.
6834     *
6835     * @return true if the view is clickable, false otherwise
6836     *
6837     * @see #setClickable(boolean)
6838     * @attr ref android.R.styleable#View_clickable
6839     */
6840    @ViewDebug.ExportedProperty
6841    public boolean isClickable() {
6842        return (mViewFlags & CLICKABLE) == CLICKABLE;
6843    }
6844
6845    /**
6846     * Enables or disables click events for this view. When a view
6847     * is clickable it will change its state to "pressed" on every click.
6848     * Subclasses should set the view clickable to visually react to
6849     * user's clicks.
6850     *
6851     * @param clickable true to make the view clickable, false otherwise
6852     *
6853     * @see #isClickable()
6854     * @attr ref android.R.styleable#View_clickable
6855     */
6856    public void setClickable(boolean clickable) {
6857        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
6858    }
6859
6860    /**
6861     * Indicates whether this view reacts to long click events or not.
6862     *
6863     * @return true if the view is long clickable, false otherwise
6864     *
6865     * @see #setLongClickable(boolean)
6866     * @attr ref android.R.styleable#View_longClickable
6867     */
6868    public boolean isLongClickable() {
6869        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
6870    }
6871
6872    /**
6873     * Enables or disables long click events for this view. When a view is long
6874     * clickable it reacts to the user holding down the button for a longer
6875     * duration than a tap. This event can either launch the listener or a
6876     * context menu.
6877     *
6878     * @param longClickable true to make the view long clickable, false otherwise
6879     * @see #isLongClickable()
6880     * @attr ref android.R.styleable#View_longClickable
6881     */
6882    public void setLongClickable(boolean longClickable) {
6883        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
6884    }
6885
6886    /**
6887     * Sets the pressed state for this view and provides a touch coordinate for
6888     * animation hinting.
6889     *
6890     * @param pressed Pass true to set the View's internal state to "pressed",
6891     *            or false to reverts the View's internal state from a
6892     *            previously set "pressed" state.
6893     * @param x The x coordinate of the touch that caused the press
6894     * @param y The y coordinate of the touch that caused the press
6895     */
6896    private void setPressed(boolean pressed, float x, float y) {
6897        if (pressed) {
6898            drawableHotspotChanged(x, y);
6899        }
6900
6901        setPressed(pressed);
6902    }
6903
6904    /**
6905     * Sets the pressed state for this view.
6906     *
6907     * @see #isClickable()
6908     * @see #setClickable(boolean)
6909     *
6910     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
6911     *        the View's internal state from a previously set "pressed" state.
6912     */
6913    public void setPressed(boolean pressed) {
6914        final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
6915
6916        if (pressed) {
6917            mPrivateFlags |= PFLAG_PRESSED;
6918        } else {
6919            mPrivateFlags &= ~PFLAG_PRESSED;
6920        }
6921
6922        if (needsRefresh) {
6923            refreshDrawableState();
6924        }
6925        dispatchSetPressed(pressed);
6926    }
6927
6928    /**
6929     * Dispatch setPressed to all of this View's children.
6930     *
6931     * @see #setPressed(boolean)
6932     *
6933     * @param pressed The new pressed state
6934     */
6935    protected void dispatchSetPressed(boolean pressed) {
6936    }
6937
6938    /**
6939     * Indicates whether the view is currently in pressed state. Unless
6940     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
6941     * the pressed state.
6942     *
6943     * @see #setPressed(boolean)
6944     * @see #isClickable()
6945     * @see #setClickable(boolean)
6946     *
6947     * @return true if the view is currently pressed, false otherwise
6948     */
6949    @ViewDebug.ExportedProperty
6950    public boolean isPressed() {
6951        return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED;
6952    }
6953
6954    /**
6955     * Indicates whether this view will save its state (that is,
6956     * whether its {@link #onSaveInstanceState} method will be called).
6957     *
6958     * @return Returns true if the view state saving is enabled, else false.
6959     *
6960     * @see #setSaveEnabled(boolean)
6961     * @attr ref android.R.styleable#View_saveEnabled
6962     */
6963    public boolean isSaveEnabled() {
6964        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
6965    }
6966
6967    /**
6968     * Controls whether the saving of this view's state is
6969     * enabled (that is, whether its {@link #onSaveInstanceState} method
6970     * will be called).  Note that even if freezing is enabled, the
6971     * view still must have an id assigned to it (via {@link #setId(int)})
6972     * for its state to be saved.  This flag can only disable the
6973     * saving of this view; any child views may still have their state saved.
6974     *
6975     * @param enabled Set to false to <em>disable</em> state saving, or true
6976     * (the default) to allow it.
6977     *
6978     * @see #isSaveEnabled()
6979     * @see #setId(int)
6980     * @see #onSaveInstanceState()
6981     * @attr ref android.R.styleable#View_saveEnabled
6982     */
6983    public void setSaveEnabled(boolean enabled) {
6984        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
6985    }
6986
6987    /**
6988     * Gets whether the framework should discard touches when the view's
6989     * window is obscured by another visible window.
6990     * Refer to the {@link View} security documentation for more details.
6991     *
6992     * @return True if touch filtering is enabled.
6993     *
6994     * @see #setFilterTouchesWhenObscured(boolean)
6995     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
6996     */
6997    @ViewDebug.ExportedProperty
6998    public boolean getFilterTouchesWhenObscured() {
6999        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
7000    }
7001
7002    /**
7003     * Sets whether the framework should discard touches when the view's
7004     * window is obscured by another visible window.
7005     * Refer to the {@link View} security documentation for more details.
7006     *
7007     * @param enabled True if touch filtering should be enabled.
7008     *
7009     * @see #getFilterTouchesWhenObscured
7010     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
7011     */
7012    public void setFilterTouchesWhenObscured(boolean enabled) {
7013        setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0,
7014                FILTER_TOUCHES_WHEN_OBSCURED);
7015    }
7016
7017    /**
7018     * Indicates whether the entire hierarchy under this view will save its
7019     * state when a state saving traversal occurs from its parent.  The default
7020     * is true; if false, these views will not be saved unless
7021     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
7022     *
7023     * @return Returns true if the view state saving from parent is enabled, else false.
7024     *
7025     * @see #setSaveFromParentEnabled(boolean)
7026     */
7027    public boolean isSaveFromParentEnabled() {
7028        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
7029    }
7030
7031    /**
7032     * Controls whether the entire hierarchy under this view will save its
7033     * state when a state saving traversal occurs from its parent.  The default
7034     * is true; if false, these views will not be saved unless
7035     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
7036     *
7037     * @param enabled Set to false to <em>disable</em> state saving, or true
7038     * (the default) to allow it.
7039     *
7040     * @see #isSaveFromParentEnabled()
7041     * @see #setId(int)
7042     * @see #onSaveInstanceState()
7043     */
7044    public void setSaveFromParentEnabled(boolean enabled) {
7045        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
7046    }
7047
7048
7049    /**
7050     * Returns whether this View is able to take focus.
7051     *
7052     * @return True if this view can take focus, or false otherwise.
7053     * @attr ref android.R.styleable#View_focusable
7054     */
7055    @ViewDebug.ExportedProperty(category = "focus")
7056    public final boolean isFocusable() {
7057        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
7058    }
7059
7060    /**
7061     * When a view is focusable, it may not want to take focus when in touch mode.
7062     * For example, a button would like focus when the user is navigating via a D-pad
7063     * so that the user can click on it, but once the user starts touching the screen,
7064     * the button shouldn't take focus
7065     * @return Whether the view is focusable in touch mode.
7066     * @attr ref android.R.styleable#View_focusableInTouchMode
7067     */
7068    @ViewDebug.ExportedProperty
7069    public final boolean isFocusableInTouchMode() {
7070        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
7071    }
7072
7073    /**
7074     * Find the nearest view in the specified direction that can take focus.
7075     * This does not actually give focus to that view.
7076     *
7077     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
7078     *
7079     * @return The nearest focusable in the specified direction, or null if none
7080     *         can be found.
7081     */
7082    public View focusSearch(@FocusRealDirection int direction) {
7083        if (mParent != null) {
7084            return mParent.focusSearch(this, direction);
7085        } else {
7086            return null;
7087        }
7088    }
7089
7090    /**
7091     * This method is the last chance for the focused view and its ancestors to
7092     * respond to an arrow key. This is called when the focused view did not
7093     * consume the key internally, nor could the view system find a new view in
7094     * the requested direction to give focus to.
7095     *
7096     * @param focused The currently focused view.
7097     * @param direction The direction focus wants to move. One of FOCUS_UP,
7098     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
7099     * @return True if the this view consumed this unhandled move.
7100     */
7101    public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) {
7102        return false;
7103    }
7104
7105    /**
7106     * If a user manually specified the next view id for a particular direction,
7107     * use the root to look up the view.
7108     * @param root The root view of the hierarchy containing this view.
7109     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
7110     * or FOCUS_BACKWARD.
7111     * @return The user specified next view, or null if there is none.
7112     */
7113    View findUserSetNextFocus(View root, @FocusDirection int direction) {
7114        switch (direction) {
7115            case FOCUS_LEFT:
7116                if (mNextFocusLeftId == View.NO_ID) return null;
7117                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
7118            case FOCUS_RIGHT:
7119                if (mNextFocusRightId == View.NO_ID) return null;
7120                return findViewInsideOutShouldExist(root, mNextFocusRightId);
7121            case FOCUS_UP:
7122                if (mNextFocusUpId == View.NO_ID) return null;
7123                return findViewInsideOutShouldExist(root, mNextFocusUpId);
7124            case FOCUS_DOWN:
7125                if (mNextFocusDownId == View.NO_ID) return null;
7126                return findViewInsideOutShouldExist(root, mNextFocusDownId);
7127            case FOCUS_FORWARD:
7128                if (mNextFocusForwardId == View.NO_ID) return null;
7129                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
7130            case FOCUS_BACKWARD: {
7131                if (mID == View.NO_ID) return null;
7132                final int id = mID;
7133                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
7134                    @Override
7135                    public boolean apply(View t) {
7136                        return t.mNextFocusForwardId == id;
7137                    }
7138                });
7139            }
7140        }
7141        return null;
7142    }
7143
7144    private View findViewInsideOutShouldExist(View root, int id) {
7145        if (mMatchIdPredicate == null) {
7146            mMatchIdPredicate = new MatchIdPredicate();
7147        }
7148        mMatchIdPredicate.mId = id;
7149        View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate);
7150        if (result == null) {
7151            Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id);
7152        }
7153        return result;
7154    }
7155
7156    /**
7157     * Find and return all focusable views that are descendants of this view,
7158     * possibly including this view if it is focusable itself.
7159     *
7160     * @param direction The direction of the focus
7161     * @return A list of focusable views
7162     */
7163    public ArrayList<View> getFocusables(@FocusDirection int direction) {
7164        ArrayList<View> result = new ArrayList<View>(24);
7165        addFocusables(result, direction);
7166        return result;
7167    }
7168
7169    /**
7170     * Add any focusable views that are descendants of this view (possibly
7171     * including this view if it is focusable itself) to views.  If we are in touch mode,
7172     * only add views that are also focusable in touch mode.
7173     *
7174     * @param views Focusable views found so far
7175     * @param direction The direction of the focus
7176     */
7177    public void addFocusables(ArrayList<View> views, @FocusDirection int direction) {
7178        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
7179    }
7180
7181    /**
7182     * Adds any focusable views that are descendants of this view (possibly
7183     * including this view if it is focusable itself) to views. This method
7184     * adds all focusable views regardless if we are in touch mode or
7185     * only views focusable in touch mode if we are in touch mode or
7186     * only views that can take accessibility focus if accessibility is enabeld
7187     * depending on the focusable mode paramater.
7188     *
7189     * @param views Focusable views found so far or null if all we are interested is
7190     *        the number of focusables.
7191     * @param direction The direction of the focus.
7192     * @param focusableMode The type of focusables to be added.
7193     *
7194     * @see #FOCUSABLES_ALL
7195     * @see #FOCUSABLES_TOUCH_MODE
7196     */
7197    public void addFocusables(ArrayList<View> views, @FocusDirection int direction,
7198            @FocusableMode int focusableMode) {
7199        if (views == null) {
7200            return;
7201        }
7202        if (!isFocusable()) {
7203            return;
7204        }
7205        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
7206                && isInTouchMode() && !isFocusableInTouchMode()) {
7207            return;
7208        }
7209        views.add(this);
7210    }
7211
7212    /**
7213     * Finds the Views that contain given text. The containment is case insensitive.
7214     * The search is performed by either the text that the View renders or the content
7215     * description that describes the view for accessibility purposes and the view does
7216     * not render or both. Clients can specify how the search is to be performed via
7217     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
7218     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
7219     *
7220     * @param outViews The output list of matching Views.
7221     * @param searched The text to match against.
7222     *
7223     * @see #FIND_VIEWS_WITH_TEXT
7224     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
7225     * @see #setContentDescription(CharSequence)
7226     */
7227    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched,
7228            @FindViewFlags int flags) {
7229        if (getAccessibilityNodeProvider() != null) {
7230            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
7231                outViews.add(this);
7232            }
7233        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
7234                && (searched != null && searched.length() > 0)
7235                && (mContentDescription != null && mContentDescription.length() > 0)) {
7236            String searchedLowerCase = searched.toString().toLowerCase();
7237            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
7238            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
7239                outViews.add(this);
7240            }
7241        }
7242    }
7243
7244    /**
7245     * Find and return all touchable views that are descendants of this view,
7246     * possibly including this view if it is touchable itself.
7247     *
7248     * @return A list of touchable views
7249     */
7250    public ArrayList<View> getTouchables() {
7251        ArrayList<View> result = new ArrayList<View>();
7252        addTouchables(result);
7253        return result;
7254    }
7255
7256    /**
7257     * Add any touchable views that are descendants of this view (possibly
7258     * including this view if it is touchable itself) to views.
7259     *
7260     * @param views Touchable views found so far
7261     */
7262    public void addTouchables(ArrayList<View> views) {
7263        final int viewFlags = mViewFlags;
7264
7265        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
7266                && (viewFlags & ENABLED_MASK) == ENABLED) {
7267            views.add(this);
7268        }
7269    }
7270
7271    /**
7272     * Returns whether this View is accessibility focused.
7273     *
7274     * @return True if this View is accessibility focused.
7275     */
7276    public boolean isAccessibilityFocused() {
7277        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
7278    }
7279
7280    /**
7281     * Call this to try to give accessibility focus to this view.
7282     *
7283     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
7284     * returns false or the view is no visible or the view already has accessibility
7285     * focus.
7286     *
7287     * See also {@link #focusSearch(int)}, which is what you call to say that you
7288     * have focus, and you want your parent to look for the next one.
7289     *
7290     * @return Whether this view actually took accessibility focus.
7291     *
7292     * @hide
7293     */
7294    public boolean requestAccessibilityFocus() {
7295        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
7296        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
7297            return false;
7298        }
7299        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
7300            return false;
7301        }
7302        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
7303            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
7304            ViewRootImpl viewRootImpl = getViewRootImpl();
7305            if (viewRootImpl != null) {
7306                viewRootImpl.setAccessibilityFocus(this, null);
7307            }
7308            invalidate();
7309            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
7310            return true;
7311        }
7312        return false;
7313    }
7314
7315    /**
7316     * Call this to try to clear accessibility focus of this view.
7317     *
7318     * See also {@link #focusSearch(int)}, which is what you call to say that you
7319     * have focus, and you want your parent to look for the next one.
7320     *
7321     * @hide
7322     */
7323    public void clearAccessibilityFocus() {
7324        clearAccessibilityFocusNoCallbacks();
7325        // Clear the global reference of accessibility focus if this
7326        // view or any of its descendants had accessibility focus.
7327        ViewRootImpl viewRootImpl = getViewRootImpl();
7328        if (viewRootImpl != null) {
7329            View focusHost = viewRootImpl.getAccessibilityFocusedHost();
7330            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
7331                viewRootImpl.setAccessibilityFocus(null, null);
7332            }
7333        }
7334    }
7335
7336    private void sendAccessibilityHoverEvent(int eventType) {
7337        // Since we are not delivering to a client accessibility events from not
7338        // important views (unless the clinet request that) we need to fire the
7339        // event from the deepest view exposed to the client. As a consequence if
7340        // the user crosses a not exposed view the client will see enter and exit
7341        // of the exposed predecessor followed by and enter and exit of that same
7342        // predecessor when entering and exiting the not exposed descendant. This
7343        // is fine since the client has a clear idea which view is hovered at the
7344        // price of a couple more events being sent. This is a simple and
7345        // working solution.
7346        View source = this;
7347        while (true) {
7348            if (source.includeForAccessibility()) {
7349                source.sendAccessibilityEvent(eventType);
7350                return;
7351            }
7352            ViewParent parent = source.getParent();
7353            if (parent instanceof View) {
7354                source = (View) parent;
7355            } else {
7356                return;
7357            }
7358        }
7359    }
7360
7361    /**
7362     * Clears accessibility focus without calling any callback methods
7363     * normally invoked in {@link #clearAccessibilityFocus()}. This method
7364     * is used for clearing accessibility focus when giving this focus to
7365     * another view.
7366     */
7367    void clearAccessibilityFocusNoCallbacks() {
7368        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
7369            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
7370            invalidate();
7371            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
7372        }
7373    }
7374
7375    /**
7376     * Call this to try to give focus to a specific view or to one of its
7377     * descendants.
7378     *
7379     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7380     * false), or if it is focusable and it is not focusable in touch mode
7381     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7382     *
7383     * See also {@link #focusSearch(int)}, which is what you call to say that you
7384     * have focus, and you want your parent to look for the next one.
7385     *
7386     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
7387     * {@link #FOCUS_DOWN} and <code>null</code>.
7388     *
7389     * @return Whether this view or one of its descendants actually took focus.
7390     */
7391    public final boolean requestFocus() {
7392        return requestFocus(View.FOCUS_DOWN);
7393    }
7394
7395    /**
7396     * Call this to try to give focus to a specific view or to one of its
7397     * descendants and give it a hint about what direction focus is heading.
7398     *
7399     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7400     * false), or if it is focusable and it is not focusable in touch mode
7401     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7402     *
7403     * See also {@link #focusSearch(int)}, which is what you call to say that you
7404     * have focus, and you want your parent to look for the next one.
7405     *
7406     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
7407     * <code>null</code> set for the previously focused rectangle.
7408     *
7409     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
7410     * @return Whether this view or one of its descendants actually took focus.
7411     */
7412    public final boolean requestFocus(int direction) {
7413        return requestFocus(direction, null);
7414    }
7415
7416    /**
7417     * Call this to try to give focus to a specific view or to one of its descendants
7418     * and give it hints about the direction and a specific rectangle that the focus
7419     * is coming from.  The rectangle can help give larger views a finer grained hint
7420     * about where focus is coming from, and therefore, where to show selection, or
7421     * forward focus change internally.
7422     *
7423     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7424     * false), or if it is focusable and it is not focusable in touch mode
7425     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7426     *
7427     * A View will not take focus if it is not visible.
7428     *
7429     * A View will not take focus if one of its parents has
7430     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
7431     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
7432     *
7433     * See also {@link #focusSearch(int)}, which is what you call to say that you
7434     * have focus, and you want your parent to look for the next one.
7435     *
7436     * You may wish to override this method if your custom {@link View} has an internal
7437     * {@link View} that it wishes to forward the request to.
7438     *
7439     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
7440     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
7441     *        to give a finer grained hint about where focus is coming from.  May be null
7442     *        if there is no hint.
7443     * @return Whether this view or one of its descendants actually took focus.
7444     */
7445    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
7446        return requestFocusNoSearch(direction, previouslyFocusedRect);
7447    }
7448
7449    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
7450        // need to be focusable
7451        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
7452                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
7453            return false;
7454        }
7455
7456        // need to be focusable in touch mode if in touch mode
7457        if (isInTouchMode() &&
7458            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
7459               return false;
7460        }
7461
7462        // need to not have any parents blocking us
7463        if (hasAncestorThatBlocksDescendantFocus()) {
7464            return false;
7465        }
7466
7467        handleFocusGainInternal(direction, previouslyFocusedRect);
7468        return true;
7469    }
7470
7471    /**
7472     * Call this to try to give focus to a specific view or to one of its descendants. This is a
7473     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
7474     * touch mode to request focus when they are touched.
7475     *
7476     * @return Whether this view or one of its descendants actually took focus.
7477     *
7478     * @see #isInTouchMode()
7479     *
7480     */
7481    public final boolean requestFocusFromTouch() {
7482        // Leave touch mode if we need to
7483        if (isInTouchMode()) {
7484            ViewRootImpl viewRoot = getViewRootImpl();
7485            if (viewRoot != null) {
7486                viewRoot.ensureTouchMode(false);
7487            }
7488        }
7489        return requestFocus(View.FOCUS_DOWN);
7490    }
7491
7492    /**
7493     * @return Whether any ancestor of this view blocks descendant focus.
7494     */
7495    private boolean hasAncestorThatBlocksDescendantFocus() {
7496        final boolean focusableInTouchMode = isFocusableInTouchMode();
7497        ViewParent ancestor = mParent;
7498        while (ancestor instanceof ViewGroup) {
7499            final ViewGroup vgAncestor = (ViewGroup) ancestor;
7500            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS
7501                    || (!focusableInTouchMode && vgAncestor.shouldBlockFocusForTouchscreen())) {
7502                return true;
7503            } else {
7504                ancestor = vgAncestor.getParent();
7505            }
7506        }
7507        return false;
7508    }
7509
7510    /**
7511     * Gets the mode for determining whether this View is important for accessibility
7512     * which is if it fires accessibility events and if it is reported to
7513     * accessibility services that query the screen.
7514     *
7515     * @return The mode for determining whether a View is important for accessibility.
7516     *
7517     * @attr ref android.R.styleable#View_importantForAccessibility
7518     *
7519     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
7520     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
7521     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
7522     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
7523     */
7524    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
7525            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
7526            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
7527            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"),
7528            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS,
7529                    to = "noHideDescendants")
7530        })
7531    public int getImportantForAccessibility() {
7532        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
7533                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
7534    }
7535
7536    /**
7537     * Sets the live region mode for this view. This indicates to accessibility
7538     * services whether they should automatically notify the user about changes
7539     * to the view's content description or text, or to the content descriptions
7540     * or text of the view's children (where applicable).
7541     * <p>
7542     * For example, in a login screen with a TextView that displays an "incorrect
7543     * password" notification, that view should be marked as a live region with
7544     * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
7545     * <p>
7546     * To disable change notifications for this view, use
7547     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region
7548     * mode for most views.
7549     * <p>
7550     * To indicate that the user should be notified of changes, use
7551     * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
7552     * <p>
7553     * If the view's changes should interrupt ongoing speech and notify the user
7554     * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}.
7555     *
7556     * @param mode The live region mode for this view, one of:
7557     *        <ul>
7558     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE}
7559     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE}
7560     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}
7561     *        </ul>
7562     * @attr ref android.R.styleable#View_accessibilityLiveRegion
7563     */
7564    public void setAccessibilityLiveRegion(int mode) {
7565        if (mode != getAccessibilityLiveRegion()) {
7566            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
7567            mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT)
7568                    & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
7569            notifyViewAccessibilityStateChangedIfNeeded(
7570                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7571        }
7572    }
7573
7574    /**
7575     * Gets the live region mode for this View.
7576     *
7577     * @return The live region mode for the view.
7578     *
7579     * @attr ref android.R.styleable#View_accessibilityLiveRegion
7580     *
7581     * @see #setAccessibilityLiveRegion(int)
7582     */
7583    public int getAccessibilityLiveRegion() {
7584        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK)
7585                >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
7586    }
7587
7588    /**
7589     * Sets how to determine whether this view is important for accessibility
7590     * which is if it fires accessibility events and if it is reported to
7591     * accessibility services that query the screen.
7592     *
7593     * @param mode How to determine whether this view is important for accessibility.
7594     *
7595     * @attr ref android.R.styleable#View_importantForAccessibility
7596     *
7597     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
7598     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
7599     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
7600     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
7601     */
7602    public void setImportantForAccessibility(int mode) {
7603        final int oldMode = getImportantForAccessibility();
7604        if (mode != oldMode) {
7605            // If we're moving between AUTO and another state, we might not need
7606            // to send a subtree changed notification. We'll store the computed
7607            // importance, since we'll need to check it later to make sure.
7608            final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO
7609                    || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO;
7610            final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility();
7611            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
7612            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
7613                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
7614            if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) {
7615                notifySubtreeAccessibilityStateChangedIfNeeded();
7616            } else {
7617                notifyViewAccessibilityStateChangedIfNeeded(
7618                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7619            }
7620        }
7621    }
7622
7623    /**
7624     * Computes whether this view should be exposed for accessibility. In
7625     * general, views that are interactive or provide information are exposed
7626     * while views that serve only as containers are hidden.
7627     * <p>
7628     * If an ancestor of this view has importance
7629     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method
7630     * returns <code>false</code>.
7631     * <p>
7632     * Otherwise, the value is computed according to the view's
7633     * {@link #getImportantForAccessibility()} value:
7634     * <ol>
7635     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or
7636     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false
7637     * </code>
7638     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code>
7639     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if
7640     * view satisfies any of the following:
7641     * <ul>
7642     * <li>Is actionable, e.g. {@link #isClickable()},
7643     * {@link #isLongClickable()}, or {@link #isFocusable()}
7644     * <li>Has an {@link AccessibilityDelegate}
7645     * <li>Has an interaction listener, e.g. {@link OnTouchListener},
7646     * {@link OnKeyListener}, etc.
7647     * <li>Is an accessibility live region, e.g.
7648     * {@link #getAccessibilityLiveRegion()} is not
7649     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}.
7650     * </ul>
7651     * </ol>
7652     *
7653     * @return Whether the view is exposed for accessibility.
7654     * @see #setImportantForAccessibility(int)
7655     * @see #getImportantForAccessibility()
7656     */
7657    public boolean isImportantForAccessibility() {
7658        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
7659                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
7660        if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO
7661                || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
7662            return false;
7663        }
7664
7665        // Check parent mode to ensure we're not hidden.
7666        ViewParent parent = mParent;
7667        while (parent instanceof View) {
7668            if (((View) parent).getImportantForAccessibility()
7669                    == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
7670                return false;
7671            }
7672            parent = parent.getParent();
7673        }
7674
7675        return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility()
7676                || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null
7677                || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE;
7678    }
7679
7680    /**
7681     * Gets the parent for accessibility purposes. Note that the parent for
7682     * accessibility is not necessary the immediate parent. It is the first
7683     * predecessor that is important for accessibility.
7684     *
7685     * @return The parent for accessibility purposes.
7686     */
7687    public ViewParent getParentForAccessibility() {
7688        if (mParent instanceof View) {
7689            View parentView = (View) mParent;
7690            if (parentView.includeForAccessibility()) {
7691                return mParent;
7692            } else {
7693                return mParent.getParentForAccessibility();
7694            }
7695        }
7696        return null;
7697    }
7698
7699    /**
7700     * Adds the children of a given View for accessibility. Since some Views are
7701     * not important for accessibility the children for accessibility are not
7702     * necessarily direct children of the view, rather they are the first level of
7703     * descendants important for accessibility.
7704     *
7705     * @param children The list of children for accessibility.
7706     */
7707    public void addChildrenForAccessibility(ArrayList<View> children) {
7708
7709    }
7710
7711    /**
7712     * Whether to regard this view for accessibility. A view is regarded for
7713     * accessibility if it is important for accessibility or the querying
7714     * accessibility service has explicitly requested that view not
7715     * important for accessibility are regarded.
7716     *
7717     * @return Whether to regard the view for accessibility.
7718     *
7719     * @hide
7720     */
7721    public boolean includeForAccessibility() {
7722        if (mAttachInfo != null) {
7723            return (mAttachInfo.mAccessibilityFetchFlags
7724                    & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0
7725                    || isImportantForAccessibility();
7726        }
7727        return false;
7728    }
7729
7730    /**
7731     * Returns whether the View is considered actionable from
7732     * accessibility perspective. Such view are important for
7733     * accessibility.
7734     *
7735     * @return True if the view is actionable for accessibility.
7736     *
7737     * @hide
7738     */
7739    public boolean isActionableForAccessibility() {
7740        return (isClickable() || isLongClickable() || isFocusable());
7741    }
7742
7743    /**
7744     * Returns whether the View has registered callbacks which makes it
7745     * important for accessibility.
7746     *
7747     * @return True if the view is actionable for accessibility.
7748     */
7749    private boolean hasListenersForAccessibility() {
7750        ListenerInfo info = getListenerInfo();
7751        return mTouchDelegate != null || info.mOnKeyListener != null
7752                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
7753                || info.mOnHoverListener != null || info.mOnDragListener != null;
7754    }
7755
7756    /**
7757     * Notifies that the accessibility state of this view changed. The change
7758     * is local to this view and does not represent structural changes such
7759     * as children and parent. For example, the view became focusable. The
7760     * notification is at at most once every
7761     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
7762     * to avoid unnecessary load to the system. Also once a view has a pending
7763     * notification this method is a NOP until the notification has been sent.
7764     *
7765     * @hide
7766     */
7767    public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) {
7768        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
7769            return;
7770        }
7771        if (mSendViewStateChangedAccessibilityEvent == null) {
7772            mSendViewStateChangedAccessibilityEvent =
7773                    new SendViewStateChangedAccessibilityEvent();
7774        }
7775        mSendViewStateChangedAccessibilityEvent.runOrPost(changeType);
7776    }
7777
7778    /**
7779     * Notifies that the accessibility state of this view changed. The change
7780     * is *not* local to this view and does represent structural changes such
7781     * as children and parent. For example, the view size changed. The
7782     * notification is at at most once every
7783     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
7784     * to avoid unnecessary load to the system. Also once a view has a pending
7785     * notification this method is a NOP until the notification has been sent.
7786     *
7787     * @hide
7788     */
7789    public void notifySubtreeAccessibilityStateChangedIfNeeded() {
7790        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
7791            return;
7792        }
7793        if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) {
7794            mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
7795            if (mParent != null) {
7796                try {
7797                    mParent.notifySubtreeAccessibilityStateChanged(
7798                            this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
7799                } catch (AbstractMethodError e) {
7800                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
7801                            " does not fully implement ViewParent", e);
7802                }
7803            }
7804        }
7805    }
7806
7807    /**
7808     * Reset the flag indicating the accessibility state of the subtree rooted
7809     * at this view changed.
7810     */
7811    void resetSubtreeAccessibilityStateChanged() {
7812        mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
7813    }
7814
7815    /**
7816     * Performs the specified accessibility action on the view. For
7817     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
7818     * <p>
7819     * If an {@link AccessibilityDelegate} has been specified via calling
7820     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
7821     * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
7822     * is responsible for handling this call.
7823     * </p>
7824     *
7825     * @param action The action to perform.
7826     * @param arguments Optional action arguments.
7827     * @return Whether the action was performed.
7828     */
7829    public boolean performAccessibilityAction(int action, Bundle arguments) {
7830      if (mAccessibilityDelegate != null) {
7831          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
7832      } else {
7833          return performAccessibilityActionInternal(action, arguments);
7834      }
7835    }
7836
7837   /**
7838    * @see #performAccessibilityAction(int, Bundle)
7839    *
7840    * Note: Called from the default {@link AccessibilityDelegate}.
7841    */
7842    boolean performAccessibilityActionInternal(int action, Bundle arguments) {
7843        switch (action) {
7844            case AccessibilityNodeInfo.ACTION_CLICK: {
7845                if (isClickable()) {
7846                    performClick();
7847                    return true;
7848                }
7849            } break;
7850            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
7851                if (isLongClickable()) {
7852                    performLongClick();
7853                    return true;
7854                }
7855            } break;
7856            case AccessibilityNodeInfo.ACTION_FOCUS: {
7857                if (!hasFocus()) {
7858                    // Get out of touch mode since accessibility
7859                    // wants to move focus around.
7860                    getViewRootImpl().ensureTouchMode(false);
7861                    return requestFocus();
7862                }
7863            } break;
7864            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
7865                if (hasFocus()) {
7866                    clearFocus();
7867                    return !isFocused();
7868                }
7869            } break;
7870            case AccessibilityNodeInfo.ACTION_SELECT: {
7871                if (!isSelected()) {
7872                    setSelected(true);
7873                    return isSelected();
7874                }
7875            } break;
7876            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
7877                if (isSelected()) {
7878                    setSelected(false);
7879                    return !isSelected();
7880                }
7881            } break;
7882            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
7883                if (!isAccessibilityFocused()) {
7884                    return requestAccessibilityFocus();
7885                }
7886            } break;
7887            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
7888                if (isAccessibilityFocused()) {
7889                    clearAccessibilityFocus();
7890                    return true;
7891                }
7892            } break;
7893            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
7894                if (arguments != null) {
7895                    final int granularity = arguments.getInt(
7896                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
7897                    final boolean extendSelection = arguments.getBoolean(
7898                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
7899                    return traverseAtGranularity(granularity, true, extendSelection);
7900                }
7901            } break;
7902            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
7903                if (arguments != null) {
7904                    final int granularity = arguments.getInt(
7905                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
7906                    final boolean extendSelection = arguments.getBoolean(
7907                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
7908                    return traverseAtGranularity(granularity, false, extendSelection);
7909                }
7910            } break;
7911            case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
7912                CharSequence text = getIterableTextForAccessibility();
7913                if (text == null) {
7914                    return false;
7915                }
7916                final int start = (arguments != null) ? arguments.getInt(
7917                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1;
7918                final int end = (arguments != null) ? arguments.getInt(
7919                AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1;
7920                // Only cursor position can be specified (selection length == 0)
7921                if ((getAccessibilitySelectionStart() != start
7922                        || getAccessibilitySelectionEnd() != end)
7923                        && (start == end)) {
7924                    setAccessibilitySelection(start, end);
7925                    notifyViewAccessibilityStateChangedIfNeeded(
7926                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7927                    return true;
7928                }
7929            } break;
7930        }
7931        return false;
7932    }
7933
7934    private boolean traverseAtGranularity(int granularity, boolean forward,
7935            boolean extendSelection) {
7936        CharSequence text = getIterableTextForAccessibility();
7937        if (text == null || text.length() == 0) {
7938            return false;
7939        }
7940        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
7941        if (iterator == null) {
7942            return false;
7943        }
7944        int current = getAccessibilitySelectionEnd();
7945        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7946            current = forward ? 0 : text.length();
7947        }
7948        final int[] range = forward ? iterator.following(current) : iterator.preceding(current);
7949        if (range == null) {
7950            return false;
7951        }
7952        final int segmentStart = range[0];
7953        final int segmentEnd = range[1];
7954        int selectionStart;
7955        int selectionEnd;
7956        if (extendSelection && isAccessibilitySelectionExtendable()) {
7957            selectionStart = getAccessibilitySelectionStart();
7958            if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7959                selectionStart = forward ? segmentStart : segmentEnd;
7960            }
7961            selectionEnd = forward ? segmentEnd : segmentStart;
7962        } else {
7963            selectionStart = selectionEnd= forward ? segmentEnd : segmentStart;
7964        }
7965        setAccessibilitySelection(selectionStart, selectionEnd);
7966        final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY
7967                : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY;
7968        sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd);
7969        return true;
7970    }
7971
7972    /**
7973     * Gets the text reported for accessibility purposes.
7974     *
7975     * @return The accessibility text.
7976     *
7977     * @hide
7978     */
7979    public CharSequence getIterableTextForAccessibility() {
7980        return getContentDescription();
7981    }
7982
7983    /**
7984     * Gets whether accessibility selection can be extended.
7985     *
7986     * @return If selection is extensible.
7987     *
7988     * @hide
7989     */
7990    public boolean isAccessibilitySelectionExtendable() {
7991        return false;
7992    }
7993
7994    /**
7995     * @hide
7996     */
7997    public int getAccessibilitySelectionStart() {
7998        return mAccessibilityCursorPosition;
7999    }
8000
8001    /**
8002     * @hide
8003     */
8004    public int getAccessibilitySelectionEnd() {
8005        return getAccessibilitySelectionStart();
8006    }
8007
8008    /**
8009     * @hide
8010     */
8011    public void setAccessibilitySelection(int start, int end) {
8012        if (start ==  end && end == mAccessibilityCursorPosition) {
8013            return;
8014        }
8015        if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) {
8016            mAccessibilityCursorPosition = start;
8017        } else {
8018            mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
8019        }
8020        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
8021    }
8022
8023    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
8024            int fromIndex, int toIndex) {
8025        if (mParent == null) {
8026            return;
8027        }
8028        AccessibilityEvent event = AccessibilityEvent.obtain(
8029                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
8030        onInitializeAccessibilityEvent(event);
8031        onPopulateAccessibilityEvent(event);
8032        event.setFromIndex(fromIndex);
8033        event.setToIndex(toIndex);
8034        event.setAction(action);
8035        event.setMovementGranularity(granularity);
8036        mParent.requestSendAccessibilityEvent(this, event);
8037    }
8038
8039    /**
8040     * @hide
8041     */
8042    public TextSegmentIterator getIteratorForGranularity(int granularity) {
8043        switch (granularity) {
8044            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
8045                CharSequence text = getIterableTextForAccessibility();
8046                if (text != null && text.length() > 0) {
8047                    CharacterTextSegmentIterator iterator =
8048                        CharacterTextSegmentIterator.getInstance(
8049                                mContext.getResources().getConfiguration().locale);
8050                    iterator.initialize(text.toString());
8051                    return iterator;
8052                }
8053            } break;
8054            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
8055                CharSequence text = getIterableTextForAccessibility();
8056                if (text != null && text.length() > 0) {
8057                    WordTextSegmentIterator iterator =
8058                        WordTextSegmentIterator.getInstance(
8059                                mContext.getResources().getConfiguration().locale);
8060                    iterator.initialize(text.toString());
8061                    return iterator;
8062                }
8063            } break;
8064            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
8065                CharSequence text = getIterableTextForAccessibility();
8066                if (text != null && text.length() > 0) {
8067                    ParagraphTextSegmentIterator iterator =
8068                        ParagraphTextSegmentIterator.getInstance();
8069                    iterator.initialize(text.toString());
8070                    return iterator;
8071                }
8072            } break;
8073        }
8074        return null;
8075    }
8076
8077    /**
8078     * @hide
8079     */
8080    public void dispatchStartTemporaryDetach() {
8081        onStartTemporaryDetach();
8082    }
8083
8084    /**
8085     * This is called when a container is going to temporarily detach a child, with
8086     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
8087     * It will either be followed by {@link #onFinishTemporaryDetach()} or
8088     * {@link #onDetachedFromWindow()} when the container is done.
8089     */
8090    public void onStartTemporaryDetach() {
8091        removeUnsetPressCallback();
8092        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
8093    }
8094
8095    /**
8096     * @hide
8097     */
8098    public void dispatchFinishTemporaryDetach() {
8099        onFinishTemporaryDetach();
8100    }
8101
8102    /**
8103     * Called after {@link #onStartTemporaryDetach} when the container is done
8104     * changing the view.
8105     */
8106    public void onFinishTemporaryDetach() {
8107    }
8108
8109    /**
8110     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
8111     * for this view's window.  Returns null if the view is not currently attached
8112     * to the window.  Normally you will not need to use this directly, but
8113     * just use the standard high-level event callbacks like
8114     * {@link #onKeyDown(int, KeyEvent)}.
8115     */
8116    public KeyEvent.DispatcherState getKeyDispatcherState() {
8117        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
8118    }
8119
8120    /**
8121     * Dispatch a key event before it is processed by any input method
8122     * associated with the view hierarchy.  This can be used to intercept
8123     * key events in special situations before the IME consumes them; a
8124     * typical example would be handling the BACK key to update the application's
8125     * UI instead of allowing the IME to see it and close itself.
8126     *
8127     * @param event The key event to be dispatched.
8128     * @return True if the event was handled, false otherwise.
8129     */
8130    public boolean dispatchKeyEventPreIme(KeyEvent event) {
8131        return onKeyPreIme(event.getKeyCode(), event);
8132    }
8133
8134    /**
8135     * Dispatch a key event to the next view on the focus path. This path runs
8136     * from the top of the view tree down to the currently focused view. If this
8137     * view has focus, it will dispatch to itself. Otherwise it will dispatch
8138     * the next node down the focus path. This method also fires any key
8139     * listeners.
8140     *
8141     * @param event The key event to be dispatched.
8142     * @return True if the event was handled, false otherwise.
8143     */
8144    public boolean dispatchKeyEvent(KeyEvent event) {
8145        if (mInputEventConsistencyVerifier != null) {
8146            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
8147        }
8148
8149        // Give any attached key listener a first crack at the event.
8150        //noinspection SimplifiableIfStatement
8151        ListenerInfo li = mListenerInfo;
8152        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
8153                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
8154            return true;
8155        }
8156
8157        if (event.dispatch(this, mAttachInfo != null
8158                ? mAttachInfo.mKeyDispatchState : null, this)) {
8159            return true;
8160        }
8161
8162        if (mInputEventConsistencyVerifier != null) {
8163            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8164        }
8165        return false;
8166    }
8167
8168    /**
8169     * Dispatches a key shortcut event.
8170     *
8171     * @param event The key event to be dispatched.
8172     * @return True if the event was handled by the view, false otherwise.
8173     */
8174    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
8175        return onKeyShortcut(event.getKeyCode(), event);
8176    }
8177
8178    /**
8179     * Pass the touch screen motion event down to the target view, or this
8180     * view if it is the target.
8181     *
8182     * @param event The motion event to be dispatched.
8183     * @return True if the event was handled by the view, false otherwise.
8184     */
8185    public boolean dispatchTouchEvent(MotionEvent event) {
8186        boolean result = false;
8187
8188        if (mInputEventConsistencyVerifier != null) {
8189            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
8190        }
8191
8192        final int actionMasked = event.getActionMasked();
8193        if (actionMasked == MotionEvent.ACTION_DOWN) {
8194            // Defensive cleanup for new gesture
8195            stopNestedScroll();
8196        }
8197
8198        if (onFilterTouchEventForSecurity(event)) {
8199            //noinspection SimplifiableIfStatement
8200            ListenerInfo li = mListenerInfo;
8201            if (li != null && li.mOnTouchListener != null
8202                    && (mViewFlags & ENABLED_MASK) == ENABLED
8203                    && li.mOnTouchListener.onTouch(this, event)) {
8204                result = true;
8205            }
8206
8207            if (!result && onTouchEvent(event)) {
8208                result = true;
8209            }
8210        }
8211
8212        if (!result && mInputEventConsistencyVerifier != null) {
8213            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8214        }
8215
8216        // Clean up after nested scrolls if this is the end of a gesture;
8217        // also cancel it if we tried an ACTION_DOWN but we didn't want the rest
8218        // of the gesture.
8219        if (actionMasked == MotionEvent.ACTION_UP ||
8220                actionMasked == MotionEvent.ACTION_CANCEL ||
8221                (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
8222            stopNestedScroll();
8223        }
8224
8225        return result;
8226    }
8227
8228    /**
8229     * Filter the touch event to apply security policies.
8230     *
8231     * @param event The motion event to be filtered.
8232     * @return True if the event should be dispatched, false if the event should be dropped.
8233     *
8234     * @see #getFilterTouchesWhenObscured
8235     */
8236    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
8237        //noinspection RedundantIfStatement
8238        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
8239                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
8240            // Window is obscured, drop this touch.
8241            return false;
8242        }
8243        return true;
8244    }
8245
8246    /**
8247     * Pass a trackball motion event down to the focused view.
8248     *
8249     * @param event The motion event to be dispatched.
8250     * @return True if the event was handled by the view, false otherwise.
8251     */
8252    public boolean dispatchTrackballEvent(MotionEvent event) {
8253        if (mInputEventConsistencyVerifier != null) {
8254            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
8255        }
8256
8257        return onTrackballEvent(event);
8258    }
8259
8260    /**
8261     * Dispatch a generic motion event.
8262     * <p>
8263     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
8264     * are delivered to the view under the pointer.  All other generic motion events are
8265     * delivered to the focused view.  Hover events are handled specially and are delivered
8266     * to {@link #onHoverEvent(MotionEvent)}.
8267     * </p>
8268     *
8269     * @param event The motion event to be dispatched.
8270     * @return True if the event was handled by the view, false otherwise.
8271     */
8272    public boolean dispatchGenericMotionEvent(MotionEvent event) {
8273        if (mInputEventConsistencyVerifier != null) {
8274            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
8275        }
8276
8277        final int source = event.getSource();
8278        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
8279            final int action = event.getAction();
8280            if (action == MotionEvent.ACTION_HOVER_ENTER
8281                    || action == MotionEvent.ACTION_HOVER_MOVE
8282                    || action == MotionEvent.ACTION_HOVER_EXIT) {
8283                if (dispatchHoverEvent(event)) {
8284                    return true;
8285                }
8286            } else if (dispatchGenericPointerEvent(event)) {
8287                return true;
8288            }
8289        } else if (dispatchGenericFocusedEvent(event)) {
8290            return true;
8291        }
8292
8293        if (dispatchGenericMotionEventInternal(event)) {
8294            return true;
8295        }
8296
8297        if (mInputEventConsistencyVerifier != null) {
8298            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8299        }
8300        return false;
8301    }
8302
8303    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
8304        //noinspection SimplifiableIfStatement
8305        ListenerInfo li = mListenerInfo;
8306        if (li != null && li.mOnGenericMotionListener != null
8307                && (mViewFlags & ENABLED_MASK) == ENABLED
8308                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
8309            return true;
8310        }
8311
8312        if (onGenericMotionEvent(event)) {
8313            return true;
8314        }
8315
8316        if (mInputEventConsistencyVerifier != null) {
8317            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8318        }
8319        return false;
8320    }
8321
8322    /**
8323     * Dispatch a hover event.
8324     * <p>
8325     * Do not call this method directly.
8326     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8327     * </p>
8328     *
8329     * @param event The motion event to be dispatched.
8330     * @return True if the event was handled by the view, false otherwise.
8331     */
8332    protected boolean dispatchHoverEvent(MotionEvent event) {
8333        ListenerInfo li = mListenerInfo;
8334        //noinspection SimplifiableIfStatement
8335        if (li != null && li.mOnHoverListener != null
8336                && (mViewFlags & ENABLED_MASK) == ENABLED
8337                && li.mOnHoverListener.onHover(this, event)) {
8338            return true;
8339        }
8340
8341        return onHoverEvent(event);
8342    }
8343
8344    /**
8345     * Returns true if the view has a child to which it has recently sent
8346     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
8347     * it does not have a hovered child, then it must be the innermost hovered view.
8348     * @hide
8349     */
8350    protected boolean hasHoveredChild() {
8351        return false;
8352    }
8353
8354    /**
8355     * Dispatch a generic motion event to the view under the first pointer.
8356     * <p>
8357     * Do not call this method directly.
8358     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8359     * </p>
8360     *
8361     * @param event The motion event to be dispatched.
8362     * @return True if the event was handled by the view, false otherwise.
8363     */
8364    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
8365        return false;
8366    }
8367
8368    /**
8369     * Dispatch a generic motion event to the currently focused view.
8370     * <p>
8371     * Do not call this method directly.
8372     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8373     * </p>
8374     *
8375     * @param event The motion event to be dispatched.
8376     * @return True if the event was handled by the view, false otherwise.
8377     */
8378    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
8379        return false;
8380    }
8381
8382    /**
8383     * Dispatch a pointer event.
8384     * <p>
8385     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
8386     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
8387     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
8388     * and should not be expected to handle other pointing device features.
8389     * </p>
8390     *
8391     * @param event The motion event to be dispatched.
8392     * @return True if the event was handled by the view, false otherwise.
8393     * @hide
8394     */
8395    public final boolean dispatchPointerEvent(MotionEvent event) {
8396        if (event.isTouchEvent()) {
8397            return dispatchTouchEvent(event);
8398        } else {
8399            return dispatchGenericMotionEvent(event);
8400        }
8401    }
8402
8403    /**
8404     * Called when the window containing this view gains or loses window focus.
8405     * ViewGroups should override to route to their children.
8406     *
8407     * @param hasFocus True if the window containing this view now has focus,
8408     *        false otherwise.
8409     */
8410    public void dispatchWindowFocusChanged(boolean hasFocus) {
8411        onWindowFocusChanged(hasFocus);
8412    }
8413
8414    /**
8415     * Called when the window containing this view gains or loses focus.  Note
8416     * that this is separate from view focus: to receive key events, both
8417     * your view and its window must have focus.  If a window is displayed
8418     * on top of yours that takes input focus, then your own window will lose
8419     * focus but the view focus will remain unchanged.
8420     *
8421     * @param hasWindowFocus True if the window containing this view now has
8422     *        focus, false otherwise.
8423     */
8424    public void onWindowFocusChanged(boolean hasWindowFocus) {
8425        InputMethodManager imm = InputMethodManager.peekInstance();
8426        if (!hasWindowFocus) {
8427            if (isPressed()) {
8428                setPressed(false);
8429            }
8430            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
8431                imm.focusOut(this);
8432            }
8433            removeLongPressCallback();
8434            removeTapCallback();
8435            onFocusLost();
8436        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
8437            imm.focusIn(this);
8438        }
8439        refreshDrawableState();
8440    }
8441
8442    /**
8443     * Returns true if this view is in a window that currently has window focus.
8444     * Note that this is not the same as the view itself having focus.
8445     *
8446     * @return True if this view is in a window that currently has window focus.
8447     */
8448    public boolean hasWindowFocus() {
8449        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
8450    }
8451
8452    /**
8453     * Dispatch a view visibility change down the view hierarchy.
8454     * ViewGroups should override to route to their children.
8455     * @param changedView The view whose visibility changed. Could be 'this' or
8456     * an ancestor view.
8457     * @param visibility The new visibility of changedView: {@link #VISIBLE},
8458     * {@link #INVISIBLE} or {@link #GONE}.
8459     */
8460    protected void dispatchVisibilityChanged(@NonNull View changedView,
8461            @Visibility int visibility) {
8462        onVisibilityChanged(changedView, visibility);
8463    }
8464
8465    /**
8466     * Called when the visibility of the view or an ancestor of the view is changed.
8467     * @param changedView The view whose visibility changed. Could be 'this' or
8468     * an ancestor view.
8469     * @param visibility The new visibility of changedView: {@link #VISIBLE},
8470     * {@link #INVISIBLE} or {@link #GONE}.
8471     */
8472    protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) {
8473        if (visibility == VISIBLE) {
8474            if (mAttachInfo != null) {
8475                initialAwakenScrollBars();
8476            } else {
8477                mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
8478            }
8479        }
8480    }
8481
8482    /**
8483     * Dispatch a hint about whether this view is displayed. For instance, when
8484     * a View moves out of the screen, it might receives a display hint indicating
8485     * the view is not displayed. Applications should not <em>rely</em> on this hint
8486     * as there is no guarantee that they will receive one.
8487     *
8488     * @param hint A hint about whether or not this view is displayed:
8489     * {@link #VISIBLE} or {@link #INVISIBLE}.
8490     */
8491    public void dispatchDisplayHint(@Visibility int hint) {
8492        onDisplayHint(hint);
8493    }
8494
8495    /**
8496     * Gives this view a hint about whether is displayed or not. For instance, when
8497     * a View moves out of the screen, it might receives a display hint indicating
8498     * the view is not displayed. Applications should not <em>rely</em> on this hint
8499     * as there is no guarantee that they will receive one.
8500     *
8501     * @param hint A hint about whether or not this view is displayed:
8502     * {@link #VISIBLE} or {@link #INVISIBLE}.
8503     */
8504    protected void onDisplayHint(@Visibility int hint) {
8505    }
8506
8507    /**
8508     * Dispatch a window visibility change down the view hierarchy.
8509     * ViewGroups should override to route to their children.
8510     *
8511     * @param visibility The new visibility of the window.
8512     *
8513     * @see #onWindowVisibilityChanged(int)
8514     */
8515    public void dispatchWindowVisibilityChanged(@Visibility int visibility) {
8516        onWindowVisibilityChanged(visibility);
8517    }
8518
8519    /**
8520     * Called when the window containing has change its visibility
8521     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
8522     * that this tells you whether or not your window is being made visible
8523     * to the window manager; this does <em>not</em> tell you whether or not
8524     * your window is obscured by other windows on the screen, even if it
8525     * is itself visible.
8526     *
8527     * @param visibility The new visibility of the window.
8528     */
8529    protected void onWindowVisibilityChanged(@Visibility int visibility) {
8530        if (visibility == VISIBLE) {
8531            initialAwakenScrollBars();
8532        }
8533    }
8534
8535    /**
8536     * Returns the current visibility of the window this view is attached to
8537     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
8538     *
8539     * @return Returns the current visibility of the view's window.
8540     */
8541    @Visibility
8542    public int getWindowVisibility() {
8543        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
8544    }
8545
8546    /**
8547     * Retrieve the overall visible display size in which the window this view is
8548     * attached to has been positioned in.  This takes into account screen
8549     * decorations above the window, for both cases where the window itself
8550     * is being position inside of them or the window is being placed under
8551     * then and covered insets are used for the window to position its content
8552     * inside.  In effect, this tells you the available area where content can
8553     * be placed and remain visible to users.
8554     *
8555     * <p>This function requires an IPC back to the window manager to retrieve
8556     * the requested information, so should not be used in performance critical
8557     * code like drawing.
8558     *
8559     * @param outRect Filled in with the visible display frame.  If the view
8560     * is not attached to a window, this is simply the raw display size.
8561     */
8562    public void getWindowVisibleDisplayFrame(Rect outRect) {
8563        if (mAttachInfo != null) {
8564            try {
8565                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
8566            } catch (RemoteException e) {
8567                return;
8568            }
8569            // XXX This is really broken, and probably all needs to be done
8570            // in the window manager, and we need to know more about whether
8571            // we want the area behind or in front of the IME.
8572            final Rect insets = mAttachInfo.mVisibleInsets;
8573            outRect.left += insets.left;
8574            outRect.top += insets.top;
8575            outRect.right -= insets.right;
8576            outRect.bottom -= insets.bottom;
8577            return;
8578        }
8579        // The view is not attached to a display so we don't have a context.
8580        // Make a best guess about the display size.
8581        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
8582        d.getRectSize(outRect);
8583    }
8584
8585    /**
8586     * Dispatch a notification about a resource configuration change down
8587     * the view hierarchy.
8588     * ViewGroups should override to route to their children.
8589     *
8590     * @param newConfig The new resource configuration.
8591     *
8592     * @see #onConfigurationChanged(android.content.res.Configuration)
8593     */
8594    public void dispatchConfigurationChanged(Configuration newConfig) {
8595        onConfigurationChanged(newConfig);
8596    }
8597
8598    /**
8599     * Called when the current configuration of the resources being used
8600     * by the application have changed.  You can use this to decide when
8601     * to reload resources that can changed based on orientation and other
8602     * configuration characterstics.  You only need to use this if you are
8603     * not relying on the normal {@link android.app.Activity} mechanism of
8604     * recreating the activity instance upon a configuration change.
8605     *
8606     * @param newConfig The new resource configuration.
8607     */
8608    protected void onConfigurationChanged(Configuration newConfig) {
8609    }
8610
8611    /**
8612     * Private function to aggregate all per-view attributes in to the view
8613     * root.
8614     */
8615    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
8616        performCollectViewAttributes(attachInfo, visibility);
8617    }
8618
8619    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
8620        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
8621            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
8622                attachInfo.mKeepScreenOn = true;
8623            }
8624            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
8625            ListenerInfo li = mListenerInfo;
8626            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
8627                attachInfo.mHasSystemUiListeners = true;
8628            }
8629        }
8630    }
8631
8632    void needGlobalAttributesUpdate(boolean force) {
8633        final AttachInfo ai = mAttachInfo;
8634        if (ai != null && !ai.mRecomputeGlobalAttributes) {
8635            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
8636                    || ai.mHasSystemUiListeners) {
8637                ai.mRecomputeGlobalAttributes = true;
8638            }
8639        }
8640    }
8641
8642    /**
8643     * Returns whether the device is currently in touch mode.  Touch mode is entered
8644     * once the user begins interacting with the device by touch, and affects various
8645     * things like whether focus is always visible to the user.
8646     *
8647     * @return Whether the device is in touch mode.
8648     */
8649    @ViewDebug.ExportedProperty
8650    public boolean isInTouchMode() {
8651        if (mAttachInfo != null) {
8652            return mAttachInfo.mInTouchMode;
8653        } else {
8654            return ViewRootImpl.isInTouchMode();
8655        }
8656    }
8657
8658    /**
8659     * Returns the context the view is running in, through which it can
8660     * access the current theme, resources, etc.
8661     *
8662     * @return The view's Context.
8663     */
8664    @ViewDebug.CapturedViewProperty
8665    public final Context getContext() {
8666        return mContext;
8667    }
8668
8669    /**
8670     * Handle a key event before it is processed by any input method
8671     * associated with the view hierarchy.  This can be used to intercept
8672     * key events in special situations before the IME consumes them; a
8673     * typical example would be handling the BACK key to update the application's
8674     * UI instead of allowing the IME to see it and close itself.
8675     *
8676     * @param keyCode The value in event.getKeyCode().
8677     * @param event Description of the key event.
8678     * @return If you handled the event, return true. If you want to allow the
8679     *         event to be handled by the next receiver, return false.
8680     */
8681    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
8682        return false;
8683    }
8684
8685    /**
8686     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
8687     * KeyEvent.Callback.onKeyDown()}: perform press of the view
8688     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
8689     * is released, if the view is enabled and clickable.
8690     *
8691     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8692     * although some may elect to do so in some situations. Do not rely on this to
8693     * catch software key presses.
8694     *
8695     * @param keyCode A key code that represents the button pressed, from
8696     *                {@link android.view.KeyEvent}.
8697     * @param event   The KeyEvent object that defines the button action.
8698     */
8699    public boolean onKeyDown(int keyCode, KeyEvent event) {
8700        boolean result = false;
8701
8702        if (KeyEvent.isConfirmKey(keyCode)) {
8703            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
8704                return true;
8705            }
8706            // Long clickable items don't necessarily have to be clickable
8707            if (((mViewFlags & CLICKABLE) == CLICKABLE ||
8708                    (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
8709                    (event.getRepeatCount() == 0)) {
8710                setPressed(true);
8711                checkForLongClick(0);
8712                return true;
8713            }
8714        }
8715        return result;
8716    }
8717
8718    /**
8719     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
8720     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
8721     * the event).
8722     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8723     * although some may elect to do so in some situations. Do not rely on this to
8724     * catch software key presses.
8725     */
8726    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
8727        return false;
8728    }
8729
8730    /**
8731     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
8732     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
8733     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
8734     * {@link KeyEvent#KEYCODE_ENTER} is released.
8735     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8736     * although some may elect to do so in some situations. Do not rely on this to
8737     * catch software key presses.
8738     *
8739     * @param keyCode A key code that represents the button pressed, from
8740     *                {@link android.view.KeyEvent}.
8741     * @param event   The KeyEvent object that defines the button action.
8742     */
8743    public boolean onKeyUp(int keyCode, KeyEvent event) {
8744        if (KeyEvent.isConfirmKey(keyCode)) {
8745            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
8746                return true;
8747            }
8748            if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
8749                setPressed(false);
8750
8751                if (!mHasPerformedLongPress) {
8752                    // This is a tap, so remove the longpress check
8753                    removeLongPressCallback();
8754                    return performClick();
8755                }
8756            }
8757        }
8758        return false;
8759    }
8760
8761    /**
8762     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
8763     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
8764     * the event).
8765     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8766     * although some may elect to do so in some situations. Do not rely on this to
8767     * catch software key presses.
8768     *
8769     * @param keyCode     A key code that represents the button pressed, from
8770     *                    {@link android.view.KeyEvent}.
8771     * @param repeatCount The number of times the action was made.
8772     * @param event       The KeyEvent object that defines the button action.
8773     */
8774    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
8775        return false;
8776    }
8777
8778    /**
8779     * Called on the focused view when a key shortcut event is not handled.
8780     * Override this method to implement local key shortcuts for the View.
8781     * Key shortcuts can also be implemented by setting the
8782     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
8783     *
8784     * @param keyCode The value in event.getKeyCode().
8785     * @param event Description of the key event.
8786     * @return If you handled the event, return true. If you want to allow the
8787     *         event to be handled by the next receiver, return false.
8788     */
8789    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
8790        return false;
8791    }
8792
8793    /**
8794     * Check whether the called view is a text editor, in which case it
8795     * would make sense to automatically display a soft input window for
8796     * it.  Subclasses should override this if they implement
8797     * {@link #onCreateInputConnection(EditorInfo)} to return true if
8798     * a call on that method would return a non-null InputConnection, and
8799     * they are really a first-class editor that the user would normally
8800     * start typing on when the go into a window containing your view.
8801     *
8802     * <p>The default implementation always returns false.  This does
8803     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
8804     * will not be called or the user can not otherwise perform edits on your
8805     * view; it is just a hint to the system that this is not the primary
8806     * purpose of this view.
8807     *
8808     * @return Returns true if this view is a text editor, else false.
8809     */
8810    public boolean onCheckIsTextEditor() {
8811        return false;
8812    }
8813
8814    /**
8815     * Create a new InputConnection for an InputMethod to interact
8816     * with the view.  The default implementation returns null, since it doesn't
8817     * support input methods.  You can override this to implement such support.
8818     * This is only needed for views that take focus and text input.
8819     *
8820     * <p>When implementing this, you probably also want to implement
8821     * {@link #onCheckIsTextEditor()} to indicate you will return a
8822     * non-null InputConnection.</p>
8823     *
8824     * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo}
8825     * object correctly and in its entirety, so that the connected IME can rely
8826     * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart}
8827     * and  {@link android.view.inputmethod.EditorInfo#initialSelEnd} members
8828     * must be filled in with the correct cursor position for IMEs to work correctly
8829     * with your application.</p>
8830     *
8831     * @param outAttrs Fill in with attribute information about the connection.
8832     */
8833    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
8834        return null;
8835    }
8836
8837    /**
8838     * Called by the {@link android.view.inputmethod.InputMethodManager}
8839     * when a view who is not the current
8840     * input connection target is trying to make a call on the manager.  The
8841     * default implementation returns false; you can override this to return
8842     * true for certain views if you are performing InputConnection proxying
8843     * to them.
8844     * @param view The View that is making the InputMethodManager call.
8845     * @return Return true to allow the call, false to reject.
8846     */
8847    public boolean checkInputConnectionProxy(View view) {
8848        return false;
8849    }
8850
8851    /**
8852     * Show the context menu for this view. It is not safe to hold on to the
8853     * menu after returning from this method.
8854     *
8855     * You should normally not overload this method. Overload
8856     * {@link #onCreateContextMenu(ContextMenu)} or define an
8857     * {@link OnCreateContextMenuListener} to add items to the context menu.
8858     *
8859     * @param menu The context menu to populate
8860     */
8861    public void createContextMenu(ContextMenu menu) {
8862        ContextMenuInfo menuInfo = getContextMenuInfo();
8863
8864        // Sets the current menu info so all items added to menu will have
8865        // my extra info set.
8866        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
8867
8868        onCreateContextMenu(menu);
8869        ListenerInfo li = mListenerInfo;
8870        if (li != null && li.mOnCreateContextMenuListener != null) {
8871            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
8872        }
8873
8874        // Clear the extra information so subsequent items that aren't mine don't
8875        // have my extra info.
8876        ((MenuBuilder)menu).setCurrentMenuInfo(null);
8877
8878        if (mParent != null) {
8879            mParent.createContextMenu(menu);
8880        }
8881    }
8882
8883    /**
8884     * Views should implement this if they have extra information to associate
8885     * with the context menu. The return result is supplied as a parameter to
8886     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
8887     * callback.
8888     *
8889     * @return Extra information about the item for which the context menu
8890     *         should be shown. This information will vary across different
8891     *         subclasses of View.
8892     */
8893    protected ContextMenuInfo getContextMenuInfo() {
8894        return null;
8895    }
8896
8897    /**
8898     * Views should implement this if the view itself is going to add items to
8899     * the context menu.
8900     *
8901     * @param menu the context menu to populate
8902     */
8903    protected void onCreateContextMenu(ContextMenu menu) {
8904    }
8905
8906    /**
8907     * Implement this method to handle trackball motion events.  The
8908     * <em>relative</em> movement of the trackball since the last event
8909     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
8910     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
8911     * that a movement of 1 corresponds to the user pressing one DPAD key (so
8912     * they will often be fractional values, representing the more fine-grained
8913     * movement information available from a trackball).
8914     *
8915     * @param event The motion event.
8916     * @return True if the event was handled, false otherwise.
8917     */
8918    public boolean onTrackballEvent(MotionEvent event) {
8919        return false;
8920    }
8921
8922    /**
8923     * Implement this method to handle generic motion events.
8924     * <p>
8925     * Generic motion events describe joystick movements, mouse hovers, track pad
8926     * touches, scroll wheel movements and other input events.  The
8927     * {@link MotionEvent#getSource() source} of the motion event specifies
8928     * the class of input that was received.  Implementations of this method
8929     * must examine the bits in the source before processing the event.
8930     * The following code example shows how this is done.
8931     * </p><p>
8932     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
8933     * are delivered to the view under the pointer.  All other generic motion events are
8934     * delivered to the focused view.
8935     * </p>
8936     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
8937     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {
8938     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
8939     *             // process the joystick movement...
8940     *             return true;
8941     *         }
8942     *     }
8943     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
8944     *         switch (event.getAction()) {
8945     *             case MotionEvent.ACTION_HOVER_MOVE:
8946     *                 // process the mouse hover movement...
8947     *                 return true;
8948     *             case MotionEvent.ACTION_SCROLL:
8949     *                 // process the scroll wheel movement...
8950     *                 return true;
8951     *         }
8952     *     }
8953     *     return super.onGenericMotionEvent(event);
8954     * }</pre>
8955     *
8956     * @param event The generic motion event being processed.
8957     * @return True if the event was handled, false otherwise.
8958     */
8959    public boolean onGenericMotionEvent(MotionEvent event) {
8960        return false;
8961    }
8962
8963    /**
8964     * Implement this method to handle hover events.
8965     * <p>
8966     * This method is called whenever a pointer is hovering into, over, or out of the
8967     * bounds of a view and the view is not currently being touched.
8968     * Hover events are represented as pointer events with action
8969     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
8970     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
8971     * </p>
8972     * <ul>
8973     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
8974     * when the pointer enters the bounds of the view.</li>
8975     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
8976     * when the pointer has already entered the bounds of the view and has moved.</li>
8977     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
8978     * when the pointer has exited the bounds of the view or when the pointer is
8979     * about to go down due to a button click, tap, or similar user action that
8980     * causes the view to be touched.</li>
8981     * </ul>
8982     * <p>
8983     * The view should implement this method to return true to indicate that it is
8984     * handling the hover event, such as by changing its drawable state.
8985     * </p><p>
8986     * The default implementation calls {@link #setHovered} to update the hovered state
8987     * of the view when a hover enter or hover exit event is received, if the view
8988     * is enabled and is clickable.  The default implementation also sends hover
8989     * accessibility events.
8990     * </p>
8991     *
8992     * @param event The motion event that describes the hover.
8993     * @return True if the view handled the hover event.
8994     *
8995     * @see #isHovered
8996     * @see #setHovered
8997     * @see #onHoverChanged
8998     */
8999    public boolean onHoverEvent(MotionEvent event) {
9000        // The root view may receive hover (or touch) events that are outside the bounds of
9001        // the window.  This code ensures that we only send accessibility events for
9002        // hovers that are actually within the bounds of the root view.
9003        final int action = event.getActionMasked();
9004        if (!mSendingHoverAccessibilityEvents) {
9005            if ((action == MotionEvent.ACTION_HOVER_ENTER
9006                    || action == MotionEvent.ACTION_HOVER_MOVE)
9007                    && !hasHoveredChild()
9008                    && pointInView(event.getX(), event.getY())) {
9009                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
9010                mSendingHoverAccessibilityEvents = true;
9011            }
9012        } else {
9013            if (action == MotionEvent.ACTION_HOVER_EXIT
9014                    || (action == MotionEvent.ACTION_MOVE
9015                            && !pointInView(event.getX(), event.getY()))) {
9016                mSendingHoverAccessibilityEvents = false;
9017                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
9018            }
9019        }
9020
9021        if (isHoverable()) {
9022            switch (action) {
9023                case MotionEvent.ACTION_HOVER_ENTER:
9024                    setHovered(true);
9025                    break;
9026                case MotionEvent.ACTION_HOVER_EXIT:
9027                    setHovered(false);
9028                    break;
9029            }
9030
9031            // Dispatch the event to onGenericMotionEvent before returning true.
9032            // This is to provide compatibility with existing applications that
9033            // handled HOVER_MOVE events in onGenericMotionEvent and that would
9034            // break because of the new default handling for hoverable views
9035            // in onHoverEvent.
9036            // Note that onGenericMotionEvent will be called by default when
9037            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
9038            dispatchGenericMotionEventInternal(event);
9039            // The event was already handled by calling setHovered(), so always
9040            // return true.
9041            return true;
9042        }
9043
9044        return false;
9045    }
9046
9047    /**
9048     * Returns true if the view should handle {@link #onHoverEvent}
9049     * by calling {@link #setHovered} to change its hovered state.
9050     *
9051     * @return True if the view is hoverable.
9052     */
9053    private boolean isHoverable() {
9054        final int viewFlags = mViewFlags;
9055        if ((viewFlags & ENABLED_MASK) == DISABLED) {
9056            return false;
9057        }
9058
9059        return (viewFlags & CLICKABLE) == CLICKABLE
9060                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
9061    }
9062
9063    /**
9064     * Returns true if the view is currently hovered.
9065     *
9066     * @return True if the view is currently hovered.
9067     *
9068     * @see #setHovered
9069     * @see #onHoverChanged
9070     */
9071    @ViewDebug.ExportedProperty
9072    public boolean isHovered() {
9073        return (mPrivateFlags & PFLAG_HOVERED) != 0;
9074    }
9075
9076    /**
9077     * Sets whether the view is currently hovered.
9078     * <p>
9079     * Calling this method also changes the drawable state of the view.  This
9080     * enables the view to react to hover by using different drawable resources
9081     * to change its appearance.
9082     * </p><p>
9083     * The {@link #onHoverChanged} method is called when the hovered state changes.
9084     * </p>
9085     *
9086     * @param hovered True if the view is hovered.
9087     *
9088     * @see #isHovered
9089     * @see #onHoverChanged
9090     */
9091    public void setHovered(boolean hovered) {
9092        if (hovered) {
9093            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
9094                mPrivateFlags |= PFLAG_HOVERED;
9095                refreshDrawableState();
9096                onHoverChanged(true);
9097            }
9098        } else {
9099            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
9100                mPrivateFlags &= ~PFLAG_HOVERED;
9101                refreshDrawableState();
9102                onHoverChanged(false);
9103            }
9104        }
9105    }
9106
9107    /**
9108     * Implement this method to handle hover state changes.
9109     * <p>
9110     * This method is called whenever the hover state changes as a result of a
9111     * call to {@link #setHovered}.
9112     * </p>
9113     *
9114     * @param hovered The current hover state, as returned by {@link #isHovered}.
9115     *
9116     * @see #isHovered
9117     * @see #setHovered
9118     */
9119    public void onHoverChanged(boolean hovered) {
9120    }
9121
9122    /**
9123     * Implement this method to handle touch screen motion events.
9124     * <p>
9125     * If this method is used to detect click actions, it is recommended that
9126     * the actions be performed by implementing and calling
9127     * {@link #performClick()}. This will ensure consistent system behavior,
9128     * including:
9129     * <ul>
9130     * <li>obeying click sound preferences
9131     * <li>dispatching OnClickListener calls
9132     * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when
9133     * accessibility features are enabled
9134     * </ul>
9135     *
9136     * @param event The motion event.
9137     * @return True if the event was handled, false otherwise.
9138     */
9139    public boolean onTouchEvent(MotionEvent event) {
9140        final float x = event.getX();
9141        final float y = event.getY();
9142        final int viewFlags = mViewFlags;
9143
9144        if ((viewFlags & ENABLED_MASK) == DISABLED) {
9145            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
9146                setPressed(false);
9147            }
9148            // A disabled view that is clickable still consumes the touch
9149            // events, it just doesn't respond to them.
9150            return (((viewFlags & CLICKABLE) == CLICKABLE ||
9151                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
9152        }
9153
9154        if (mTouchDelegate != null) {
9155            if (mTouchDelegate.onTouchEvent(event)) {
9156                return true;
9157            }
9158        }
9159
9160        if (((viewFlags & CLICKABLE) == CLICKABLE ||
9161                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
9162            switch (event.getAction()) {
9163                case MotionEvent.ACTION_UP:
9164                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
9165                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
9166                        // take focus if we don't have it already and we should in
9167                        // touch mode.
9168                        boolean focusTaken = false;
9169                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
9170                            focusTaken = requestFocus();
9171                        }
9172
9173                        if (prepressed) {
9174                            // The button is being released before we actually
9175                            // showed it as pressed.  Make it show the pressed
9176                            // state now (before scheduling the click) to ensure
9177                            // the user sees it.
9178                            setPressed(true, x, y);
9179                       }
9180
9181                        if (!mHasPerformedLongPress) {
9182                            // This is a tap, so remove the longpress check
9183                            removeLongPressCallback();
9184
9185                            // Only perform take click actions if we were in the pressed state
9186                            if (!focusTaken) {
9187                                // Use a Runnable and post this rather than calling
9188                                // performClick directly. This lets other visual state
9189                                // of the view update before click actions start.
9190                                if (mPerformClick == null) {
9191                                    mPerformClick = new PerformClick();
9192                                }
9193                                if (!post(mPerformClick)) {
9194                                    performClick();
9195                                }
9196                            }
9197                        }
9198
9199                        if (mUnsetPressedState == null) {
9200                            mUnsetPressedState = new UnsetPressedState();
9201                        }
9202
9203                        if (prepressed) {
9204                            postDelayed(mUnsetPressedState,
9205                                    ViewConfiguration.getPressedStateDuration());
9206                        } else if (!post(mUnsetPressedState)) {
9207                            // If the post failed, unpress right now
9208                            mUnsetPressedState.run();
9209                        }
9210
9211                        removeTapCallback();
9212                    }
9213                    break;
9214
9215                case MotionEvent.ACTION_DOWN:
9216                    mHasPerformedLongPress = false;
9217
9218                    if (performButtonActionOnTouchDown(event)) {
9219                        break;
9220                    }
9221
9222                    // Walk up the hierarchy to determine if we're inside a scrolling container.
9223                    boolean isInScrollingContainer = isInScrollingContainer();
9224
9225                    // For views inside a scrolling container, delay the pressed feedback for
9226                    // a short period in case this is a scroll.
9227                    if (isInScrollingContainer) {
9228                        mPrivateFlags |= PFLAG_PREPRESSED;
9229                        if (mPendingCheckForTap == null) {
9230                            mPendingCheckForTap = new CheckForTap();
9231                        }
9232                        mPendingCheckForTap.x = event.getX();
9233                        mPendingCheckForTap.y = event.getY();
9234                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
9235                    } else {
9236                        // Not inside a scrolling container, so show the feedback right away
9237                        setPressed(true, x, y);
9238                        checkForLongClick(0);
9239                    }
9240                    break;
9241
9242                case MotionEvent.ACTION_CANCEL:
9243                    setPressed(false);
9244                    removeTapCallback();
9245                    removeLongPressCallback();
9246                    break;
9247
9248                case MotionEvent.ACTION_MOVE:
9249                    drawableHotspotChanged(x, y);
9250
9251                    // Be lenient about moving outside of buttons
9252                    if (!pointInView(x, y, mTouchSlop)) {
9253                        // Outside button
9254                        removeTapCallback();
9255                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
9256                            // Remove any future long press/tap checks
9257                            removeLongPressCallback();
9258
9259                            setPressed(false);
9260                        }
9261                    }
9262                    break;
9263            }
9264
9265            return true;
9266        }
9267
9268        return false;
9269    }
9270
9271    /**
9272     * @hide
9273     */
9274    public boolean isInScrollingContainer() {
9275        ViewParent p = getParent();
9276        while (p != null && p instanceof ViewGroup) {
9277            if (((ViewGroup) p).shouldDelayChildPressedState()) {
9278                return true;
9279            }
9280            p = p.getParent();
9281        }
9282        return false;
9283    }
9284
9285    /**
9286     * Remove the longpress detection timer.
9287     */
9288    private void removeLongPressCallback() {
9289        if (mPendingCheckForLongPress != null) {
9290          removeCallbacks(mPendingCheckForLongPress);
9291        }
9292    }
9293
9294    /**
9295     * Remove the pending click action
9296     */
9297    private void removePerformClickCallback() {
9298        if (mPerformClick != null) {
9299            removeCallbacks(mPerformClick);
9300        }
9301    }
9302
9303    /**
9304     * Remove the prepress detection timer.
9305     */
9306    private void removeUnsetPressCallback() {
9307        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
9308            setPressed(false);
9309            removeCallbacks(mUnsetPressedState);
9310        }
9311    }
9312
9313    /**
9314     * Remove the tap detection timer.
9315     */
9316    private void removeTapCallback() {
9317        if (mPendingCheckForTap != null) {
9318            mPrivateFlags &= ~PFLAG_PREPRESSED;
9319            removeCallbacks(mPendingCheckForTap);
9320        }
9321    }
9322
9323    /**
9324     * Cancels a pending long press.  Your subclass can use this if you
9325     * want the context menu to come up if the user presses and holds
9326     * at the same place, but you don't want it to come up if they press
9327     * and then move around enough to cause scrolling.
9328     */
9329    public void cancelLongPress() {
9330        removeLongPressCallback();
9331
9332        /*
9333         * The prepressed state handled by the tap callback is a display
9334         * construct, but the tap callback will post a long press callback
9335         * less its own timeout. Remove it here.
9336         */
9337        removeTapCallback();
9338    }
9339
9340    /**
9341     * Remove the pending callback for sending a
9342     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
9343     */
9344    private void removeSendViewScrolledAccessibilityEventCallback() {
9345        if (mSendViewScrolledAccessibilityEvent != null) {
9346            removeCallbacks(mSendViewScrolledAccessibilityEvent);
9347            mSendViewScrolledAccessibilityEvent.mIsPending = false;
9348        }
9349    }
9350
9351    /**
9352     * Sets the TouchDelegate for this View.
9353     */
9354    public void setTouchDelegate(TouchDelegate delegate) {
9355        mTouchDelegate = delegate;
9356    }
9357
9358    /**
9359     * Gets the TouchDelegate for this View.
9360     */
9361    public TouchDelegate getTouchDelegate() {
9362        return mTouchDelegate;
9363    }
9364
9365    /**
9366     * Request unbuffered dispatch of the given stream of MotionEvents to this View.
9367     *
9368     * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input
9369     * system not batch {@link MotionEvent}s but instead deliver them as soon as they're
9370     * available. This method should only be called for touch events.
9371     *
9372     * <p class="note">This api is not intended for most applications. Buffered dispatch
9373     * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent
9374     * streams will not improve your input latency. Side effects include: increased latency,
9375     * jittery scrolls and inability to take advantage of system resampling. Talk to your input
9376     * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for
9377     * you.</p>
9378     */
9379    public final void requestUnbufferedDispatch(MotionEvent event) {
9380        final int action = event.getAction();
9381        if (mAttachInfo == null
9382                || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE
9383                || !event.isTouchEvent()) {
9384            return;
9385        }
9386        mAttachInfo.mUnbufferedDispatchRequested = true;
9387    }
9388
9389    /**
9390     * Set flags controlling behavior of this view.
9391     *
9392     * @param flags Constant indicating the value which should be set
9393     * @param mask Constant indicating the bit range that should be changed
9394     */
9395    void setFlags(int flags, int mask) {
9396        final boolean accessibilityEnabled =
9397                AccessibilityManager.getInstance(mContext).isEnabled();
9398        final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility();
9399
9400        int old = mViewFlags;
9401        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
9402
9403        int changed = mViewFlags ^ old;
9404        if (changed == 0) {
9405            return;
9406        }
9407        int privateFlags = mPrivateFlags;
9408
9409        /* Check if the FOCUSABLE bit has changed */
9410        if (((changed & FOCUSABLE_MASK) != 0) &&
9411                ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) {
9412            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
9413                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
9414                /* Give up focus if we are no longer focusable */
9415                clearFocus();
9416            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
9417                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
9418                /*
9419                 * Tell the view system that we are now available to take focus
9420                 * if no one else already has it.
9421                 */
9422                if (mParent != null) mParent.focusableViewAvailable(this);
9423            }
9424        }
9425
9426        final int newVisibility = flags & VISIBILITY_MASK;
9427        if (newVisibility == VISIBLE) {
9428            if ((changed & VISIBILITY_MASK) != 0) {
9429                /*
9430                 * If this view is becoming visible, invalidate it in case it changed while
9431                 * it was not visible. Marking it drawn ensures that the invalidation will
9432                 * go through.
9433                 */
9434                mPrivateFlags |= PFLAG_DRAWN;
9435                invalidate(true);
9436
9437                needGlobalAttributesUpdate(true);
9438
9439                // a view becoming visible is worth notifying the parent
9440                // about in case nothing has focus.  even if this specific view
9441                // isn't focusable, it may contain something that is, so let
9442                // the root view try to give this focus if nothing else does.
9443                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
9444                    mParent.focusableViewAvailable(this);
9445                }
9446            }
9447        }
9448
9449        /* Check if the GONE bit has changed */
9450        if ((changed & GONE) != 0) {
9451            needGlobalAttributesUpdate(false);
9452            requestLayout();
9453
9454            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
9455                if (hasFocus()) clearFocus();
9456                clearAccessibilityFocus();
9457                destroyDrawingCache();
9458                if (mParent instanceof View) {
9459                    // GONE views noop invalidation, so invalidate the parent
9460                    ((View) mParent).invalidate(true);
9461                }
9462                // Mark the view drawn to ensure that it gets invalidated properly the next
9463                // time it is visible and gets invalidated
9464                mPrivateFlags |= PFLAG_DRAWN;
9465            }
9466            if (mAttachInfo != null) {
9467                mAttachInfo.mViewVisibilityChanged = true;
9468            }
9469        }
9470
9471        /* Check if the VISIBLE bit has changed */
9472        if ((changed & INVISIBLE) != 0) {
9473            needGlobalAttributesUpdate(false);
9474            /*
9475             * If this view is becoming invisible, set the DRAWN flag so that
9476             * the next invalidate() will not be skipped.
9477             */
9478            mPrivateFlags |= PFLAG_DRAWN;
9479
9480            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) {
9481                // root view becoming invisible shouldn't clear focus and accessibility focus
9482                if (getRootView() != this) {
9483                    if (hasFocus()) clearFocus();
9484                    clearAccessibilityFocus();
9485                }
9486            }
9487            if (mAttachInfo != null) {
9488                mAttachInfo.mViewVisibilityChanged = true;
9489            }
9490        }
9491
9492        if ((changed & VISIBILITY_MASK) != 0) {
9493            // If the view is invisible, cleanup its display list to free up resources
9494            if (newVisibility != VISIBLE && mAttachInfo != null) {
9495                cleanupDraw();
9496            }
9497
9498            if (mParent instanceof ViewGroup) {
9499                ((ViewGroup) mParent).onChildVisibilityChanged(this,
9500                        (changed & VISIBILITY_MASK), newVisibility);
9501                ((View) mParent).invalidate(true);
9502            } else if (mParent != null) {
9503                mParent.invalidateChild(this, null);
9504            }
9505            dispatchVisibilityChanged(this, newVisibility);
9506
9507            notifySubtreeAccessibilityStateChangedIfNeeded();
9508        }
9509
9510        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
9511            destroyDrawingCache();
9512        }
9513
9514        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
9515            destroyDrawingCache();
9516            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
9517            invalidateParentCaches();
9518        }
9519
9520        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
9521            destroyDrawingCache();
9522            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
9523        }
9524
9525        if ((changed & DRAW_MASK) != 0) {
9526            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
9527                if (mBackground != null) {
9528                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
9529                    mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
9530                } else {
9531                    mPrivateFlags |= PFLAG_SKIP_DRAW;
9532                }
9533            } else {
9534                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
9535            }
9536            requestLayout();
9537            invalidate(true);
9538        }
9539
9540        if ((changed & KEEP_SCREEN_ON) != 0) {
9541            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
9542                mParent.recomputeViewAttributes(this);
9543            }
9544        }
9545
9546        if (accessibilityEnabled) {
9547            if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0
9548                    || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0) {
9549                if (oldIncludeForAccessibility != includeForAccessibility()) {
9550                    notifySubtreeAccessibilityStateChangedIfNeeded();
9551                } else {
9552                    notifyViewAccessibilityStateChangedIfNeeded(
9553                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9554                }
9555            } else if ((changed & ENABLED_MASK) != 0) {
9556                notifyViewAccessibilityStateChangedIfNeeded(
9557                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9558            }
9559        }
9560    }
9561
9562    /**
9563     * Change the view's z order in the tree, so it's on top of other sibling
9564     * views. This ordering change may affect layout, if the parent container
9565     * uses an order-dependent layout scheme (e.g., LinearLayout). Prior
9566     * to {@link android.os.Build.VERSION_CODES#KITKAT} this
9567     * method should be followed by calls to {@link #requestLayout()} and
9568     * {@link View#invalidate()} on the view's parent to force the parent to redraw
9569     * with the new child ordering.
9570     *
9571     * @see ViewGroup#bringChildToFront(View)
9572     */
9573    public void bringToFront() {
9574        if (mParent != null) {
9575            mParent.bringChildToFront(this);
9576        }
9577    }
9578
9579    /**
9580     * This is called in response to an internal scroll in this view (i.e., the
9581     * view scrolled its own contents). This is typically as a result of
9582     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
9583     * called.
9584     *
9585     * @param l Current horizontal scroll origin.
9586     * @param t Current vertical scroll origin.
9587     * @param oldl Previous horizontal scroll origin.
9588     * @param oldt Previous vertical scroll origin.
9589     */
9590    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
9591        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
9592            postSendViewScrolledAccessibilityEventCallback();
9593        }
9594
9595        mBackgroundSizeChanged = true;
9596
9597        final AttachInfo ai = mAttachInfo;
9598        if (ai != null) {
9599            ai.mViewScrollChanged = true;
9600        }
9601    }
9602
9603    /**
9604     * Interface definition for a callback to be invoked when the layout bounds of a view
9605     * changes due to layout processing.
9606     */
9607    public interface OnLayoutChangeListener {
9608        /**
9609         * Called when the layout bounds of a view changes due to layout processing.
9610         *
9611         * @param v The view whose bounds have changed.
9612         * @param left The new value of the view's left property.
9613         * @param top The new value of the view's top property.
9614         * @param right The new value of the view's right property.
9615         * @param bottom The new value of the view's bottom property.
9616         * @param oldLeft The previous value of the view's left property.
9617         * @param oldTop The previous value of the view's top property.
9618         * @param oldRight The previous value of the view's right property.
9619         * @param oldBottom The previous value of the view's bottom property.
9620         */
9621        void onLayoutChange(View v, int left, int top, int right, int bottom,
9622            int oldLeft, int oldTop, int oldRight, int oldBottom);
9623    }
9624
9625    /**
9626     * This is called during layout when the size of this view has changed. If
9627     * you were just added to the view hierarchy, you're called with the old
9628     * values of 0.
9629     *
9630     * @param w Current width of this view.
9631     * @param h Current height of this view.
9632     * @param oldw Old width of this view.
9633     * @param oldh Old height of this view.
9634     */
9635    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
9636    }
9637
9638    /**
9639     * Called by draw to draw the child views. This may be overridden
9640     * by derived classes to gain control just before its children are drawn
9641     * (but after its own view has been drawn).
9642     * @param canvas the canvas on which to draw the view
9643     */
9644    protected void dispatchDraw(Canvas canvas) {
9645
9646    }
9647
9648    /**
9649     * Gets the parent of this view. Note that the parent is a
9650     * ViewParent and not necessarily a View.
9651     *
9652     * @return Parent of this view.
9653     */
9654    public final ViewParent getParent() {
9655        return mParent;
9656    }
9657
9658    /**
9659     * Set the horizontal scrolled position of your view. This will cause a call to
9660     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9661     * invalidated.
9662     * @param value the x position to scroll to
9663     */
9664    public void setScrollX(int value) {
9665        scrollTo(value, mScrollY);
9666    }
9667
9668    /**
9669     * Set the vertical scrolled position of your view. This will cause a call to
9670     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9671     * invalidated.
9672     * @param value the y position to scroll to
9673     */
9674    public void setScrollY(int value) {
9675        scrollTo(mScrollX, value);
9676    }
9677
9678    /**
9679     * Return the scrolled left position of this view. This is the left edge of
9680     * the displayed part of your view. You do not need to draw any pixels
9681     * farther left, since those are outside of the frame of your view on
9682     * screen.
9683     *
9684     * @return The left edge of the displayed part of your view, in pixels.
9685     */
9686    public final int getScrollX() {
9687        return mScrollX;
9688    }
9689
9690    /**
9691     * Return the scrolled top position of this view. This is the top edge of
9692     * the displayed part of your view. You do not need to draw any pixels above
9693     * it, since those are outside of the frame of your view on screen.
9694     *
9695     * @return The top edge of the displayed part of your view, in pixels.
9696     */
9697    public final int getScrollY() {
9698        return mScrollY;
9699    }
9700
9701    /**
9702     * Return the width of the your view.
9703     *
9704     * @return The width of your view, in pixels.
9705     */
9706    @ViewDebug.ExportedProperty(category = "layout")
9707    public final int getWidth() {
9708        return mRight - mLeft;
9709    }
9710
9711    /**
9712     * Return the height of your view.
9713     *
9714     * @return The height of your view, in pixels.
9715     */
9716    @ViewDebug.ExportedProperty(category = "layout")
9717    public final int getHeight() {
9718        return mBottom - mTop;
9719    }
9720
9721    /**
9722     * Return the visible drawing bounds of your view. Fills in the output
9723     * rectangle with the values from getScrollX(), getScrollY(),
9724     * getWidth(), and getHeight(). These bounds do not account for any
9725     * transformation properties currently set on the view, such as
9726     * {@link #setScaleX(float)} or {@link #setRotation(float)}.
9727     *
9728     * @param outRect The (scrolled) drawing bounds of the view.
9729     */
9730    public void getDrawingRect(Rect outRect) {
9731        outRect.left = mScrollX;
9732        outRect.top = mScrollY;
9733        outRect.right = mScrollX + (mRight - mLeft);
9734        outRect.bottom = mScrollY + (mBottom - mTop);
9735    }
9736
9737    /**
9738     * Like {@link #getMeasuredWidthAndState()}, but only returns the
9739     * raw width component (that is the result is masked by
9740     * {@link #MEASURED_SIZE_MASK}).
9741     *
9742     * @return The raw measured width of this view.
9743     */
9744    public final int getMeasuredWidth() {
9745        return mMeasuredWidth & MEASURED_SIZE_MASK;
9746    }
9747
9748    /**
9749     * Return the full width measurement information for this view as computed
9750     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
9751     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
9752     * This should be used during measurement and layout calculations only. Use
9753     * {@link #getWidth()} to see how wide a view is after layout.
9754     *
9755     * @return The measured width of this view as a bit mask.
9756     */
9757    public final int getMeasuredWidthAndState() {
9758        return mMeasuredWidth;
9759    }
9760
9761    /**
9762     * Like {@link #getMeasuredHeightAndState()}, but only returns the
9763     * raw width component (that is the result is masked by
9764     * {@link #MEASURED_SIZE_MASK}).
9765     *
9766     * @return The raw measured height of this view.
9767     */
9768    public final int getMeasuredHeight() {
9769        return mMeasuredHeight & MEASURED_SIZE_MASK;
9770    }
9771
9772    /**
9773     * Return the full height measurement information for this view as computed
9774     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
9775     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
9776     * This should be used during measurement and layout calculations only. Use
9777     * {@link #getHeight()} to see how wide a view is after layout.
9778     *
9779     * @return The measured width of this view as a bit mask.
9780     */
9781    public final int getMeasuredHeightAndState() {
9782        return mMeasuredHeight;
9783    }
9784
9785    /**
9786     * Return only the state bits of {@link #getMeasuredWidthAndState()}
9787     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
9788     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
9789     * and the height component is at the shifted bits
9790     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
9791     */
9792    public final int getMeasuredState() {
9793        return (mMeasuredWidth&MEASURED_STATE_MASK)
9794                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
9795                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
9796    }
9797
9798    /**
9799     * The transform matrix of this view, which is calculated based on the current
9800     * rotation, scale, and pivot properties.
9801     *
9802     * @see #getRotation()
9803     * @see #getScaleX()
9804     * @see #getScaleY()
9805     * @see #getPivotX()
9806     * @see #getPivotY()
9807     * @return The current transform matrix for the view
9808     */
9809    public Matrix getMatrix() {
9810        ensureTransformationInfo();
9811        final Matrix matrix = mTransformationInfo.mMatrix;
9812        mRenderNode.getMatrix(matrix);
9813        return matrix;
9814    }
9815
9816    /**
9817     * Returns true if the transform matrix is the identity matrix.
9818     * Recomputes the matrix if necessary.
9819     *
9820     * @return True if the transform matrix is the identity matrix, false otherwise.
9821     */
9822    final boolean hasIdentityMatrix() {
9823        return mRenderNode.hasIdentityMatrix();
9824    }
9825
9826    void ensureTransformationInfo() {
9827        if (mTransformationInfo == null) {
9828            mTransformationInfo = new TransformationInfo();
9829        }
9830    }
9831
9832   /**
9833     * Utility method to retrieve the inverse of the current mMatrix property.
9834     * We cache the matrix to avoid recalculating it when transform properties
9835     * have not changed.
9836     *
9837     * @return The inverse of the current matrix of this view.
9838     * @hide
9839     */
9840    public final Matrix getInverseMatrix() {
9841        ensureTransformationInfo();
9842        if (mTransformationInfo.mInverseMatrix == null) {
9843            mTransformationInfo.mInverseMatrix = new Matrix();
9844        }
9845        final Matrix matrix = mTransformationInfo.mInverseMatrix;
9846        mRenderNode.getInverseMatrix(matrix);
9847        return matrix;
9848    }
9849
9850    /**
9851     * Gets the distance along the Z axis from the camera to this view.
9852     *
9853     * @see #setCameraDistance(float)
9854     *
9855     * @return The distance along the Z axis.
9856     */
9857    public float getCameraDistance() {
9858        final float dpi = mResources.getDisplayMetrics().densityDpi;
9859        return -(mRenderNode.getCameraDistance() * dpi);
9860    }
9861
9862    /**
9863     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
9864     * views are drawn) from the camera to this view. The camera's distance
9865     * affects 3D transformations, for instance rotations around the X and Y
9866     * axis. If the rotationX or rotationY properties are changed and this view is
9867     * large (more than half the size of the screen), it is recommended to always
9868     * use a camera distance that's greater than the height (X axis rotation) or
9869     * the width (Y axis rotation) of this view.</p>
9870     *
9871     * <p>The distance of the camera from the view plane can have an affect on the
9872     * perspective distortion of the view when it is rotated around the x or y axis.
9873     * For example, a large distance will result in a large viewing angle, and there
9874     * will not be much perspective distortion of the view as it rotates. A short
9875     * distance may cause much more perspective distortion upon rotation, and can
9876     * also result in some drawing artifacts if the rotated view ends up partially
9877     * behind the camera (which is why the recommendation is to use a distance at
9878     * least as far as the size of the view, if the view is to be rotated.)</p>
9879     *
9880     * <p>The distance is expressed in "depth pixels." The default distance depends
9881     * on the screen density. For instance, on a medium density display, the
9882     * default distance is 1280. On a high density display, the default distance
9883     * is 1920.</p>
9884     *
9885     * <p>If you want to specify a distance that leads to visually consistent
9886     * results across various densities, use the following formula:</p>
9887     * <pre>
9888     * float scale = context.getResources().getDisplayMetrics().density;
9889     * view.setCameraDistance(distance * scale);
9890     * </pre>
9891     *
9892     * <p>The density scale factor of a high density display is 1.5,
9893     * and 1920 = 1280 * 1.5.</p>
9894     *
9895     * @param distance The distance in "depth pixels", if negative the opposite
9896     *        value is used
9897     *
9898     * @see #setRotationX(float)
9899     * @see #setRotationY(float)
9900     */
9901    public void setCameraDistance(float distance) {
9902        final float dpi = mResources.getDisplayMetrics().densityDpi;
9903
9904        invalidateViewProperty(true, false);
9905        mRenderNode.setCameraDistance(-Math.abs(distance) / dpi);
9906        invalidateViewProperty(false, false);
9907
9908        invalidateParentIfNeededAndWasQuickRejected();
9909    }
9910
9911    /**
9912     * The degrees that the view is rotated around the pivot point.
9913     *
9914     * @see #setRotation(float)
9915     * @see #getPivotX()
9916     * @see #getPivotY()
9917     *
9918     * @return The degrees of rotation.
9919     */
9920    @ViewDebug.ExportedProperty(category = "drawing")
9921    public float getRotation() {
9922        return mRenderNode.getRotation();
9923    }
9924
9925    /**
9926     * Sets the degrees that the view is rotated around the pivot point. Increasing values
9927     * result in clockwise rotation.
9928     *
9929     * @param rotation The degrees of rotation.
9930     *
9931     * @see #getRotation()
9932     * @see #getPivotX()
9933     * @see #getPivotY()
9934     * @see #setRotationX(float)
9935     * @see #setRotationY(float)
9936     *
9937     * @attr ref android.R.styleable#View_rotation
9938     */
9939    public void setRotation(float rotation) {
9940        if (rotation != getRotation()) {
9941            // Double-invalidation is necessary to capture view's old and new areas
9942            invalidateViewProperty(true, false);
9943            mRenderNode.setRotation(rotation);
9944            invalidateViewProperty(false, true);
9945
9946            invalidateParentIfNeededAndWasQuickRejected();
9947            notifySubtreeAccessibilityStateChangedIfNeeded();
9948        }
9949    }
9950
9951    /**
9952     * The degrees that the view is rotated around the vertical axis through the pivot point.
9953     *
9954     * @see #getPivotX()
9955     * @see #getPivotY()
9956     * @see #setRotationY(float)
9957     *
9958     * @return The degrees of Y rotation.
9959     */
9960    @ViewDebug.ExportedProperty(category = "drawing")
9961    public float getRotationY() {
9962        return mRenderNode.getRotationY();
9963    }
9964
9965    /**
9966     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
9967     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
9968     * down the y axis.
9969     *
9970     * When rotating large views, it is recommended to adjust the camera distance
9971     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
9972     *
9973     * @param rotationY The degrees of Y rotation.
9974     *
9975     * @see #getRotationY()
9976     * @see #getPivotX()
9977     * @see #getPivotY()
9978     * @see #setRotation(float)
9979     * @see #setRotationX(float)
9980     * @see #setCameraDistance(float)
9981     *
9982     * @attr ref android.R.styleable#View_rotationY
9983     */
9984    public void setRotationY(float rotationY) {
9985        if (rotationY != getRotationY()) {
9986            invalidateViewProperty(true, false);
9987            mRenderNode.setRotationY(rotationY);
9988            invalidateViewProperty(false, true);
9989
9990            invalidateParentIfNeededAndWasQuickRejected();
9991            notifySubtreeAccessibilityStateChangedIfNeeded();
9992        }
9993    }
9994
9995    /**
9996     * The degrees that the view is rotated around the horizontal axis through the pivot point.
9997     *
9998     * @see #getPivotX()
9999     * @see #getPivotY()
10000     * @see #setRotationX(float)
10001     *
10002     * @return The degrees of X rotation.
10003     */
10004    @ViewDebug.ExportedProperty(category = "drawing")
10005    public float getRotationX() {
10006        return mRenderNode.getRotationX();
10007    }
10008
10009    /**
10010     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
10011     * Increasing values result in clockwise rotation from the viewpoint of looking down the
10012     * x axis.
10013     *
10014     * When rotating large views, it is recommended to adjust the camera distance
10015     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
10016     *
10017     * @param rotationX The degrees of X rotation.
10018     *
10019     * @see #getRotationX()
10020     * @see #getPivotX()
10021     * @see #getPivotY()
10022     * @see #setRotation(float)
10023     * @see #setRotationY(float)
10024     * @see #setCameraDistance(float)
10025     *
10026     * @attr ref android.R.styleable#View_rotationX
10027     */
10028    public void setRotationX(float rotationX) {
10029        if (rotationX != getRotationX()) {
10030            invalidateViewProperty(true, false);
10031            mRenderNode.setRotationX(rotationX);
10032            invalidateViewProperty(false, true);
10033
10034            invalidateParentIfNeededAndWasQuickRejected();
10035            notifySubtreeAccessibilityStateChangedIfNeeded();
10036        }
10037    }
10038
10039    /**
10040     * The amount that the view is scaled in x around the pivot point, as a proportion of
10041     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
10042     *
10043     * <p>By default, this is 1.0f.
10044     *
10045     * @see #getPivotX()
10046     * @see #getPivotY()
10047     * @return The scaling factor.
10048     */
10049    @ViewDebug.ExportedProperty(category = "drawing")
10050    public float getScaleX() {
10051        return mRenderNode.getScaleX();
10052    }
10053
10054    /**
10055     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
10056     * the view's unscaled width. A value of 1 means that no scaling is applied.
10057     *
10058     * @param scaleX The scaling factor.
10059     * @see #getPivotX()
10060     * @see #getPivotY()
10061     *
10062     * @attr ref android.R.styleable#View_scaleX
10063     */
10064    public void setScaleX(float scaleX) {
10065        if (scaleX != getScaleX()) {
10066            invalidateViewProperty(true, false);
10067            mRenderNode.setScaleX(scaleX);
10068            invalidateViewProperty(false, true);
10069
10070            invalidateParentIfNeededAndWasQuickRejected();
10071            notifySubtreeAccessibilityStateChangedIfNeeded();
10072        }
10073    }
10074
10075    /**
10076     * The amount that the view is scaled in y around the pivot point, as a proportion of
10077     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
10078     *
10079     * <p>By default, this is 1.0f.
10080     *
10081     * @see #getPivotX()
10082     * @see #getPivotY()
10083     * @return The scaling factor.
10084     */
10085    @ViewDebug.ExportedProperty(category = "drawing")
10086    public float getScaleY() {
10087        return mRenderNode.getScaleY();
10088    }
10089
10090    /**
10091     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
10092     * the view's unscaled width. A value of 1 means that no scaling is applied.
10093     *
10094     * @param scaleY The scaling factor.
10095     * @see #getPivotX()
10096     * @see #getPivotY()
10097     *
10098     * @attr ref android.R.styleable#View_scaleY
10099     */
10100    public void setScaleY(float scaleY) {
10101        if (scaleY != getScaleY()) {
10102            invalidateViewProperty(true, false);
10103            mRenderNode.setScaleY(scaleY);
10104            invalidateViewProperty(false, true);
10105
10106            invalidateParentIfNeededAndWasQuickRejected();
10107            notifySubtreeAccessibilityStateChangedIfNeeded();
10108        }
10109    }
10110
10111    /**
10112     * The x location of the point around which the view is {@link #setRotation(float) rotated}
10113     * and {@link #setScaleX(float) scaled}.
10114     *
10115     * @see #getRotation()
10116     * @see #getScaleX()
10117     * @see #getScaleY()
10118     * @see #getPivotY()
10119     * @return The x location of the pivot point.
10120     *
10121     * @attr ref android.R.styleable#View_transformPivotX
10122     */
10123    @ViewDebug.ExportedProperty(category = "drawing")
10124    public float getPivotX() {
10125        return mRenderNode.getPivotX();
10126    }
10127
10128    /**
10129     * Sets the x location of the point around which the view is
10130     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
10131     * By default, the pivot point is centered on the object.
10132     * Setting this property disables this behavior and causes the view to use only the
10133     * explicitly set pivotX and pivotY values.
10134     *
10135     * @param pivotX The x location of the pivot point.
10136     * @see #getRotation()
10137     * @see #getScaleX()
10138     * @see #getScaleY()
10139     * @see #getPivotY()
10140     *
10141     * @attr ref android.R.styleable#View_transformPivotX
10142     */
10143    public void setPivotX(float pivotX) {
10144        if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) {
10145            invalidateViewProperty(true, false);
10146            mRenderNode.setPivotX(pivotX);
10147            invalidateViewProperty(false, true);
10148
10149            invalidateParentIfNeededAndWasQuickRejected();
10150        }
10151    }
10152
10153    /**
10154     * The y location of the point around which the view is {@link #setRotation(float) rotated}
10155     * and {@link #setScaleY(float) scaled}.
10156     *
10157     * @see #getRotation()
10158     * @see #getScaleX()
10159     * @see #getScaleY()
10160     * @see #getPivotY()
10161     * @return The y location of the pivot point.
10162     *
10163     * @attr ref android.R.styleable#View_transformPivotY
10164     */
10165    @ViewDebug.ExportedProperty(category = "drawing")
10166    public float getPivotY() {
10167        return mRenderNode.getPivotY();
10168    }
10169
10170    /**
10171     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
10172     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
10173     * Setting this property disables this behavior and causes the view to use only the
10174     * explicitly set pivotX and pivotY values.
10175     *
10176     * @param pivotY The y location of the pivot point.
10177     * @see #getRotation()
10178     * @see #getScaleX()
10179     * @see #getScaleY()
10180     * @see #getPivotY()
10181     *
10182     * @attr ref android.R.styleable#View_transformPivotY
10183     */
10184    public void setPivotY(float pivotY) {
10185        if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) {
10186            invalidateViewProperty(true, false);
10187            mRenderNode.setPivotY(pivotY);
10188            invalidateViewProperty(false, true);
10189
10190            invalidateParentIfNeededAndWasQuickRejected();
10191        }
10192    }
10193
10194    /**
10195     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
10196     * completely transparent and 1 means the view is completely opaque.
10197     *
10198     * <p>By default this is 1.0f.
10199     * @return The opacity of the view.
10200     */
10201    @ViewDebug.ExportedProperty(category = "drawing")
10202    public float getAlpha() {
10203        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
10204    }
10205
10206    /**
10207     * Returns whether this View has content which overlaps.
10208     *
10209     * <p>This function, intended to be overridden by specific View types, is an optimization when
10210     * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to
10211     * an offscreen buffer and then composited into place, which can be expensive. If the view has
10212     * no overlapping rendering, the view can draw each primitive with the appropriate alpha value
10213     * directly. An example of overlapping rendering is a TextView with a background image, such as
10214     * a Button. An example of non-overlapping rendering is a TextView with no background, or an
10215     * ImageView with only the foreground image. The default implementation returns true; subclasses
10216     * should override if they have cases which can be optimized.</p>
10217     *
10218     * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas}
10219     * necessitates that a View return true if it uses the methods internally without passing the
10220     * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p>
10221     *
10222     * @return true if the content in this view might overlap, false otherwise.
10223     */
10224    public boolean hasOverlappingRendering() {
10225        return true;
10226    }
10227
10228    /**
10229     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
10230     * completely transparent and 1 means the view is completely opaque.</p>
10231     *
10232     * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant
10233     * performance implications, especially for large views. It is best to use the alpha property
10234     * sparingly and transiently, as in the case of fading animations.</p>
10235     *
10236     * <p>For a view with a frequently changing alpha, such as during a fading animation, it is
10237     * strongly recommended for performance reasons to either override
10238     * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a
10239     * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p>
10240     *
10241     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
10242     * responsible for applying the opacity itself.</p>
10243     *
10244     * <p>Note that if the view is backed by a
10245     * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a
10246     * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than
10247     * 1.0 will supercede the alpha of the layer paint.</p>
10248     *
10249     * @param alpha The opacity of the view.
10250     *
10251     * @see #hasOverlappingRendering()
10252     * @see #setLayerType(int, android.graphics.Paint)
10253     *
10254     * @attr ref android.R.styleable#View_alpha
10255     */
10256    public void setAlpha(float alpha) {
10257        ensureTransformationInfo();
10258        if (mTransformationInfo.mAlpha != alpha) {
10259            mTransformationInfo.mAlpha = alpha;
10260            if (onSetAlpha((int) (alpha * 255))) {
10261                mPrivateFlags |= PFLAG_ALPHA_SET;
10262                // subclass is handling alpha - don't optimize rendering cache invalidation
10263                invalidateParentCaches();
10264                invalidate(true);
10265            } else {
10266                mPrivateFlags &= ~PFLAG_ALPHA_SET;
10267                invalidateViewProperty(true, false);
10268                mRenderNode.setAlpha(getFinalAlpha());
10269                notifyViewAccessibilityStateChangedIfNeeded(
10270                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
10271            }
10272        }
10273    }
10274
10275    /**
10276     * Faster version of setAlpha() which performs the same steps except there are
10277     * no calls to invalidate(). The caller of this function should perform proper invalidation
10278     * on the parent and this object. The return value indicates whether the subclass handles
10279     * alpha (the return value for onSetAlpha()).
10280     *
10281     * @param alpha The new value for the alpha property
10282     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
10283     *         the new value for the alpha property is different from the old value
10284     */
10285    boolean setAlphaNoInvalidation(float alpha) {
10286        ensureTransformationInfo();
10287        if (mTransformationInfo.mAlpha != alpha) {
10288            mTransformationInfo.mAlpha = alpha;
10289            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
10290            if (subclassHandlesAlpha) {
10291                mPrivateFlags |= PFLAG_ALPHA_SET;
10292                return true;
10293            } else {
10294                mPrivateFlags &= ~PFLAG_ALPHA_SET;
10295                mRenderNode.setAlpha(getFinalAlpha());
10296            }
10297        }
10298        return false;
10299    }
10300
10301    /**
10302     * This property is hidden and intended only for use by the Fade transition, which
10303     * animates it to produce a visual translucency that does not side-effect (or get
10304     * affected by) the real alpha property. This value is composited with the other
10305     * alpha value (and the AlphaAnimation value, when that is present) to produce
10306     * a final visual translucency result, which is what is passed into the DisplayList.
10307     *
10308     * @hide
10309     */
10310    public void setTransitionAlpha(float alpha) {
10311        ensureTransformationInfo();
10312        if (mTransformationInfo.mTransitionAlpha != alpha) {
10313            mTransformationInfo.mTransitionAlpha = alpha;
10314            mPrivateFlags &= ~PFLAG_ALPHA_SET;
10315            invalidateViewProperty(true, false);
10316            mRenderNode.setAlpha(getFinalAlpha());
10317        }
10318    }
10319
10320    /**
10321     * Calculates the visual alpha of this view, which is a combination of the actual
10322     * alpha value and the transitionAlpha value (if set).
10323     */
10324    private float getFinalAlpha() {
10325        if (mTransformationInfo != null) {
10326            return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha;
10327        }
10328        return 1;
10329    }
10330
10331    /**
10332     * This property is hidden and intended only for use by the Fade transition, which
10333     * animates it to produce a visual translucency that does not side-effect (or get
10334     * affected by) the real alpha property. This value is composited with the other
10335     * alpha value (and the AlphaAnimation value, when that is present) to produce
10336     * a final visual translucency result, which is what is passed into the DisplayList.
10337     *
10338     * @hide
10339     */
10340    @ViewDebug.ExportedProperty(category = "drawing")
10341    public float getTransitionAlpha() {
10342        return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1;
10343    }
10344
10345    /**
10346     * Top position of this view relative to its parent.
10347     *
10348     * @return The top of this view, in pixels.
10349     */
10350    @ViewDebug.CapturedViewProperty
10351    public final int getTop() {
10352        return mTop;
10353    }
10354
10355    /**
10356     * Sets the top position of this view relative to its parent. This method is meant to be called
10357     * by the layout system and should not generally be called otherwise, because the property
10358     * may be changed at any time by the layout.
10359     *
10360     * @param top The top of this view, in pixels.
10361     */
10362    public final void setTop(int top) {
10363        if (top != mTop) {
10364            final boolean matrixIsIdentity = hasIdentityMatrix();
10365            if (matrixIsIdentity) {
10366                if (mAttachInfo != null) {
10367                    int minTop;
10368                    int yLoc;
10369                    if (top < mTop) {
10370                        minTop = top;
10371                        yLoc = top - mTop;
10372                    } else {
10373                        minTop = mTop;
10374                        yLoc = 0;
10375                    }
10376                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
10377                }
10378            } else {
10379                // Double-invalidation is necessary to capture view's old and new areas
10380                invalidate(true);
10381            }
10382
10383            int width = mRight - mLeft;
10384            int oldHeight = mBottom - mTop;
10385
10386            mTop = top;
10387            mRenderNode.setTop(mTop);
10388
10389            sizeChange(width, mBottom - mTop, width, oldHeight);
10390
10391            if (!matrixIsIdentity) {
10392                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10393                invalidate(true);
10394            }
10395            mBackgroundSizeChanged = true;
10396            invalidateParentIfNeeded();
10397            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10398                // View was rejected last time it was drawn by its parent; this may have changed
10399                invalidateParentIfNeeded();
10400            }
10401        }
10402    }
10403
10404    /**
10405     * Bottom position of this view relative to its parent.
10406     *
10407     * @return The bottom of this view, in pixels.
10408     */
10409    @ViewDebug.CapturedViewProperty
10410    public final int getBottom() {
10411        return mBottom;
10412    }
10413
10414    /**
10415     * True if this view has changed since the last time being drawn.
10416     *
10417     * @return The dirty state of this view.
10418     */
10419    public boolean isDirty() {
10420        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
10421    }
10422
10423    /**
10424     * Sets the bottom position of this view relative to its parent. This method is meant to be
10425     * called by the layout system and should not generally be called otherwise, because the
10426     * property may be changed at any time by the layout.
10427     *
10428     * @param bottom The bottom of this view, in pixels.
10429     */
10430    public final void setBottom(int bottom) {
10431        if (bottom != mBottom) {
10432            final boolean matrixIsIdentity = hasIdentityMatrix();
10433            if (matrixIsIdentity) {
10434                if (mAttachInfo != null) {
10435                    int maxBottom;
10436                    if (bottom < mBottom) {
10437                        maxBottom = mBottom;
10438                    } else {
10439                        maxBottom = bottom;
10440                    }
10441                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
10442                }
10443            } else {
10444                // Double-invalidation is necessary to capture view's old and new areas
10445                invalidate(true);
10446            }
10447
10448            int width = mRight - mLeft;
10449            int oldHeight = mBottom - mTop;
10450
10451            mBottom = bottom;
10452            mRenderNode.setBottom(mBottom);
10453
10454            sizeChange(width, mBottom - mTop, width, oldHeight);
10455
10456            if (!matrixIsIdentity) {
10457                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10458                invalidate(true);
10459            }
10460            mBackgroundSizeChanged = true;
10461            invalidateParentIfNeeded();
10462            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10463                // View was rejected last time it was drawn by its parent; this may have changed
10464                invalidateParentIfNeeded();
10465            }
10466        }
10467    }
10468
10469    /**
10470     * Left position of this view relative to its parent.
10471     *
10472     * @return The left edge of this view, in pixels.
10473     */
10474    @ViewDebug.CapturedViewProperty
10475    public final int getLeft() {
10476        return mLeft;
10477    }
10478
10479    /**
10480     * Sets the left position of this view relative to its parent. This method is meant to be called
10481     * by the layout system and should not generally be called otherwise, because the property
10482     * may be changed at any time by the layout.
10483     *
10484     * @param left The left of this view, in pixels.
10485     */
10486    public final void setLeft(int left) {
10487        if (left != mLeft) {
10488            final boolean matrixIsIdentity = hasIdentityMatrix();
10489            if (matrixIsIdentity) {
10490                if (mAttachInfo != null) {
10491                    int minLeft;
10492                    int xLoc;
10493                    if (left < mLeft) {
10494                        minLeft = left;
10495                        xLoc = left - mLeft;
10496                    } else {
10497                        minLeft = mLeft;
10498                        xLoc = 0;
10499                    }
10500                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
10501                }
10502            } else {
10503                // Double-invalidation is necessary to capture view's old and new areas
10504                invalidate(true);
10505            }
10506
10507            int oldWidth = mRight - mLeft;
10508            int height = mBottom - mTop;
10509
10510            mLeft = left;
10511            mRenderNode.setLeft(left);
10512
10513            sizeChange(mRight - mLeft, height, oldWidth, height);
10514
10515            if (!matrixIsIdentity) {
10516                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10517                invalidate(true);
10518            }
10519            mBackgroundSizeChanged = true;
10520            invalidateParentIfNeeded();
10521            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10522                // View was rejected last time it was drawn by its parent; this may have changed
10523                invalidateParentIfNeeded();
10524            }
10525        }
10526    }
10527
10528    /**
10529     * Right position of this view relative to its parent.
10530     *
10531     * @return The right edge of this view, in pixels.
10532     */
10533    @ViewDebug.CapturedViewProperty
10534    public final int getRight() {
10535        return mRight;
10536    }
10537
10538    /**
10539     * Sets the right position of this view relative to its parent. This method is meant to be called
10540     * by the layout system and should not generally be called otherwise, because the property
10541     * may be changed at any time by the layout.
10542     *
10543     * @param right The right of this view, in pixels.
10544     */
10545    public final void setRight(int right) {
10546        if (right != mRight) {
10547            final boolean matrixIsIdentity = hasIdentityMatrix();
10548            if (matrixIsIdentity) {
10549                if (mAttachInfo != null) {
10550                    int maxRight;
10551                    if (right < mRight) {
10552                        maxRight = mRight;
10553                    } else {
10554                        maxRight = right;
10555                    }
10556                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
10557                }
10558            } else {
10559                // Double-invalidation is necessary to capture view's old and new areas
10560                invalidate(true);
10561            }
10562
10563            int oldWidth = mRight - mLeft;
10564            int height = mBottom - mTop;
10565
10566            mRight = right;
10567            mRenderNode.setRight(mRight);
10568
10569            sizeChange(mRight - mLeft, height, oldWidth, height);
10570
10571            if (!matrixIsIdentity) {
10572                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10573                invalidate(true);
10574            }
10575            mBackgroundSizeChanged = true;
10576            invalidateParentIfNeeded();
10577            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10578                // View was rejected last time it was drawn by its parent; this may have changed
10579                invalidateParentIfNeeded();
10580            }
10581        }
10582    }
10583
10584    /**
10585     * The visual x position of this view, in pixels. This is equivalent to the
10586     * {@link #setTranslationX(float) translationX} property plus the current
10587     * {@link #getLeft() left} property.
10588     *
10589     * @return The visual x position of this view, in pixels.
10590     */
10591    @ViewDebug.ExportedProperty(category = "drawing")
10592    public float getX() {
10593        return mLeft + getTranslationX();
10594    }
10595
10596    /**
10597     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
10598     * {@link #setTranslationX(float) translationX} property to be the difference between
10599     * the x value passed in and the current {@link #getLeft() left} property.
10600     *
10601     * @param x The visual x position of this view, in pixels.
10602     */
10603    public void setX(float x) {
10604        setTranslationX(x - mLeft);
10605    }
10606
10607    /**
10608     * The visual y position of this view, in pixels. This is equivalent to the
10609     * {@link #setTranslationY(float) translationY} property plus the current
10610     * {@link #getTop() top} property.
10611     *
10612     * @return The visual y position of this view, in pixels.
10613     */
10614    @ViewDebug.ExportedProperty(category = "drawing")
10615    public float getY() {
10616        return mTop + getTranslationY();
10617    }
10618
10619    /**
10620     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
10621     * {@link #setTranslationY(float) translationY} property to be the difference between
10622     * the y value passed in and the current {@link #getTop() top} property.
10623     *
10624     * @param y The visual y position of this view, in pixels.
10625     */
10626    public void setY(float y) {
10627        setTranslationY(y - mTop);
10628    }
10629
10630    /**
10631     * The visual z position of this view, in pixels. This is equivalent to the
10632     * {@link #setTranslationZ(float) translationZ} property plus the current
10633     * {@link #getElevation() elevation} property.
10634     *
10635     * @return The visual z position of this view, in pixels.
10636     */
10637    @ViewDebug.ExportedProperty(category = "drawing")
10638    public float getZ() {
10639        return getElevation() + getTranslationZ();
10640    }
10641
10642    /**
10643     * Sets the visual z position of this view, in pixels. This is equivalent to setting the
10644     * {@link #setTranslationZ(float) translationZ} property to be the difference between
10645     * the x value passed in and the current {@link #getElevation() elevation} property.
10646     *
10647     * @param z The visual z position of this view, in pixels.
10648     */
10649    public void setZ(float z) {
10650        setTranslationZ(z - getElevation());
10651    }
10652
10653    /**
10654     * The base elevation of this view relative to its parent, in pixels.
10655     *
10656     * @return The base depth position of the view, in pixels.
10657     */
10658    @ViewDebug.ExportedProperty(category = "drawing")
10659    public float getElevation() {
10660        return mRenderNode.getElevation();
10661    }
10662
10663    /**
10664     * Sets the base elevation of this view, in pixels.
10665     *
10666     * @attr ref android.R.styleable#View_elevation
10667     */
10668    public void setElevation(float elevation) {
10669        if (elevation != getElevation()) {
10670            invalidateViewProperty(true, false);
10671            mRenderNode.setElevation(elevation);
10672            invalidateViewProperty(false, true);
10673
10674            invalidateParentIfNeededAndWasQuickRejected();
10675        }
10676    }
10677
10678    /**
10679     * The horizontal location of this view relative to its {@link #getLeft() left} position.
10680     * This position is post-layout, in addition to wherever the object's
10681     * layout placed it.
10682     *
10683     * @return The horizontal position of this view relative to its left position, in pixels.
10684     */
10685    @ViewDebug.ExportedProperty(category = "drawing")
10686    public float getTranslationX() {
10687        return mRenderNode.getTranslationX();
10688    }
10689
10690    /**
10691     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
10692     * This effectively positions the object post-layout, in addition to wherever the object's
10693     * layout placed it.
10694     *
10695     * @param translationX The horizontal position of this view relative to its left position,
10696     * in pixels.
10697     *
10698     * @attr ref android.R.styleable#View_translationX
10699     */
10700    public void setTranslationX(float translationX) {
10701        if (translationX != getTranslationX()) {
10702            invalidateViewProperty(true, false);
10703            mRenderNode.setTranslationX(translationX);
10704            invalidateViewProperty(false, true);
10705
10706            invalidateParentIfNeededAndWasQuickRejected();
10707            notifySubtreeAccessibilityStateChangedIfNeeded();
10708        }
10709    }
10710
10711    /**
10712     * The vertical location of this view relative to its {@link #getTop() top} position.
10713     * This position is post-layout, in addition to wherever the object's
10714     * layout placed it.
10715     *
10716     * @return The vertical position of this view relative to its top position,
10717     * in pixels.
10718     */
10719    @ViewDebug.ExportedProperty(category = "drawing")
10720    public float getTranslationY() {
10721        return mRenderNode.getTranslationY();
10722    }
10723
10724    /**
10725     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
10726     * This effectively positions the object post-layout, in addition to wherever the object's
10727     * layout placed it.
10728     *
10729     * @param translationY The vertical position of this view relative to its top position,
10730     * in pixels.
10731     *
10732     * @attr ref android.R.styleable#View_translationY
10733     */
10734    public void setTranslationY(float translationY) {
10735        if (translationY != getTranslationY()) {
10736            invalidateViewProperty(true, false);
10737            mRenderNode.setTranslationY(translationY);
10738            invalidateViewProperty(false, true);
10739
10740            invalidateParentIfNeededAndWasQuickRejected();
10741        }
10742    }
10743
10744    /**
10745     * The depth location of this view relative to its {@link #getElevation() elevation}.
10746     *
10747     * @return The depth of this view relative to its elevation.
10748     */
10749    @ViewDebug.ExportedProperty(category = "drawing")
10750    public float getTranslationZ() {
10751        return mRenderNode.getTranslationZ();
10752    }
10753
10754    /**
10755     * Sets the depth location of this view relative to its {@link #getElevation() elevation}.
10756     *
10757     * @attr ref android.R.styleable#View_translationZ
10758     */
10759    public void setTranslationZ(float translationZ) {
10760        if (translationZ != getTranslationZ()) {
10761            invalidateViewProperty(true, false);
10762            mRenderNode.setTranslationZ(translationZ);
10763            invalidateViewProperty(false, true);
10764
10765            invalidateParentIfNeededAndWasQuickRejected();
10766        }
10767    }
10768
10769    /** @hide */
10770    public void setAnimationMatrix(Matrix matrix) {
10771        invalidateViewProperty(true, false);
10772        mRenderNode.setAnimationMatrix(matrix);
10773        invalidateViewProperty(false, true);
10774
10775        invalidateParentIfNeededAndWasQuickRejected();
10776    }
10777
10778    /**
10779     * Returns the current StateListAnimator if exists.
10780     *
10781     * @return StateListAnimator or null if it does not exists
10782     * @see    #setStateListAnimator(android.animation.StateListAnimator)
10783     */
10784    public StateListAnimator getStateListAnimator() {
10785        return mStateListAnimator;
10786    }
10787
10788    /**
10789     * Attaches the provided StateListAnimator to this View.
10790     * <p>
10791     * Any previously attached StateListAnimator will be detached.
10792     *
10793     * @param stateListAnimator The StateListAnimator to update the view
10794     * @see {@link android.animation.StateListAnimator}
10795     */
10796    public void setStateListAnimator(StateListAnimator stateListAnimator) {
10797        if (mStateListAnimator == stateListAnimator) {
10798            return;
10799        }
10800        if (mStateListAnimator != null) {
10801            mStateListAnimator.setTarget(null);
10802        }
10803        mStateListAnimator = stateListAnimator;
10804        if (stateListAnimator != null) {
10805            stateListAnimator.setTarget(this);
10806            if (isAttachedToWindow()) {
10807                stateListAnimator.setState(getDrawableState());
10808            }
10809        }
10810    }
10811
10812    /**
10813     * Returns whether the Outline should be used to clip the contents of the View.
10814     * <p>
10815     * Note that this flag will only be respected if the View's Outline returns true from
10816     * {@link Outline#canClip()}.
10817     *
10818     * @see #setOutlineProvider(ViewOutlineProvider)
10819     * @see #setClipToOutline(boolean)
10820     */
10821    public final boolean getClipToOutline() {
10822        return mRenderNode.getClipToOutline();
10823    }
10824
10825    /**
10826     * Sets whether the View's Outline should be used to clip the contents of the View.
10827     * <p>
10828     * Note that this flag will only be respected if the View's Outline returns true from
10829     * {@link Outline#canClip()}.
10830     *
10831     * @see #setOutlineProvider(ViewOutlineProvider)
10832     * @see #getClipToOutline()
10833     */
10834    public void setClipToOutline(boolean clipToOutline) {
10835        damageInParent();
10836        if (getClipToOutline() != clipToOutline) {
10837            mRenderNode.setClipToOutline(clipToOutline);
10838        }
10839    }
10840
10841    // correspond to the enum values of View_outlineProvider
10842    private static final int PROVIDER_BACKGROUND = 0;
10843    private static final int PROVIDER_NONE = 1;
10844    private static final int PROVIDER_BOUNDS = 2;
10845    private static final int PROVIDER_PADDED_BOUNDS = 3;
10846    private void setOutlineProviderFromAttribute(int providerInt) {
10847        switch (providerInt) {
10848            case PROVIDER_BACKGROUND:
10849                setOutlineProvider(ViewOutlineProvider.BACKGROUND);
10850                break;
10851            case PROVIDER_NONE:
10852                setOutlineProvider(null);
10853                break;
10854            case PROVIDER_BOUNDS:
10855                setOutlineProvider(ViewOutlineProvider.BOUNDS);
10856                break;
10857            case PROVIDER_PADDED_BOUNDS:
10858                setOutlineProvider(ViewOutlineProvider.PADDED_BOUNDS);
10859                break;
10860        }
10861    }
10862
10863    /**
10864     * Sets the {@link ViewOutlineProvider} of the view, which generates the Outline that defines
10865     * the shape of the shadow it casts, and enables outline clipping.
10866     * <p>
10867     * The default ViewOutlineProvider, {@link ViewOutlineProvider#BACKGROUND}, queries the Outline
10868     * from the View's background drawable, via {@link Drawable#getOutline(Outline)}. Changing the
10869     * outline provider with this method allows this behavior to be overridden.
10870     * <p>
10871     * If the ViewOutlineProvider is null, if querying it for an outline returns false,
10872     * or if the produced Outline is {@link Outline#isEmpty()}, shadows will not be cast.
10873     * <p>
10874     * Only outlines that return true from {@link Outline#canClip()} may be used for clipping.
10875     *
10876     * @see #setClipToOutline(boolean)
10877     * @see #getClipToOutline()
10878     * @see #getOutlineProvider()
10879     */
10880    public void setOutlineProvider(ViewOutlineProvider provider) {
10881        mOutlineProvider = provider;
10882        invalidateOutline();
10883    }
10884
10885    /**
10886     * Returns the current {@link ViewOutlineProvider} of the view, which generates the Outline
10887     * that defines the shape of the shadow it casts, and enables outline clipping.
10888     *
10889     * @see #setOutlineProvider(ViewOutlineProvider)
10890     */
10891    public ViewOutlineProvider getOutlineProvider() {
10892        return mOutlineProvider;
10893    }
10894
10895    /**
10896     * Called to rebuild this View's Outline from its {@link ViewOutlineProvider outline provider}
10897     *
10898     * @see #setOutlineProvider(ViewOutlineProvider)
10899     */
10900    public void invalidateOutline() {
10901        // Unattached views ignore this signal, and outline is recomputed in onAttachedToWindow()
10902        if (mAttachInfo == null) return;
10903
10904        if (mOutlineProvider == null) {
10905            // no provider, remove outline
10906            mRenderNode.setOutline(null);
10907        } else {
10908            final Outline outline = mAttachInfo.mTmpOutline;
10909            outline.setEmpty();
10910            outline.setAlpha(1.0f);
10911
10912            mOutlineProvider.getOutline(this, outline);
10913            mRenderNode.setOutline(outline);
10914        }
10915
10916        notifySubtreeAccessibilityStateChangedIfNeeded();
10917        invalidateViewProperty(false, false);
10918    }
10919
10920    /** @hide */
10921    public void setRevealClip(boolean shouldClip, float x, float y, float radius) {
10922        mRenderNode.setRevealClip(shouldClip, x, y, radius);
10923        invalidateViewProperty(false, false);
10924    }
10925
10926    /**
10927     * Hit rectangle in parent's coordinates
10928     *
10929     * @param outRect The hit rectangle of the view.
10930     */
10931    public void getHitRect(Rect outRect) {
10932        if (hasIdentityMatrix() || mAttachInfo == null) {
10933            outRect.set(mLeft, mTop, mRight, mBottom);
10934        } else {
10935            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
10936            tmpRect.set(0, 0, getWidth(), getHeight());
10937            getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect)
10938            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
10939                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
10940        }
10941    }
10942
10943    /**
10944     * Determines whether the given point, in local coordinates is inside the view.
10945     */
10946    /*package*/ final boolean pointInView(float localX, float localY) {
10947        return localX >= 0 && localX < (mRight - mLeft)
10948                && localY >= 0 && localY < (mBottom - mTop);
10949    }
10950
10951    /**
10952     * Utility method to determine whether the given point, in local coordinates,
10953     * is inside the view, where the area of the view is expanded by the slop factor.
10954     * This method is called while processing touch-move events to determine if the event
10955     * is still within the view.
10956     *
10957     * @hide
10958     */
10959    public boolean pointInView(float localX, float localY, float slop) {
10960        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
10961                localY < ((mBottom - mTop) + slop);
10962    }
10963
10964    /**
10965     * When a view has focus and the user navigates away from it, the next view is searched for
10966     * starting from the rectangle filled in by this method.
10967     *
10968     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
10969     * of the view.  However, if your view maintains some idea of internal selection,
10970     * such as a cursor, or a selected row or column, you should override this method and
10971     * fill in a more specific rectangle.
10972     *
10973     * @param r The rectangle to fill in, in this view's coordinates.
10974     */
10975    public void getFocusedRect(Rect r) {
10976        getDrawingRect(r);
10977    }
10978
10979    /**
10980     * If some part of this view is not clipped by any of its parents, then
10981     * return that area in r in global (root) coordinates. To convert r to local
10982     * coordinates (without taking possible View rotations into account), offset
10983     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
10984     * If the view is completely clipped or translated out, return false.
10985     *
10986     * @param r If true is returned, r holds the global coordinates of the
10987     *        visible portion of this view.
10988     * @param globalOffset If true is returned, globalOffset holds the dx,dy
10989     *        between this view and its root. globalOffet may be null.
10990     * @return true if r is non-empty (i.e. part of the view is visible at the
10991     *         root level.
10992     */
10993    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
10994        int width = mRight - mLeft;
10995        int height = mBottom - mTop;
10996        if (width > 0 && height > 0) {
10997            r.set(0, 0, width, height);
10998            if (globalOffset != null) {
10999                globalOffset.set(-mScrollX, -mScrollY);
11000            }
11001            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
11002        }
11003        return false;
11004    }
11005
11006    public final boolean getGlobalVisibleRect(Rect r) {
11007        return getGlobalVisibleRect(r, null);
11008    }
11009
11010    public final boolean getLocalVisibleRect(Rect r) {
11011        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
11012        if (getGlobalVisibleRect(r, offset)) {
11013            r.offset(-offset.x, -offset.y); // make r local
11014            return true;
11015        }
11016        return false;
11017    }
11018
11019    /**
11020     * Offset this view's vertical location by the specified number of pixels.
11021     *
11022     * @param offset the number of pixels to offset the view by
11023     */
11024    public void offsetTopAndBottom(int offset) {
11025        if (offset != 0) {
11026            final boolean matrixIsIdentity = hasIdentityMatrix();
11027            if (matrixIsIdentity) {
11028                if (isHardwareAccelerated()) {
11029                    invalidateViewProperty(false, false);
11030                } else {
11031                    final ViewParent p = mParent;
11032                    if (p != null && mAttachInfo != null) {
11033                        final Rect r = mAttachInfo.mTmpInvalRect;
11034                        int minTop;
11035                        int maxBottom;
11036                        int yLoc;
11037                        if (offset < 0) {
11038                            minTop = mTop + offset;
11039                            maxBottom = mBottom;
11040                            yLoc = offset;
11041                        } else {
11042                            minTop = mTop;
11043                            maxBottom = mBottom + offset;
11044                            yLoc = 0;
11045                        }
11046                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
11047                        p.invalidateChild(this, r);
11048                    }
11049                }
11050            } else {
11051                invalidateViewProperty(false, false);
11052            }
11053
11054            mTop += offset;
11055            mBottom += offset;
11056            mRenderNode.offsetTopAndBottom(offset);
11057            if (isHardwareAccelerated()) {
11058                invalidateViewProperty(false, false);
11059            } else {
11060                if (!matrixIsIdentity) {
11061                    invalidateViewProperty(false, true);
11062                }
11063                invalidateParentIfNeeded();
11064            }
11065            notifySubtreeAccessibilityStateChangedIfNeeded();
11066        }
11067    }
11068
11069    /**
11070     * Offset this view's horizontal location by the specified amount of pixels.
11071     *
11072     * @param offset the number of pixels to offset the view by
11073     */
11074    public void offsetLeftAndRight(int offset) {
11075        if (offset != 0) {
11076            final boolean matrixIsIdentity = hasIdentityMatrix();
11077            if (matrixIsIdentity) {
11078                if (isHardwareAccelerated()) {
11079                    invalidateViewProperty(false, false);
11080                } else {
11081                    final ViewParent p = mParent;
11082                    if (p != null && mAttachInfo != null) {
11083                        final Rect r = mAttachInfo.mTmpInvalRect;
11084                        int minLeft;
11085                        int maxRight;
11086                        if (offset < 0) {
11087                            minLeft = mLeft + offset;
11088                            maxRight = mRight;
11089                        } else {
11090                            minLeft = mLeft;
11091                            maxRight = mRight + offset;
11092                        }
11093                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
11094                        p.invalidateChild(this, r);
11095                    }
11096                }
11097            } else {
11098                invalidateViewProperty(false, false);
11099            }
11100
11101            mLeft += offset;
11102            mRight += offset;
11103            mRenderNode.offsetLeftAndRight(offset);
11104            if (isHardwareAccelerated()) {
11105                invalidateViewProperty(false, false);
11106            } else {
11107                if (!matrixIsIdentity) {
11108                    invalidateViewProperty(false, true);
11109                }
11110                invalidateParentIfNeeded();
11111            }
11112            notifySubtreeAccessibilityStateChangedIfNeeded();
11113        }
11114    }
11115
11116    /**
11117     * Get the LayoutParams associated with this view. All views should have
11118     * layout parameters. These supply parameters to the <i>parent</i> of this
11119     * view specifying how it should be arranged. There are many subclasses of
11120     * ViewGroup.LayoutParams, and these correspond to the different subclasses
11121     * of ViewGroup that are responsible for arranging their children.
11122     *
11123     * This method may return null if this View is not attached to a parent
11124     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
11125     * was not invoked successfully. When a View is attached to a parent
11126     * ViewGroup, this method must not return null.
11127     *
11128     * @return The LayoutParams associated with this view, or null if no
11129     *         parameters have been set yet
11130     */
11131    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
11132    public ViewGroup.LayoutParams getLayoutParams() {
11133        return mLayoutParams;
11134    }
11135
11136    /**
11137     * Set the layout parameters associated with this view. These supply
11138     * parameters to the <i>parent</i> of this view specifying how it should be
11139     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
11140     * correspond to the different subclasses of ViewGroup that are responsible
11141     * for arranging their children.
11142     *
11143     * @param params The layout parameters for this view, cannot be null
11144     */
11145    public void setLayoutParams(ViewGroup.LayoutParams params) {
11146        if (params == null) {
11147            throw new NullPointerException("Layout parameters cannot be null");
11148        }
11149        mLayoutParams = params;
11150        resolveLayoutParams();
11151        if (mParent instanceof ViewGroup) {
11152            ((ViewGroup) mParent).onSetLayoutParams(this, params);
11153        }
11154        requestLayout();
11155    }
11156
11157    /**
11158     * Resolve the layout parameters depending on the resolved layout direction
11159     *
11160     * @hide
11161     */
11162    public void resolveLayoutParams() {
11163        if (mLayoutParams != null) {
11164            mLayoutParams.resolveLayoutDirection(getLayoutDirection());
11165        }
11166    }
11167
11168    /**
11169     * Set the scrolled position of your view. This will cause a call to
11170     * {@link #onScrollChanged(int, int, int, int)} and the view will be
11171     * invalidated.
11172     * @param x the x position to scroll to
11173     * @param y the y position to scroll to
11174     */
11175    public void scrollTo(int x, int y) {
11176        if (mScrollX != x || mScrollY != y) {
11177            int oldX = mScrollX;
11178            int oldY = mScrollY;
11179            mScrollX = x;
11180            mScrollY = y;
11181            invalidateParentCaches();
11182            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
11183            if (!awakenScrollBars()) {
11184                postInvalidateOnAnimation();
11185            }
11186        }
11187    }
11188
11189    /**
11190     * Move the scrolled position of your view. This will cause a call to
11191     * {@link #onScrollChanged(int, int, int, int)} and the view will be
11192     * invalidated.
11193     * @param x the amount of pixels to scroll by horizontally
11194     * @param y the amount of pixels to scroll by vertically
11195     */
11196    public void scrollBy(int x, int y) {
11197        scrollTo(mScrollX + x, mScrollY + y);
11198    }
11199
11200    /**
11201     * <p>Trigger the scrollbars to draw. When invoked this method starts an
11202     * animation to fade the scrollbars out after a default delay. If a subclass
11203     * provides animated scrolling, the start delay should equal the duration
11204     * of the scrolling animation.</p>
11205     *
11206     * <p>The animation starts only if at least one of the scrollbars is
11207     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
11208     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11209     * this method returns true, and false otherwise. If the animation is
11210     * started, this method calls {@link #invalidate()}; in that case the
11211     * caller should not call {@link #invalidate()}.</p>
11212     *
11213     * <p>This method should be invoked every time a subclass directly updates
11214     * the scroll parameters.</p>
11215     *
11216     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
11217     * and {@link #scrollTo(int, int)}.</p>
11218     *
11219     * @return true if the animation is played, false otherwise
11220     *
11221     * @see #awakenScrollBars(int)
11222     * @see #scrollBy(int, int)
11223     * @see #scrollTo(int, int)
11224     * @see #isHorizontalScrollBarEnabled()
11225     * @see #isVerticalScrollBarEnabled()
11226     * @see #setHorizontalScrollBarEnabled(boolean)
11227     * @see #setVerticalScrollBarEnabled(boolean)
11228     */
11229    protected boolean awakenScrollBars() {
11230        return mScrollCache != null &&
11231                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
11232    }
11233
11234    /**
11235     * Trigger the scrollbars to draw.
11236     * This method differs from awakenScrollBars() only in its default duration.
11237     * initialAwakenScrollBars() will show the scroll bars for longer than
11238     * usual to give the user more of a chance to notice them.
11239     *
11240     * @return true if the animation is played, false otherwise.
11241     */
11242    private boolean initialAwakenScrollBars() {
11243        return mScrollCache != null &&
11244                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
11245    }
11246
11247    /**
11248     * <p>
11249     * Trigger the scrollbars to draw. When invoked this method starts an
11250     * animation to fade the scrollbars out after a fixed delay. If a subclass
11251     * provides animated scrolling, the start delay should equal the duration of
11252     * the scrolling animation.
11253     * </p>
11254     *
11255     * <p>
11256     * The animation starts only if at least one of the scrollbars is enabled,
11257     * as specified by {@link #isHorizontalScrollBarEnabled()} and
11258     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11259     * this method returns true, and false otherwise. If the animation is
11260     * started, this method calls {@link #invalidate()}; in that case the caller
11261     * should not call {@link #invalidate()}.
11262     * </p>
11263     *
11264     * <p>
11265     * This method should be invoked everytime a subclass directly updates the
11266     * scroll parameters.
11267     * </p>
11268     *
11269     * @param startDelay the delay, in milliseconds, after which the animation
11270     *        should start; when the delay is 0, the animation starts
11271     *        immediately
11272     * @return true if the animation is played, false otherwise
11273     *
11274     * @see #scrollBy(int, int)
11275     * @see #scrollTo(int, int)
11276     * @see #isHorizontalScrollBarEnabled()
11277     * @see #isVerticalScrollBarEnabled()
11278     * @see #setHorizontalScrollBarEnabled(boolean)
11279     * @see #setVerticalScrollBarEnabled(boolean)
11280     */
11281    protected boolean awakenScrollBars(int startDelay) {
11282        return awakenScrollBars(startDelay, true);
11283    }
11284
11285    /**
11286     * <p>
11287     * Trigger the scrollbars to draw. When invoked this method starts an
11288     * animation to fade the scrollbars out after a fixed delay. If a subclass
11289     * provides animated scrolling, the start delay should equal the duration of
11290     * the scrolling animation.
11291     * </p>
11292     *
11293     * <p>
11294     * The animation starts only if at least one of the scrollbars is enabled,
11295     * as specified by {@link #isHorizontalScrollBarEnabled()} and
11296     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11297     * this method returns true, and false otherwise. If the animation is
11298     * started, this method calls {@link #invalidate()} if the invalidate parameter
11299     * is set to true; in that case the caller
11300     * should not call {@link #invalidate()}.
11301     * </p>
11302     *
11303     * <p>
11304     * This method should be invoked everytime a subclass directly updates the
11305     * scroll parameters.
11306     * </p>
11307     *
11308     * @param startDelay the delay, in milliseconds, after which the animation
11309     *        should start; when the delay is 0, the animation starts
11310     *        immediately
11311     *
11312     * @param invalidate Wheter this method should call invalidate
11313     *
11314     * @return true if the animation is played, false otherwise
11315     *
11316     * @see #scrollBy(int, int)
11317     * @see #scrollTo(int, int)
11318     * @see #isHorizontalScrollBarEnabled()
11319     * @see #isVerticalScrollBarEnabled()
11320     * @see #setHorizontalScrollBarEnabled(boolean)
11321     * @see #setVerticalScrollBarEnabled(boolean)
11322     */
11323    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
11324        final ScrollabilityCache scrollCache = mScrollCache;
11325
11326        if (scrollCache == null || !scrollCache.fadeScrollBars) {
11327            return false;
11328        }
11329
11330        if (scrollCache.scrollBar == null) {
11331            scrollCache.scrollBar = new ScrollBarDrawable();
11332        }
11333
11334        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
11335
11336            if (invalidate) {
11337                // Invalidate to show the scrollbars
11338                postInvalidateOnAnimation();
11339            }
11340
11341            if (scrollCache.state == ScrollabilityCache.OFF) {
11342                // FIXME: this is copied from WindowManagerService.
11343                // We should get this value from the system when it
11344                // is possible to do so.
11345                final int KEY_REPEAT_FIRST_DELAY = 750;
11346                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
11347            }
11348
11349            // Tell mScrollCache when we should start fading. This may
11350            // extend the fade start time if one was already scheduled
11351            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
11352            scrollCache.fadeStartTime = fadeStartTime;
11353            scrollCache.state = ScrollabilityCache.ON;
11354
11355            // Schedule our fader to run, unscheduling any old ones first
11356            if (mAttachInfo != null) {
11357                mAttachInfo.mHandler.removeCallbacks(scrollCache);
11358                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
11359            }
11360
11361            return true;
11362        }
11363
11364        return false;
11365    }
11366
11367    /**
11368     * Do not invalidate views which are not visible and which are not running an animation. They
11369     * will not get drawn and they should not set dirty flags as if they will be drawn
11370     */
11371    private boolean skipInvalidate() {
11372        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
11373                (!(mParent instanceof ViewGroup) ||
11374                        !((ViewGroup) mParent).isViewTransitioning(this));
11375    }
11376
11377    /**
11378     * Mark the area defined by dirty as needing to be drawn. If the view is
11379     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
11380     * point in the future.
11381     * <p>
11382     * This must be called from a UI thread. To call from a non-UI thread, call
11383     * {@link #postInvalidate()}.
11384     * <p>
11385     * <b>WARNING:</b> In API 19 and below, this method may be destructive to
11386     * {@code dirty}.
11387     *
11388     * @param dirty the rectangle representing the bounds of the dirty region
11389     */
11390    public void invalidate(Rect dirty) {
11391        final int scrollX = mScrollX;
11392        final int scrollY = mScrollY;
11393        invalidateInternal(dirty.left - scrollX, dirty.top - scrollY,
11394                dirty.right - scrollX, dirty.bottom - scrollY, true, false);
11395    }
11396
11397    /**
11398     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The
11399     * coordinates of the dirty rect are relative to the view. If the view is
11400     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
11401     * point in the future.
11402     * <p>
11403     * This must be called from a UI thread. To call from a non-UI thread, call
11404     * {@link #postInvalidate()}.
11405     *
11406     * @param l the left position of the dirty region
11407     * @param t the top position of the dirty region
11408     * @param r the right position of the dirty region
11409     * @param b the bottom position of the dirty region
11410     */
11411    public void invalidate(int l, int t, int r, int b) {
11412        final int scrollX = mScrollX;
11413        final int scrollY = mScrollY;
11414        invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false);
11415    }
11416
11417    /**
11418     * Invalidate the whole view. If the view is visible,
11419     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
11420     * the future.
11421     * <p>
11422     * This must be called from a UI thread. To call from a non-UI thread, call
11423     * {@link #postInvalidate()}.
11424     */
11425    public void invalidate() {
11426        invalidate(true);
11427    }
11428
11429    /**
11430     * This is where the invalidate() work actually happens. A full invalidate()
11431     * causes the drawing cache to be invalidated, but this function can be
11432     * called with invalidateCache set to false to skip that invalidation step
11433     * for cases that do not need it (for example, a component that remains at
11434     * the same dimensions with the same content).
11435     *
11436     * @param invalidateCache Whether the drawing cache for this view should be
11437     *            invalidated as well. This is usually true for a full
11438     *            invalidate, but may be set to false if the View's contents or
11439     *            dimensions have not changed.
11440     */
11441    void invalidate(boolean invalidateCache) {
11442        invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true);
11443    }
11444
11445    void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache,
11446            boolean fullInvalidate) {
11447        if (mGhostView != null) {
11448            mGhostView.invalidate(invalidateCache);
11449            return;
11450        }
11451
11452        if (skipInvalidate()) {
11453            return;
11454        }
11455
11456        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)
11457                || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID)
11458                || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED
11459                || (fullInvalidate && isOpaque() != mLastIsOpaque)) {
11460            if (fullInvalidate) {
11461                mLastIsOpaque = isOpaque();
11462                mPrivateFlags &= ~PFLAG_DRAWN;
11463            }
11464
11465            mPrivateFlags |= PFLAG_DIRTY;
11466
11467            if (invalidateCache) {
11468                mPrivateFlags |= PFLAG_INVALIDATED;
11469                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
11470            }
11471
11472            // Propagate the damage rectangle to the parent view.
11473            final AttachInfo ai = mAttachInfo;
11474            final ViewParent p = mParent;
11475            if (p != null && ai != null && l < r && t < b) {
11476                final Rect damage = ai.mTmpInvalRect;
11477                damage.set(l, t, r, b);
11478                p.invalidateChild(this, damage);
11479            }
11480
11481            // Damage the entire projection receiver, if necessary.
11482            if (mBackground != null && mBackground.isProjected()) {
11483                final View receiver = getProjectionReceiver();
11484                if (receiver != null) {
11485                    receiver.damageInParent();
11486                }
11487            }
11488
11489            // Damage the entire IsolatedZVolume receiving this view's shadow.
11490            if (isHardwareAccelerated() && getZ() != 0) {
11491                damageShadowReceiver();
11492            }
11493        }
11494    }
11495
11496    /**
11497     * @return this view's projection receiver, or {@code null} if none exists
11498     */
11499    private View getProjectionReceiver() {
11500        ViewParent p = getParent();
11501        while (p != null && p instanceof View) {
11502            final View v = (View) p;
11503            if (v.isProjectionReceiver()) {
11504                return v;
11505            }
11506            p = p.getParent();
11507        }
11508
11509        return null;
11510    }
11511
11512    /**
11513     * @return whether the view is a projection receiver
11514     */
11515    private boolean isProjectionReceiver() {
11516        return mBackground != null;
11517    }
11518
11519    /**
11520     * Damage area of the screen that can be covered by this View's shadow.
11521     *
11522     * This method will guarantee that any changes to shadows cast by a View
11523     * are damaged on the screen for future redraw.
11524     */
11525    private void damageShadowReceiver() {
11526        final AttachInfo ai = mAttachInfo;
11527        if (ai != null) {
11528            ViewParent p = getParent();
11529            if (p != null && p instanceof ViewGroup) {
11530                final ViewGroup vg = (ViewGroup) p;
11531                vg.damageInParent();
11532            }
11533        }
11534    }
11535
11536    /**
11537     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
11538     * set any flags or handle all of the cases handled by the default invalidation methods.
11539     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
11540     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
11541     * walk up the hierarchy, transforming the dirty rect as necessary.
11542     *
11543     * The method also handles normal invalidation logic if display list properties are not
11544     * being used in this view. The invalidateParent and forceRedraw flags are used by that
11545     * backup approach, to handle these cases used in the various property-setting methods.
11546     *
11547     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
11548     * are not being used in this view
11549     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
11550     * list properties are not being used in this view
11551     */
11552    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
11553        if (!isHardwareAccelerated()
11554                || !mRenderNode.isValid()
11555                || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) {
11556            if (invalidateParent) {
11557                invalidateParentCaches();
11558            }
11559            if (forceRedraw) {
11560                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
11561            }
11562            invalidate(false);
11563        } else {
11564            damageInParent();
11565        }
11566        if (isHardwareAccelerated() && invalidateParent && getZ() != 0) {
11567            damageShadowReceiver();
11568        }
11569    }
11570
11571    /**
11572     * Tells the parent view to damage this view's bounds.
11573     *
11574     * @hide
11575     */
11576    protected void damageInParent() {
11577        final AttachInfo ai = mAttachInfo;
11578        final ViewParent p = mParent;
11579        if (p != null && ai != null) {
11580            final Rect r = ai.mTmpInvalRect;
11581            r.set(0, 0, mRight - mLeft, mBottom - mTop);
11582            if (mParent instanceof ViewGroup) {
11583                ((ViewGroup) mParent).damageChild(this, r);
11584            } else {
11585                mParent.invalidateChild(this, r);
11586            }
11587        }
11588    }
11589
11590    /**
11591     * Utility method to transform a given Rect by the current matrix of this view.
11592     */
11593    void transformRect(final Rect rect) {
11594        if (!getMatrix().isIdentity()) {
11595            RectF boundingRect = mAttachInfo.mTmpTransformRect;
11596            boundingRect.set(rect);
11597            getMatrix().mapRect(boundingRect);
11598            rect.set((int) Math.floor(boundingRect.left),
11599                    (int) Math.floor(boundingRect.top),
11600                    (int) Math.ceil(boundingRect.right),
11601                    (int) Math.ceil(boundingRect.bottom));
11602        }
11603    }
11604
11605    /**
11606     * Used to indicate that the parent of this view should clear its caches. This functionality
11607     * is used to force the parent to rebuild its display list (when hardware-accelerated),
11608     * which is necessary when various parent-managed properties of the view change, such as
11609     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
11610     * clears the parent caches and does not causes an invalidate event.
11611     *
11612     * @hide
11613     */
11614    protected void invalidateParentCaches() {
11615        if (mParent instanceof View) {
11616            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
11617        }
11618    }
11619
11620    /**
11621     * Used to indicate that the parent of this view should be invalidated. This functionality
11622     * is used to force the parent to rebuild its display list (when hardware-accelerated),
11623     * which is necessary when various parent-managed properties of the view change, such as
11624     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
11625     * an invalidation event to the parent.
11626     *
11627     * @hide
11628     */
11629    protected void invalidateParentIfNeeded() {
11630        if (isHardwareAccelerated() && mParent instanceof View) {
11631            ((View) mParent).invalidate(true);
11632        }
11633    }
11634
11635    /**
11636     * @hide
11637     */
11638    protected void invalidateParentIfNeededAndWasQuickRejected() {
11639        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) {
11640            // View was rejected last time it was drawn by its parent; this may have changed
11641            invalidateParentIfNeeded();
11642        }
11643    }
11644
11645    /**
11646     * Indicates whether this View is opaque. An opaque View guarantees that it will
11647     * draw all the pixels overlapping its bounds using a fully opaque color.
11648     *
11649     * Subclasses of View should override this method whenever possible to indicate
11650     * whether an instance is opaque. Opaque Views are treated in a special way by
11651     * the View hierarchy, possibly allowing it to perform optimizations during
11652     * invalidate/draw passes.
11653     *
11654     * @return True if this View is guaranteed to be fully opaque, false otherwise.
11655     */
11656    @ViewDebug.ExportedProperty(category = "drawing")
11657    public boolean isOpaque() {
11658        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
11659                getFinalAlpha() >= 1.0f;
11660    }
11661
11662    /**
11663     * @hide
11664     */
11665    protected void computeOpaqueFlags() {
11666        // Opaque if:
11667        //   - Has a background
11668        //   - Background is opaque
11669        //   - Doesn't have scrollbars or scrollbars overlay
11670
11671        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
11672            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
11673        } else {
11674            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
11675        }
11676
11677        final int flags = mViewFlags;
11678        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
11679                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY ||
11680                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) {
11681            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
11682        } else {
11683            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
11684        }
11685    }
11686
11687    /**
11688     * @hide
11689     */
11690    protected boolean hasOpaqueScrollbars() {
11691        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
11692    }
11693
11694    /**
11695     * @return A handler associated with the thread running the View. This
11696     * handler can be used to pump events in the UI events queue.
11697     */
11698    public Handler getHandler() {
11699        final AttachInfo attachInfo = mAttachInfo;
11700        if (attachInfo != null) {
11701            return attachInfo.mHandler;
11702        }
11703        return null;
11704    }
11705
11706    /**
11707     * Gets the view root associated with the View.
11708     * @return The view root, or null if none.
11709     * @hide
11710     */
11711    public ViewRootImpl getViewRootImpl() {
11712        if (mAttachInfo != null) {
11713            return mAttachInfo.mViewRootImpl;
11714        }
11715        return null;
11716    }
11717
11718    /**
11719     * @hide
11720     */
11721    public HardwareRenderer getHardwareRenderer() {
11722        return mAttachInfo != null ? mAttachInfo.mHardwareRenderer : null;
11723    }
11724
11725    /**
11726     * <p>Causes the Runnable to be added to the message queue.
11727     * The runnable will be run on the user interface thread.</p>
11728     *
11729     * @param action The Runnable that will be executed.
11730     *
11731     * @return Returns true if the Runnable was successfully placed in to the
11732     *         message queue.  Returns false on failure, usually because the
11733     *         looper processing the message queue is exiting.
11734     *
11735     * @see #postDelayed
11736     * @see #removeCallbacks
11737     */
11738    public boolean post(Runnable action) {
11739        final AttachInfo attachInfo = mAttachInfo;
11740        if (attachInfo != null) {
11741            return attachInfo.mHandler.post(action);
11742        }
11743        // Assume that post will succeed later
11744        ViewRootImpl.getRunQueue().post(action);
11745        return true;
11746    }
11747
11748    /**
11749     * <p>Causes the Runnable to be added to the message queue, to be run
11750     * after the specified amount of time elapses.
11751     * The runnable will be run on the user interface thread.</p>
11752     *
11753     * @param action The Runnable that will be executed.
11754     * @param delayMillis The delay (in milliseconds) until the Runnable
11755     *        will be executed.
11756     *
11757     * @return true if the Runnable was successfully placed in to the
11758     *         message queue.  Returns false on failure, usually because the
11759     *         looper processing the message queue is exiting.  Note that a
11760     *         result of true does not mean the Runnable will be processed --
11761     *         if the looper is quit before the delivery time of the message
11762     *         occurs then the message will be dropped.
11763     *
11764     * @see #post
11765     * @see #removeCallbacks
11766     */
11767    public boolean postDelayed(Runnable action, long delayMillis) {
11768        final AttachInfo attachInfo = mAttachInfo;
11769        if (attachInfo != null) {
11770            return attachInfo.mHandler.postDelayed(action, delayMillis);
11771        }
11772        // Assume that post will succeed later
11773        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
11774        return true;
11775    }
11776
11777    /**
11778     * <p>Causes the Runnable to execute on the next animation time step.
11779     * The runnable will be run on the user interface thread.</p>
11780     *
11781     * @param action The Runnable that will be executed.
11782     *
11783     * @see #postOnAnimationDelayed
11784     * @see #removeCallbacks
11785     */
11786    public void postOnAnimation(Runnable action) {
11787        final AttachInfo attachInfo = mAttachInfo;
11788        if (attachInfo != null) {
11789            attachInfo.mViewRootImpl.mChoreographer.postCallback(
11790                    Choreographer.CALLBACK_ANIMATION, action, null);
11791        } else {
11792            // Assume that post will succeed later
11793            ViewRootImpl.getRunQueue().post(action);
11794        }
11795    }
11796
11797    /**
11798     * <p>Causes the Runnable to execute on the next animation time step,
11799     * after the specified amount of time elapses.
11800     * The runnable will be run on the user interface thread.</p>
11801     *
11802     * @param action The Runnable that will be executed.
11803     * @param delayMillis The delay (in milliseconds) until the Runnable
11804     *        will be executed.
11805     *
11806     * @see #postOnAnimation
11807     * @see #removeCallbacks
11808     */
11809    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
11810        final AttachInfo attachInfo = mAttachInfo;
11811        if (attachInfo != null) {
11812            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
11813                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
11814        } else {
11815            // Assume that post will succeed later
11816            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
11817        }
11818    }
11819
11820    /**
11821     * <p>Removes the specified Runnable from the message queue.</p>
11822     *
11823     * @param action The Runnable to remove from the message handling queue
11824     *
11825     * @return true if this view could ask the Handler to remove the Runnable,
11826     *         false otherwise. When the returned value is true, the Runnable
11827     *         may or may not have been actually removed from the message queue
11828     *         (for instance, if the Runnable was not in the queue already.)
11829     *
11830     * @see #post
11831     * @see #postDelayed
11832     * @see #postOnAnimation
11833     * @see #postOnAnimationDelayed
11834     */
11835    public boolean removeCallbacks(Runnable action) {
11836        if (action != null) {
11837            final AttachInfo attachInfo = mAttachInfo;
11838            if (attachInfo != null) {
11839                attachInfo.mHandler.removeCallbacks(action);
11840                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
11841                        Choreographer.CALLBACK_ANIMATION, action, null);
11842            }
11843            // Assume that post will succeed later
11844            ViewRootImpl.getRunQueue().removeCallbacks(action);
11845        }
11846        return true;
11847    }
11848
11849    /**
11850     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
11851     * Use this to invalidate the View from a non-UI thread.</p>
11852     *
11853     * <p>This method can be invoked from outside of the UI thread
11854     * only when this View is attached to a window.</p>
11855     *
11856     * @see #invalidate()
11857     * @see #postInvalidateDelayed(long)
11858     */
11859    public void postInvalidate() {
11860        postInvalidateDelayed(0);
11861    }
11862
11863    /**
11864     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
11865     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
11866     *
11867     * <p>This method can be invoked from outside of the UI thread
11868     * only when this View is attached to a window.</p>
11869     *
11870     * @param left The left coordinate of the rectangle to invalidate.
11871     * @param top The top coordinate of the rectangle to invalidate.
11872     * @param right The right coordinate of the rectangle to invalidate.
11873     * @param bottom The bottom coordinate of the rectangle to invalidate.
11874     *
11875     * @see #invalidate(int, int, int, int)
11876     * @see #invalidate(Rect)
11877     * @see #postInvalidateDelayed(long, int, int, int, int)
11878     */
11879    public void postInvalidate(int left, int top, int right, int bottom) {
11880        postInvalidateDelayed(0, left, top, right, bottom);
11881    }
11882
11883    /**
11884     * <p>Cause an invalidate to happen on a subsequent cycle through the event
11885     * loop. Waits for the specified amount of time.</p>
11886     *
11887     * <p>This method can be invoked from outside of the UI thread
11888     * only when this View is attached to a window.</p>
11889     *
11890     * @param delayMilliseconds the duration in milliseconds to delay the
11891     *         invalidation by
11892     *
11893     * @see #invalidate()
11894     * @see #postInvalidate()
11895     */
11896    public void postInvalidateDelayed(long delayMilliseconds) {
11897        // We try only with the AttachInfo because there's no point in invalidating
11898        // if we are not attached to our window
11899        final AttachInfo attachInfo = mAttachInfo;
11900        if (attachInfo != null) {
11901            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
11902        }
11903    }
11904
11905    /**
11906     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
11907     * through the event loop. Waits for the specified amount of time.</p>
11908     *
11909     * <p>This method can be invoked from outside of the UI thread
11910     * only when this View is attached to a window.</p>
11911     *
11912     * @param delayMilliseconds the duration in milliseconds to delay the
11913     *         invalidation by
11914     * @param left The left coordinate of the rectangle to invalidate.
11915     * @param top The top coordinate of the rectangle to invalidate.
11916     * @param right The right coordinate of the rectangle to invalidate.
11917     * @param bottom The bottom coordinate of the rectangle to invalidate.
11918     *
11919     * @see #invalidate(int, int, int, int)
11920     * @see #invalidate(Rect)
11921     * @see #postInvalidate(int, int, int, int)
11922     */
11923    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
11924            int right, int bottom) {
11925
11926        // We try only with the AttachInfo because there's no point in invalidating
11927        // if we are not attached to our window
11928        final AttachInfo attachInfo = mAttachInfo;
11929        if (attachInfo != null) {
11930            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
11931            info.target = this;
11932            info.left = left;
11933            info.top = top;
11934            info.right = right;
11935            info.bottom = bottom;
11936
11937            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
11938        }
11939    }
11940
11941    /**
11942     * <p>Cause an invalidate to happen on the next animation time step, typically the
11943     * next display frame.</p>
11944     *
11945     * <p>This method can be invoked from outside of the UI thread
11946     * only when this View is attached to a window.</p>
11947     *
11948     * @see #invalidate()
11949     */
11950    public void postInvalidateOnAnimation() {
11951        // We try only with the AttachInfo because there's no point in invalidating
11952        // if we are not attached to our window
11953        final AttachInfo attachInfo = mAttachInfo;
11954        if (attachInfo != null) {
11955            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
11956        }
11957    }
11958
11959    /**
11960     * <p>Cause an invalidate of the specified area to happen on the next animation
11961     * time step, typically the next display frame.</p>
11962     *
11963     * <p>This method can be invoked from outside of the UI thread
11964     * only when this View is attached to a window.</p>
11965     *
11966     * @param left The left coordinate of the rectangle to invalidate.
11967     * @param top The top coordinate of the rectangle to invalidate.
11968     * @param right The right coordinate of the rectangle to invalidate.
11969     * @param bottom The bottom coordinate of the rectangle to invalidate.
11970     *
11971     * @see #invalidate(int, int, int, int)
11972     * @see #invalidate(Rect)
11973     */
11974    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
11975        // We try only with the AttachInfo because there's no point in invalidating
11976        // if we are not attached to our window
11977        final AttachInfo attachInfo = mAttachInfo;
11978        if (attachInfo != null) {
11979            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
11980            info.target = this;
11981            info.left = left;
11982            info.top = top;
11983            info.right = right;
11984            info.bottom = bottom;
11985
11986            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
11987        }
11988    }
11989
11990    /**
11991     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
11992     * This event is sent at most once every
11993     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
11994     */
11995    private void postSendViewScrolledAccessibilityEventCallback() {
11996        if (mSendViewScrolledAccessibilityEvent == null) {
11997            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
11998        }
11999        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
12000            mSendViewScrolledAccessibilityEvent.mIsPending = true;
12001            postDelayed(mSendViewScrolledAccessibilityEvent,
12002                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
12003        }
12004    }
12005
12006    /**
12007     * Called by a parent to request that a child update its values for mScrollX
12008     * and mScrollY if necessary. This will typically be done if the child is
12009     * animating a scroll using a {@link android.widget.Scroller Scroller}
12010     * object.
12011     */
12012    public void computeScroll() {
12013    }
12014
12015    /**
12016     * <p>Indicate whether the horizontal edges are faded when the view is
12017     * scrolled horizontally.</p>
12018     *
12019     * @return true if the horizontal edges should are faded on scroll, false
12020     *         otherwise
12021     *
12022     * @see #setHorizontalFadingEdgeEnabled(boolean)
12023     *
12024     * @attr ref android.R.styleable#View_requiresFadingEdge
12025     */
12026    public boolean isHorizontalFadingEdgeEnabled() {
12027        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
12028    }
12029
12030    /**
12031     * <p>Define whether the horizontal edges should be faded when this view
12032     * is scrolled horizontally.</p>
12033     *
12034     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
12035     *                                    be faded when the view is scrolled
12036     *                                    horizontally
12037     *
12038     * @see #isHorizontalFadingEdgeEnabled()
12039     *
12040     * @attr ref android.R.styleable#View_requiresFadingEdge
12041     */
12042    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
12043        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
12044            if (horizontalFadingEdgeEnabled) {
12045                initScrollCache();
12046            }
12047
12048            mViewFlags ^= FADING_EDGE_HORIZONTAL;
12049        }
12050    }
12051
12052    /**
12053     * <p>Indicate whether the vertical edges are faded when the view is
12054     * scrolled horizontally.</p>
12055     *
12056     * @return true if the vertical edges should are faded on scroll, false
12057     *         otherwise
12058     *
12059     * @see #setVerticalFadingEdgeEnabled(boolean)
12060     *
12061     * @attr ref android.R.styleable#View_requiresFadingEdge
12062     */
12063    public boolean isVerticalFadingEdgeEnabled() {
12064        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
12065    }
12066
12067    /**
12068     * <p>Define whether the vertical edges should be faded when this view
12069     * is scrolled vertically.</p>
12070     *
12071     * @param verticalFadingEdgeEnabled true if the vertical edges should
12072     *                                  be faded when the view is scrolled
12073     *                                  vertically
12074     *
12075     * @see #isVerticalFadingEdgeEnabled()
12076     *
12077     * @attr ref android.R.styleable#View_requiresFadingEdge
12078     */
12079    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
12080        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
12081            if (verticalFadingEdgeEnabled) {
12082                initScrollCache();
12083            }
12084
12085            mViewFlags ^= FADING_EDGE_VERTICAL;
12086        }
12087    }
12088
12089    /**
12090     * Returns the strength, or intensity, of the top faded edge. The strength is
12091     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12092     * returns 0.0 or 1.0 but no value in between.
12093     *
12094     * Subclasses should override this method to provide a smoother fade transition
12095     * when scrolling occurs.
12096     *
12097     * @return the intensity of the top fade as a float between 0.0f and 1.0f
12098     */
12099    protected float getTopFadingEdgeStrength() {
12100        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
12101    }
12102
12103    /**
12104     * Returns the strength, or intensity, of the bottom faded edge. The strength is
12105     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12106     * returns 0.0 or 1.0 but no value in between.
12107     *
12108     * Subclasses should override this method to provide a smoother fade transition
12109     * when scrolling occurs.
12110     *
12111     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
12112     */
12113    protected float getBottomFadingEdgeStrength() {
12114        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
12115                computeVerticalScrollRange() ? 1.0f : 0.0f;
12116    }
12117
12118    /**
12119     * Returns the strength, or intensity, of the left faded edge. The strength is
12120     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12121     * returns 0.0 or 1.0 but no value in between.
12122     *
12123     * Subclasses should override this method to provide a smoother fade transition
12124     * when scrolling occurs.
12125     *
12126     * @return the intensity of the left fade as a float between 0.0f and 1.0f
12127     */
12128    protected float getLeftFadingEdgeStrength() {
12129        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
12130    }
12131
12132    /**
12133     * Returns the strength, or intensity, of the right faded edge. The strength is
12134     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12135     * returns 0.0 or 1.0 but no value in between.
12136     *
12137     * Subclasses should override this method to provide a smoother fade transition
12138     * when scrolling occurs.
12139     *
12140     * @return the intensity of the right fade as a float between 0.0f and 1.0f
12141     */
12142    protected float getRightFadingEdgeStrength() {
12143        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
12144                computeHorizontalScrollRange() ? 1.0f : 0.0f;
12145    }
12146
12147    /**
12148     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
12149     * scrollbar is not drawn by default.</p>
12150     *
12151     * @return true if the horizontal scrollbar should be painted, false
12152     *         otherwise
12153     *
12154     * @see #setHorizontalScrollBarEnabled(boolean)
12155     */
12156    public boolean isHorizontalScrollBarEnabled() {
12157        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
12158    }
12159
12160    /**
12161     * <p>Define whether the horizontal scrollbar should be drawn or not. The
12162     * scrollbar is not drawn by default.</p>
12163     *
12164     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
12165     *                                   be painted
12166     *
12167     * @see #isHorizontalScrollBarEnabled()
12168     */
12169    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
12170        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
12171            mViewFlags ^= SCROLLBARS_HORIZONTAL;
12172            computeOpaqueFlags();
12173            resolvePadding();
12174        }
12175    }
12176
12177    /**
12178     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
12179     * scrollbar is not drawn by default.</p>
12180     *
12181     * @return true if the vertical scrollbar should be painted, false
12182     *         otherwise
12183     *
12184     * @see #setVerticalScrollBarEnabled(boolean)
12185     */
12186    public boolean isVerticalScrollBarEnabled() {
12187        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
12188    }
12189
12190    /**
12191     * <p>Define whether the vertical scrollbar should be drawn or not. The
12192     * scrollbar is not drawn by default.</p>
12193     *
12194     * @param verticalScrollBarEnabled true if the vertical scrollbar should
12195     *                                 be painted
12196     *
12197     * @see #isVerticalScrollBarEnabled()
12198     */
12199    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
12200        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
12201            mViewFlags ^= SCROLLBARS_VERTICAL;
12202            computeOpaqueFlags();
12203            resolvePadding();
12204        }
12205    }
12206
12207    /**
12208     * @hide
12209     */
12210    protected void recomputePadding() {
12211        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
12212    }
12213
12214    /**
12215     * Define whether scrollbars will fade when the view is not scrolling.
12216     *
12217     * @param fadeScrollbars wheter to enable fading
12218     *
12219     * @attr ref android.R.styleable#View_fadeScrollbars
12220     */
12221    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
12222        initScrollCache();
12223        final ScrollabilityCache scrollabilityCache = mScrollCache;
12224        scrollabilityCache.fadeScrollBars = fadeScrollbars;
12225        if (fadeScrollbars) {
12226            scrollabilityCache.state = ScrollabilityCache.OFF;
12227        } else {
12228            scrollabilityCache.state = ScrollabilityCache.ON;
12229        }
12230    }
12231
12232    /**
12233     *
12234     * Returns true if scrollbars will fade when this view is not scrolling
12235     *
12236     * @return true if scrollbar fading is enabled
12237     *
12238     * @attr ref android.R.styleable#View_fadeScrollbars
12239     */
12240    public boolean isScrollbarFadingEnabled() {
12241        return mScrollCache != null && mScrollCache.fadeScrollBars;
12242    }
12243
12244    /**
12245     *
12246     * Returns the delay before scrollbars fade.
12247     *
12248     * @return the delay before scrollbars fade
12249     *
12250     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
12251     */
12252    public int getScrollBarDefaultDelayBeforeFade() {
12253        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
12254                mScrollCache.scrollBarDefaultDelayBeforeFade;
12255    }
12256
12257    /**
12258     * Define the delay before scrollbars fade.
12259     *
12260     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
12261     *
12262     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
12263     */
12264    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
12265        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
12266    }
12267
12268    /**
12269     *
12270     * Returns the scrollbar fade duration.
12271     *
12272     * @return the scrollbar fade duration
12273     *
12274     * @attr ref android.R.styleable#View_scrollbarFadeDuration
12275     */
12276    public int getScrollBarFadeDuration() {
12277        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
12278                mScrollCache.scrollBarFadeDuration;
12279    }
12280
12281    /**
12282     * Define the scrollbar fade duration.
12283     *
12284     * @param scrollBarFadeDuration - the scrollbar fade duration
12285     *
12286     * @attr ref android.R.styleable#View_scrollbarFadeDuration
12287     */
12288    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
12289        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
12290    }
12291
12292    /**
12293     *
12294     * Returns the scrollbar size.
12295     *
12296     * @return the scrollbar size
12297     *
12298     * @attr ref android.R.styleable#View_scrollbarSize
12299     */
12300    public int getScrollBarSize() {
12301        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
12302                mScrollCache.scrollBarSize;
12303    }
12304
12305    /**
12306     * Define the scrollbar size.
12307     *
12308     * @param scrollBarSize - the scrollbar size
12309     *
12310     * @attr ref android.R.styleable#View_scrollbarSize
12311     */
12312    public void setScrollBarSize(int scrollBarSize) {
12313        getScrollCache().scrollBarSize = scrollBarSize;
12314    }
12315
12316    /**
12317     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
12318     * inset. When inset, they add to the padding of the view. And the scrollbars
12319     * can be drawn inside the padding area or on the edge of the view. For example,
12320     * if a view has a background drawable and you want to draw the scrollbars
12321     * inside the padding specified by the drawable, you can use
12322     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
12323     * appear at the edge of the view, ignoring the padding, then you can use
12324     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
12325     * @param style the style of the scrollbars. Should be one of
12326     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
12327     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
12328     * @see #SCROLLBARS_INSIDE_OVERLAY
12329     * @see #SCROLLBARS_INSIDE_INSET
12330     * @see #SCROLLBARS_OUTSIDE_OVERLAY
12331     * @see #SCROLLBARS_OUTSIDE_INSET
12332     *
12333     * @attr ref android.R.styleable#View_scrollbarStyle
12334     */
12335    public void setScrollBarStyle(@ScrollBarStyle int style) {
12336        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
12337            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
12338            computeOpaqueFlags();
12339            resolvePadding();
12340        }
12341    }
12342
12343    /**
12344     * <p>Returns the current scrollbar style.</p>
12345     * @return the current scrollbar style
12346     * @see #SCROLLBARS_INSIDE_OVERLAY
12347     * @see #SCROLLBARS_INSIDE_INSET
12348     * @see #SCROLLBARS_OUTSIDE_OVERLAY
12349     * @see #SCROLLBARS_OUTSIDE_INSET
12350     *
12351     * @attr ref android.R.styleable#View_scrollbarStyle
12352     */
12353    @ViewDebug.ExportedProperty(mapping = {
12354            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
12355            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
12356            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
12357            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
12358    })
12359    @ScrollBarStyle
12360    public int getScrollBarStyle() {
12361        return mViewFlags & SCROLLBARS_STYLE_MASK;
12362    }
12363
12364    /**
12365     * <p>Compute the horizontal range that the horizontal scrollbar
12366     * represents.</p>
12367     *
12368     * <p>The range is expressed in arbitrary units that must be the same as the
12369     * units used by {@link #computeHorizontalScrollExtent()} and
12370     * {@link #computeHorizontalScrollOffset()}.</p>
12371     *
12372     * <p>The default range is the drawing width of this view.</p>
12373     *
12374     * @return the total horizontal range represented by the horizontal
12375     *         scrollbar
12376     *
12377     * @see #computeHorizontalScrollExtent()
12378     * @see #computeHorizontalScrollOffset()
12379     * @see android.widget.ScrollBarDrawable
12380     */
12381    protected int computeHorizontalScrollRange() {
12382        return getWidth();
12383    }
12384
12385    /**
12386     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
12387     * within the horizontal range. This value is used to compute the position
12388     * of the thumb within the scrollbar's track.</p>
12389     *
12390     * <p>The range is expressed in arbitrary units that must be the same as the
12391     * units used by {@link #computeHorizontalScrollRange()} and
12392     * {@link #computeHorizontalScrollExtent()}.</p>
12393     *
12394     * <p>The default offset is the scroll offset of this view.</p>
12395     *
12396     * @return the horizontal offset of the scrollbar's thumb
12397     *
12398     * @see #computeHorizontalScrollRange()
12399     * @see #computeHorizontalScrollExtent()
12400     * @see android.widget.ScrollBarDrawable
12401     */
12402    protected int computeHorizontalScrollOffset() {
12403        return mScrollX;
12404    }
12405
12406    /**
12407     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
12408     * within the horizontal range. This value is used to compute the length
12409     * of the thumb within the scrollbar's track.</p>
12410     *
12411     * <p>The range is expressed in arbitrary units that must be the same as the
12412     * units used by {@link #computeHorizontalScrollRange()} and
12413     * {@link #computeHorizontalScrollOffset()}.</p>
12414     *
12415     * <p>The default extent is the drawing width of this view.</p>
12416     *
12417     * @return the horizontal extent of the scrollbar's thumb
12418     *
12419     * @see #computeHorizontalScrollRange()
12420     * @see #computeHorizontalScrollOffset()
12421     * @see android.widget.ScrollBarDrawable
12422     */
12423    protected int computeHorizontalScrollExtent() {
12424        return getWidth();
12425    }
12426
12427    /**
12428     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
12429     *
12430     * <p>The range is expressed in arbitrary units that must be the same as the
12431     * units used by {@link #computeVerticalScrollExtent()} and
12432     * {@link #computeVerticalScrollOffset()}.</p>
12433     *
12434     * @return the total vertical range represented by the vertical scrollbar
12435     *
12436     * <p>The default range is the drawing height of this view.</p>
12437     *
12438     * @see #computeVerticalScrollExtent()
12439     * @see #computeVerticalScrollOffset()
12440     * @see android.widget.ScrollBarDrawable
12441     */
12442    protected int computeVerticalScrollRange() {
12443        return getHeight();
12444    }
12445
12446    /**
12447     * <p>Compute the vertical offset of the vertical scrollbar's thumb
12448     * within the horizontal range. This value is used to compute the position
12449     * of the thumb within the scrollbar's track.</p>
12450     *
12451     * <p>The range is expressed in arbitrary units that must be the same as the
12452     * units used by {@link #computeVerticalScrollRange()} and
12453     * {@link #computeVerticalScrollExtent()}.</p>
12454     *
12455     * <p>The default offset is the scroll offset of this view.</p>
12456     *
12457     * @return the vertical offset of the scrollbar's thumb
12458     *
12459     * @see #computeVerticalScrollRange()
12460     * @see #computeVerticalScrollExtent()
12461     * @see android.widget.ScrollBarDrawable
12462     */
12463    protected int computeVerticalScrollOffset() {
12464        return mScrollY;
12465    }
12466
12467    /**
12468     * <p>Compute the vertical extent of the vertical scrollbar's thumb
12469     * within the vertical range. This value is used to compute the length
12470     * of the thumb within the scrollbar's track.</p>
12471     *
12472     * <p>The range is expressed in arbitrary units that must be the same as the
12473     * units used by {@link #computeVerticalScrollRange()} and
12474     * {@link #computeVerticalScrollOffset()}.</p>
12475     *
12476     * <p>The default extent is the drawing height of this view.</p>
12477     *
12478     * @return the vertical extent of the scrollbar's thumb
12479     *
12480     * @see #computeVerticalScrollRange()
12481     * @see #computeVerticalScrollOffset()
12482     * @see android.widget.ScrollBarDrawable
12483     */
12484    protected int computeVerticalScrollExtent() {
12485        return getHeight();
12486    }
12487
12488    /**
12489     * Check if this view can be scrolled horizontally in a certain direction.
12490     *
12491     * @param direction Negative to check scrolling left, positive to check scrolling right.
12492     * @return true if this view can be scrolled in the specified direction, false otherwise.
12493     */
12494    public boolean canScrollHorizontally(int direction) {
12495        final int offset = computeHorizontalScrollOffset();
12496        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
12497        if (range == 0) return false;
12498        if (direction < 0) {
12499            return offset > 0;
12500        } else {
12501            return offset < range - 1;
12502        }
12503    }
12504
12505    /**
12506     * Check if this view can be scrolled vertically in a certain direction.
12507     *
12508     * @param direction Negative to check scrolling up, positive to check scrolling down.
12509     * @return true if this view can be scrolled in the specified direction, false otherwise.
12510     */
12511    public boolean canScrollVertically(int direction) {
12512        final int offset = computeVerticalScrollOffset();
12513        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
12514        if (range == 0) return false;
12515        if (direction < 0) {
12516            return offset > 0;
12517        } else {
12518            return offset < range - 1;
12519        }
12520    }
12521
12522    /**
12523     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
12524     * scrollbars are painted only if they have been awakened first.</p>
12525     *
12526     * @param canvas the canvas on which to draw the scrollbars
12527     *
12528     * @see #awakenScrollBars(int)
12529     */
12530    protected final void onDrawScrollBars(Canvas canvas) {
12531        // scrollbars are drawn only when the animation is running
12532        final ScrollabilityCache cache = mScrollCache;
12533        if (cache != null) {
12534
12535            int state = cache.state;
12536
12537            if (state == ScrollabilityCache.OFF) {
12538                return;
12539            }
12540
12541            boolean invalidate = false;
12542
12543            if (state == ScrollabilityCache.FADING) {
12544                // We're fading -- get our fade interpolation
12545                if (cache.interpolatorValues == null) {
12546                    cache.interpolatorValues = new float[1];
12547                }
12548
12549                float[] values = cache.interpolatorValues;
12550
12551                // Stops the animation if we're done
12552                if (cache.scrollBarInterpolator.timeToValues(values) ==
12553                        Interpolator.Result.FREEZE_END) {
12554                    cache.state = ScrollabilityCache.OFF;
12555                } else {
12556                    cache.scrollBar.setAlpha(Math.round(values[0]));
12557                }
12558
12559                // This will make the scroll bars inval themselves after
12560                // drawing. We only want this when we're fading so that
12561                // we prevent excessive redraws
12562                invalidate = true;
12563            } else {
12564                // We're just on -- but we may have been fading before so
12565                // reset alpha
12566                cache.scrollBar.setAlpha(255);
12567            }
12568
12569
12570            final int viewFlags = mViewFlags;
12571
12572            final boolean drawHorizontalScrollBar =
12573                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
12574            final boolean drawVerticalScrollBar =
12575                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
12576                && !isVerticalScrollBarHidden();
12577
12578            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
12579                final int width = mRight - mLeft;
12580                final int height = mBottom - mTop;
12581
12582                final ScrollBarDrawable scrollBar = cache.scrollBar;
12583
12584                final int scrollX = mScrollX;
12585                final int scrollY = mScrollY;
12586                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
12587
12588                int left;
12589                int top;
12590                int right;
12591                int bottom;
12592
12593                if (drawHorizontalScrollBar) {
12594                    int size = scrollBar.getSize(false);
12595                    if (size <= 0) {
12596                        size = cache.scrollBarSize;
12597                    }
12598
12599                    scrollBar.setParameters(computeHorizontalScrollRange(),
12600                                            computeHorizontalScrollOffset(),
12601                                            computeHorizontalScrollExtent(), false);
12602                    final int verticalScrollBarGap = drawVerticalScrollBar ?
12603                            getVerticalScrollbarWidth() : 0;
12604                    top = scrollY + height - size - (mUserPaddingBottom & inside);
12605                    left = scrollX + (mPaddingLeft & inside);
12606                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
12607                    bottom = top + size;
12608                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
12609                    if (invalidate) {
12610                        invalidate(left, top, right, bottom);
12611                    }
12612                }
12613
12614                if (drawVerticalScrollBar) {
12615                    int size = scrollBar.getSize(true);
12616                    if (size <= 0) {
12617                        size = cache.scrollBarSize;
12618                    }
12619
12620                    scrollBar.setParameters(computeVerticalScrollRange(),
12621                                            computeVerticalScrollOffset(),
12622                                            computeVerticalScrollExtent(), true);
12623                    int verticalScrollbarPosition = mVerticalScrollbarPosition;
12624                    if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
12625                        verticalScrollbarPosition = isLayoutRtl() ?
12626                                SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
12627                    }
12628                    switch (verticalScrollbarPosition) {
12629                        default:
12630                        case SCROLLBAR_POSITION_RIGHT:
12631                            left = scrollX + width - size - (mUserPaddingRight & inside);
12632                            break;
12633                        case SCROLLBAR_POSITION_LEFT:
12634                            left = scrollX + (mUserPaddingLeft & inside);
12635                            break;
12636                    }
12637                    top = scrollY + (mPaddingTop & inside);
12638                    right = left + size;
12639                    bottom = scrollY + height - (mUserPaddingBottom & inside);
12640                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
12641                    if (invalidate) {
12642                        invalidate(left, top, right, bottom);
12643                    }
12644                }
12645            }
12646        }
12647    }
12648
12649    /**
12650     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
12651     * FastScroller is visible.
12652     * @return whether to temporarily hide the vertical scrollbar
12653     * @hide
12654     */
12655    protected boolean isVerticalScrollBarHidden() {
12656        return false;
12657    }
12658
12659    /**
12660     * <p>Draw the horizontal scrollbar if
12661     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
12662     *
12663     * @param canvas the canvas on which to draw the scrollbar
12664     * @param scrollBar the scrollbar's drawable
12665     *
12666     * @see #isHorizontalScrollBarEnabled()
12667     * @see #computeHorizontalScrollRange()
12668     * @see #computeHorizontalScrollExtent()
12669     * @see #computeHorizontalScrollOffset()
12670     * @see android.widget.ScrollBarDrawable
12671     * @hide
12672     */
12673    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
12674            int l, int t, int r, int b) {
12675        scrollBar.setBounds(l, t, r, b);
12676        scrollBar.draw(canvas);
12677    }
12678
12679    /**
12680     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
12681     * returns true.</p>
12682     *
12683     * @param canvas the canvas on which to draw the scrollbar
12684     * @param scrollBar the scrollbar's drawable
12685     *
12686     * @see #isVerticalScrollBarEnabled()
12687     * @see #computeVerticalScrollRange()
12688     * @see #computeVerticalScrollExtent()
12689     * @see #computeVerticalScrollOffset()
12690     * @see android.widget.ScrollBarDrawable
12691     * @hide
12692     */
12693    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
12694            int l, int t, int r, int b) {
12695        scrollBar.setBounds(l, t, r, b);
12696        scrollBar.draw(canvas);
12697    }
12698
12699    /**
12700     * Implement this to do your drawing.
12701     *
12702     * @param canvas the canvas on which the background will be drawn
12703     */
12704    protected void onDraw(Canvas canvas) {
12705    }
12706
12707    /*
12708     * Caller is responsible for calling requestLayout if necessary.
12709     * (This allows addViewInLayout to not request a new layout.)
12710     */
12711    void assignParent(ViewParent parent) {
12712        if (mParent == null) {
12713            mParent = parent;
12714        } else if (parent == null) {
12715            mParent = null;
12716        } else {
12717            throw new RuntimeException("view " + this + " being added, but"
12718                    + " it already has a parent");
12719        }
12720    }
12721
12722    /**
12723     * This is called when the view is attached to a window.  At this point it
12724     * has a Surface and will start drawing.  Note that this function is
12725     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
12726     * however it may be called any time before the first onDraw -- including
12727     * before or after {@link #onMeasure(int, int)}.
12728     *
12729     * @see #onDetachedFromWindow()
12730     */
12731    protected void onAttachedToWindow() {
12732        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
12733            mParent.requestTransparentRegion(this);
12734        }
12735
12736        if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
12737            initialAwakenScrollBars();
12738            mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
12739        }
12740
12741        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
12742
12743        jumpDrawablesToCurrentState();
12744
12745        resetSubtreeAccessibilityStateChanged();
12746
12747        invalidateOutline();
12748
12749        if (isFocused()) {
12750            InputMethodManager imm = InputMethodManager.peekInstance();
12751            imm.focusIn(this);
12752        }
12753    }
12754
12755    /**
12756     * Resolve all RTL related properties.
12757     *
12758     * @return true if resolution of RTL properties has been done
12759     *
12760     * @hide
12761     */
12762    public boolean resolveRtlPropertiesIfNeeded() {
12763        if (!needRtlPropertiesResolution()) return false;
12764
12765        // Order is important here: LayoutDirection MUST be resolved first
12766        if (!isLayoutDirectionResolved()) {
12767            resolveLayoutDirection();
12768            resolveLayoutParams();
12769        }
12770        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
12771        if (!isTextDirectionResolved()) {
12772            resolveTextDirection();
12773        }
12774        if (!isTextAlignmentResolved()) {
12775            resolveTextAlignment();
12776        }
12777        // Should resolve Drawables before Padding because we need the layout direction of the
12778        // Drawable to correctly resolve Padding.
12779        if (!isDrawablesResolved()) {
12780            resolveDrawables();
12781        }
12782        if (!isPaddingResolved()) {
12783            resolvePadding();
12784        }
12785        onRtlPropertiesChanged(getLayoutDirection());
12786        return true;
12787    }
12788
12789    /**
12790     * Reset resolution of all RTL related properties.
12791     *
12792     * @hide
12793     */
12794    public void resetRtlProperties() {
12795        resetResolvedLayoutDirection();
12796        resetResolvedTextDirection();
12797        resetResolvedTextAlignment();
12798        resetResolvedPadding();
12799        resetResolvedDrawables();
12800    }
12801
12802    /**
12803     * @see #onScreenStateChanged(int)
12804     */
12805    void dispatchScreenStateChanged(int screenState) {
12806        onScreenStateChanged(screenState);
12807    }
12808
12809    /**
12810     * This method is called whenever the state of the screen this view is
12811     * attached to changes. A state change will usually occurs when the screen
12812     * turns on or off (whether it happens automatically or the user does it
12813     * manually.)
12814     *
12815     * @param screenState The new state of the screen. Can be either
12816     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
12817     */
12818    public void onScreenStateChanged(int screenState) {
12819    }
12820
12821    /**
12822     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
12823     */
12824    private boolean hasRtlSupport() {
12825        return mContext.getApplicationInfo().hasRtlSupport();
12826    }
12827
12828    /**
12829     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
12830     * RTL not supported)
12831     */
12832    private boolean isRtlCompatibilityMode() {
12833        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
12834        return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport();
12835    }
12836
12837    /**
12838     * @return true if RTL properties need resolution.
12839     *
12840     */
12841    private boolean needRtlPropertiesResolution() {
12842        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
12843    }
12844
12845    /**
12846     * Called when any RTL property (layout direction or text direction or text alignment) has
12847     * been changed.
12848     *
12849     * Subclasses need to override this method to take care of cached information that depends on the
12850     * resolved layout direction, or to inform child views that inherit their layout direction.
12851     *
12852     * The default implementation does nothing.
12853     *
12854     * @param layoutDirection the direction of the layout
12855     *
12856     * @see #LAYOUT_DIRECTION_LTR
12857     * @see #LAYOUT_DIRECTION_RTL
12858     */
12859    public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) {
12860    }
12861
12862    /**
12863     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
12864     * that the parent directionality can and will be resolved before its children.
12865     *
12866     * @return true if resolution has been done, false otherwise.
12867     *
12868     * @hide
12869     */
12870    public boolean resolveLayoutDirection() {
12871        // Clear any previous layout direction resolution
12872        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
12873
12874        if (hasRtlSupport()) {
12875            // Set resolved depending on layout direction
12876            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
12877                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
12878                case LAYOUT_DIRECTION_INHERIT:
12879                    // We cannot resolve yet. LTR is by default and let the resolution happen again
12880                    // later to get the correct resolved value
12881                    if (!canResolveLayoutDirection()) return false;
12882
12883                    // Parent has not yet resolved, LTR is still the default
12884                    try {
12885                        if (!mParent.isLayoutDirectionResolved()) return false;
12886
12887                        if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
12888                            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12889                        }
12890                    } catch (AbstractMethodError e) {
12891                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
12892                                " does not fully implement ViewParent", e);
12893                    }
12894                    break;
12895                case LAYOUT_DIRECTION_RTL:
12896                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12897                    break;
12898                case LAYOUT_DIRECTION_LOCALE:
12899                    if((LAYOUT_DIRECTION_RTL ==
12900                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
12901                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12902                    }
12903                    break;
12904                default:
12905                    // Nothing to do, LTR by default
12906            }
12907        }
12908
12909        // Set to resolved
12910        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
12911        return true;
12912    }
12913
12914    /**
12915     * Check if layout direction resolution can be done.
12916     *
12917     * @return true if layout direction resolution can be done otherwise return false.
12918     */
12919    public boolean canResolveLayoutDirection() {
12920        switch (getRawLayoutDirection()) {
12921            case LAYOUT_DIRECTION_INHERIT:
12922                if (mParent != null) {
12923                    try {
12924                        return mParent.canResolveLayoutDirection();
12925                    } catch (AbstractMethodError e) {
12926                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
12927                                " does not fully implement ViewParent", e);
12928                    }
12929                }
12930                return false;
12931
12932            default:
12933                return true;
12934        }
12935    }
12936
12937    /**
12938     * Reset the resolved layout direction. Layout direction will be resolved during a call to
12939     * {@link #onMeasure(int, int)}.
12940     *
12941     * @hide
12942     */
12943    public void resetResolvedLayoutDirection() {
12944        // Reset the current resolved bits
12945        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
12946    }
12947
12948    /**
12949     * @return true if the layout direction is inherited.
12950     *
12951     * @hide
12952     */
12953    public boolean isLayoutDirectionInherited() {
12954        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
12955    }
12956
12957    /**
12958     * @return true if layout direction has been resolved.
12959     */
12960    public boolean isLayoutDirectionResolved() {
12961        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
12962    }
12963
12964    /**
12965     * Return if padding has been resolved
12966     *
12967     * @hide
12968     */
12969    boolean isPaddingResolved() {
12970        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
12971    }
12972
12973    /**
12974     * Resolves padding depending on layout direction, if applicable, and
12975     * recomputes internal padding values to adjust for scroll bars.
12976     *
12977     * @hide
12978     */
12979    public void resolvePadding() {
12980        final int resolvedLayoutDirection = getLayoutDirection();
12981
12982        if (!isRtlCompatibilityMode()) {
12983            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
12984            // If start / end padding are defined, they will be resolved (hence overriding) to
12985            // left / right or right / left depending on the resolved layout direction.
12986            // If start / end padding are not defined, use the left / right ones.
12987            if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) {
12988                Rect padding = sThreadLocal.get();
12989                if (padding == null) {
12990                    padding = new Rect();
12991                    sThreadLocal.set(padding);
12992                }
12993                mBackground.getPadding(padding);
12994                if (!mLeftPaddingDefined) {
12995                    mUserPaddingLeftInitial = padding.left;
12996                }
12997                if (!mRightPaddingDefined) {
12998                    mUserPaddingRightInitial = padding.right;
12999                }
13000            }
13001            switch (resolvedLayoutDirection) {
13002                case LAYOUT_DIRECTION_RTL:
13003                    if (mUserPaddingStart != UNDEFINED_PADDING) {
13004                        mUserPaddingRight = mUserPaddingStart;
13005                    } else {
13006                        mUserPaddingRight = mUserPaddingRightInitial;
13007                    }
13008                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
13009                        mUserPaddingLeft = mUserPaddingEnd;
13010                    } else {
13011                        mUserPaddingLeft = mUserPaddingLeftInitial;
13012                    }
13013                    break;
13014                case LAYOUT_DIRECTION_LTR:
13015                default:
13016                    if (mUserPaddingStart != UNDEFINED_PADDING) {
13017                        mUserPaddingLeft = mUserPaddingStart;
13018                    } else {
13019                        mUserPaddingLeft = mUserPaddingLeftInitial;
13020                    }
13021                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
13022                        mUserPaddingRight = mUserPaddingEnd;
13023                    } else {
13024                        mUserPaddingRight = mUserPaddingRightInitial;
13025                    }
13026            }
13027
13028            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
13029        }
13030
13031        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
13032        onRtlPropertiesChanged(resolvedLayoutDirection);
13033
13034        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
13035    }
13036
13037    /**
13038     * Reset the resolved layout direction.
13039     *
13040     * @hide
13041     */
13042    public void resetResolvedPadding() {
13043        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
13044    }
13045
13046    /**
13047     * This is called when the view is detached from a window.  At this point it
13048     * no longer has a surface for drawing.
13049     *
13050     * @see #onAttachedToWindow()
13051     */
13052    protected void onDetachedFromWindow() {
13053    }
13054
13055    /**
13056     * This is a framework-internal mirror of onDetachedFromWindow() that's called
13057     * after onDetachedFromWindow().
13058     *
13059     * If you override this you *MUST* call super.onDetachedFromWindowInternal()!
13060     * The super method should be called at the end of the overriden method to ensure
13061     * subclasses are destroyed first
13062     *
13063     * @hide
13064     */
13065    protected void onDetachedFromWindowInternal() {
13066        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
13067        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
13068
13069        removeUnsetPressCallback();
13070        removeLongPressCallback();
13071        removePerformClickCallback();
13072        removeSendViewScrolledAccessibilityEventCallback();
13073        stopNestedScroll();
13074
13075        // Anything that started animating right before detach should already
13076        // be in its final state when re-attached.
13077        jumpDrawablesToCurrentState();
13078
13079        destroyDrawingCache();
13080
13081        cleanupDraw();
13082        mCurrentAnimation = null;
13083    }
13084
13085    private void cleanupDraw() {
13086        resetDisplayList();
13087        if (mAttachInfo != null) {
13088            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
13089        }
13090    }
13091
13092    void invalidateInheritedLayoutMode(int layoutModeOfRoot) {
13093    }
13094
13095    /**
13096     * @return The number of times this view has been attached to a window
13097     */
13098    protected int getWindowAttachCount() {
13099        return mWindowAttachCount;
13100    }
13101
13102    /**
13103     * Retrieve a unique token identifying the window this view is attached to.
13104     * @return Return the window's token for use in
13105     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
13106     */
13107    public IBinder getWindowToken() {
13108        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
13109    }
13110
13111    /**
13112     * Retrieve the {@link WindowId} for the window this view is
13113     * currently attached to.
13114     */
13115    public WindowId getWindowId() {
13116        if (mAttachInfo == null) {
13117            return null;
13118        }
13119        if (mAttachInfo.mWindowId == null) {
13120            try {
13121                mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId(
13122                        mAttachInfo.mWindowToken);
13123                mAttachInfo.mWindowId = new WindowId(
13124                        mAttachInfo.mIWindowId);
13125            } catch (RemoteException e) {
13126            }
13127        }
13128        return mAttachInfo.mWindowId;
13129    }
13130
13131    /**
13132     * Retrieve a unique token identifying the top-level "real" window of
13133     * the window that this view is attached to.  That is, this is like
13134     * {@link #getWindowToken}, except if the window this view in is a panel
13135     * window (attached to another containing window), then the token of
13136     * the containing window is returned instead.
13137     *
13138     * @return Returns the associated window token, either
13139     * {@link #getWindowToken()} or the containing window's token.
13140     */
13141    public IBinder getApplicationWindowToken() {
13142        AttachInfo ai = mAttachInfo;
13143        if (ai != null) {
13144            IBinder appWindowToken = ai.mPanelParentWindowToken;
13145            if (appWindowToken == null) {
13146                appWindowToken = ai.mWindowToken;
13147            }
13148            return appWindowToken;
13149        }
13150        return null;
13151    }
13152
13153    /**
13154     * Gets the logical display to which the view's window has been attached.
13155     *
13156     * @return The logical display, or null if the view is not currently attached to a window.
13157     */
13158    public Display getDisplay() {
13159        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
13160    }
13161
13162    /**
13163     * Retrieve private session object this view hierarchy is using to
13164     * communicate with the window manager.
13165     * @return the session object to communicate with the window manager
13166     */
13167    /*package*/ IWindowSession getWindowSession() {
13168        return mAttachInfo != null ? mAttachInfo.mSession : null;
13169    }
13170
13171    /**
13172     * @param info the {@link android.view.View.AttachInfo} to associated with
13173     *        this view
13174     */
13175    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
13176        //System.out.println("Attached! " + this);
13177        mAttachInfo = info;
13178        if (mOverlay != null) {
13179            mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
13180        }
13181        mWindowAttachCount++;
13182        // We will need to evaluate the drawable state at least once.
13183        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
13184        if (mFloatingTreeObserver != null) {
13185            info.mTreeObserver.merge(mFloatingTreeObserver);
13186            mFloatingTreeObserver = null;
13187        }
13188        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
13189            mAttachInfo.mScrollContainers.add(this);
13190            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
13191        }
13192        performCollectViewAttributes(mAttachInfo, visibility);
13193        onAttachedToWindow();
13194
13195        ListenerInfo li = mListenerInfo;
13196        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
13197                li != null ? li.mOnAttachStateChangeListeners : null;
13198        if (listeners != null && listeners.size() > 0) {
13199            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
13200            // perform the dispatching. The iterator is a safe guard against listeners that
13201            // could mutate the list by calling the various add/remove methods. This prevents
13202            // the array from being modified while we iterate it.
13203            for (OnAttachStateChangeListener listener : listeners) {
13204                listener.onViewAttachedToWindow(this);
13205            }
13206        }
13207
13208        int vis = info.mWindowVisibility;
13209        if (vis != GONE) {
13210            onWindowVisibilityChanged(vis);
13211        }
13212        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
13213            // If nobody has evaluated the drawable state yet, then do it now.
13214            refreshDrawableState();
13215        }
13216        needGlobalAttributesUpdate(false);
13217    }
13218
13219    void dispatchDetachedFromWindow() {
13220        AttachInfo info = mAttachInfo;
13221        if (info != null) {
13222            int vis = info.mWindowVisibility;
13223            if (vis != GONE) {
13224                onWindowVisibilityChanged(GONE);
13225            }
13226        }
13227
13228        onDetachedFromWindow();
13229        onDetachedFromWindowInternal();
13230
13231        ListenerInfo li = mListenerInfo;
13232        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
13233                li != null ? li.mOnAttachStateChangeListeners : null;
13234        if (listeners != null && listeners.size() > 0) {
13235            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
13236            // perform the dispatching. The iterator is a safe guard against listeners that
13237            // could mutate the list by calling the various add/remove methods. This prevents
13238            // the array from being modified while we iterate it.
13239            for (OnAttachStateChangeListener listener : listeners) {
13240                listener.onViewDetachedFromWindow(this);
13241            }
13242        }
13243
13244        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
13245            mAttachInfo.mScrollContainers.remove(this);
13246            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
13247        }
13248
13249        mAttachInfo = null;
13250        if (mOverlay != null) {
13251            mOverlay.getOverlayView().dispatchDetachedFromWindow();
13252        }
13253    }
13254
13255    /**
13256     * Cancel any deferred high-level input events that were previously posted to the event queue.
13257     *
13258     * <p>Many views post high-level events such as click handlers to the event queue
13259     * to run deferred in order to preserve a desired user experience - clearing visible
13260     * pressed states before executing, etc. This method will abort any events of this nature
13261     * that are currently in flight.</p>
13262     *
13263     * <p>Custom views that generate their own high-level deferred input events should override
13264     * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p>
13265     *
13266     * <p>This will also cancel pending input events for any child views.</p>
13267     *
13268     * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases.
13269     * This will not impact newer events posted after this call that may occur as a result of
13270     * lower-level input events still waiting in the queue. If you are trying to prevent
13271     * double-submitted  events for the duration of some sort of asynchronous transaction
13272     * you should also take other steps to protect against unexpected double inputs e.g. calling
13273     * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when
13274     * the transaction completes, tracking already submitted transaction IDs, etc.</p>
13275     */
13276    public final void cancelPendingInputEvents() {
13277        dispatchCancelPendingInputEvents();
13278    }
13279
13280    /**
13281     * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight.
13282     * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling.
13283     */
13284    void dispatchCancelPendingInputEvents() {
13285        mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER;
13286        onCancelPendingInputEvents();
13287        if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) {
13288            throw new SuperNotCalledException("View " + getClass().getSimpleName() +
13289                    " did not call through to super.onCancelPendingInputEvents()");
13290        }
13291    }
13292
13293    /**
13294     * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or
13295     * a parent view.
13296     *
13297     * <p>This method is responsible for removing any pending high-level input events that were
13298     * posted to the event queue to run later. Custom view classes that post their own deferred
13299     * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or
13300     * {@link android.os.Handler} should override this method, call
13301     * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate.
13302     * </p>
13303     */
13304    public void onCancelPendingInputEvents() {
13305        removePerformClickCallback();
13306        cancelLongPress();
13307        mPrivateFlags3 |= PFLAG3_CALLED_SUPER;
13308    }
13309
13310    /**
13311     * Store this view hierarchy's frozen state into the given container.
13312     *
13313     * @param container The SparseArray in which to save the view's state.
13314     *
13315     * @see #restoreHierarchyState(android.util.SparseArray)
13316     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13317     * @see #onSaveInstanceState()
13318     */
13319    public void saveHierarchyState(SparseArray<Parcelable> container) {
13320        dispatchSaveInstanceState(container);
13321    }
13322
13323    /**
13324     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
13325     * this view and its children. May be overridden to modify how freezing happens to a
13326     * view's children; for example, some views may want to not store state for their children.
13327     *
13328     * @param container The SparseArray in which to save the view's state.
13329     *
13330     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13331     * @see #saveHierarchyState(android.util.SparseArray)
13332     * @see #onSaveInstanceState()
13333     */
13334    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
13335        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
13336            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
13337            Parcelable state = onSaveInstanceState();
13338            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
13339                throw new IllegalStateException(
13340                        "Derived class did not call super.onSaveInstanceState()");
13341            }
13342            if (state != null) {
13343                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
13344                // + ": " + state);
13345                container.put(mID, state);
13346            }
13347        }
13348    }
13349
13350    /**
13351     * Hook allowing a view to generate a representation of its internal state
13352     * that can later be used to create a new instance with that same state.
13353     * This state should only contain information that is not persistent or can
13354     * not be reconstructed later. For example, you will never store your
13355     * current position on screen because that will be computed again when a
13356     * new instance of the view is placed in its view hierarchy.
13357     * <p>
13358     * Some examples of things you may store here: the current cursor position
13359     * in a text view (but usually not the text itself since that is stored in a
13360     * content provider or other persistent storage), the currently selected
13361     * item in a list view.
13362     *
13363     * @return Returns a Parcelable object containing the view's current dynamic
13364     *         state, or null if there is nothing interesting to save. The
13365     *         default implementation returns null.
13366     * @see #onRestoreInstanceState(android.os.Parcelable)
13367     * @see #saveHierarchyState(android.util.SparseArray)
13368     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13369     * @see #setSaveEnabled(boolean)
13370     */
13371    protected Parcelable onSaveInstanceState() {
13372        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
13373        return BaseSavedState.EMPTY_STATE;
13374    }
13375
13376    /**
13377     * Restore this view hierarchy's frozen state from the given container.
13378     *
13379     * @param container The SparseArray which holds previously frozen states.
13380     *
13381     * @see #saveHierarchyState(android.util.SparseArray)
13382     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13383     * @see #onRestoreInstanceState(android.os.Parcelable)
13384     */
13385    public void restoreHierarchyState(SparseArray<Parcelable> container) {
13386        dispatchRestoreInstanceState(container);
13387    }
13388
13389    /**
13390     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
13391     * state for this view and its children. May be overridden to modify how restoring
13392     * happens to a view's children; for example, some views may want to not store state
13393     * for their children.
13394     *
13395     * @param container The SparseArray which holds previously saved state.
13396     *
13397     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13398     * @see #restoreHierarchyState(android.util.SparseArray)
13399     * @see #onRestoreInstanceState(android.os.Parcelable)
13400     */
13401    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
13402        if (mID != NO_ID) {
13403            Parcelable state = container.get(mID);
13404            if (state != null) {
13405                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
13406                // + ": " + state);
13407                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
13408                onRestoreInstanceState(state);
13409                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
13410                    throw new IllegalStateException(
13411                            "Derived class did not call super.onRestoreInstanceState()");
13412                }
13413            }
13414        }
13415    }
13416
13417    /**
13418     * Hook allowing a view to re-apply a representation of its internal state that had previously
13419     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
13420     * null state.
13421     *
13422     * @param state The frozen state that had previously been returned by
13423     *        {@link #onSaveInstanceState}.
13424     *
13425     * @see #onSaveInstanceState()
13426     * @see #restoreHierarchyState(android.util.SparseArray)
13427     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13428     */
13429    protected void onRestoreInstanceState(Parcelable state) {
13430        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
13431        if (state != BaseSavedState.EMPTY_STATE && state != null) {
13432            throw new IllegalArgumentException("Wrong state class, expecting View State but "
13433                    + "received " + state.getClass().toString() + " instead. This usually happens "
13434                    + "when two views of different type have the same id in the same hierarchy. "
13435                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
13436                    + "other views do not use the same id.");
13437        }
13438    }
13439
13440    /**
13441     * <p>Return the time at which the drawing of the view hierarchy started.</p>
13442     *
13443     * @return the drawing start time in milliseconds
13444     */
13445    public long getDrawingTime() {
13446        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
13447    }
13448
13449    /**
13450     * <p>Enables or disables the duplication of the parent's state into this view. When
13451     * duplication is enabled, this view gets its drawable state from its parent rather
13452     * than from its own internal properties.</p>
13453     *
13454     * <p>Note: in the current implementation, setting this property to true after the
13455     * view was added to a ViewGroup might have no effect at all. This property should
13456     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
13457     *
13458     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
13459     * property is enabled, an exception will be thrown.</p>
13460     *
13461     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
13462     * parent, these states should not be affected by this method.</p>
13463     *
13464     * @param enabled True to enable duplication of the parent's drawable state, false
13465     *                to disable it.
13466     *
13467     * @see #getDrawableState()
13468     * @see #isDuplicateParentStateEnabled()
13469     */
13470    public void setDuplicateParentStateEnabled(boolean enabled) {
13471        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
13472    }
13473
13474    /**
13475     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
13476     *
13477     * @return True if this view's drawable state is duplicated from the parent,
13478     *         false otherwise
13479     *
13480     * @see #getDrawableState()
13481     * @see #setDuplicateParentStateEnabled(boolean)
13482     */
13483    public boolean isDuplicateParentStateEnabled() {
13484        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
13485    }
13486
13487    /**
13488     * <p>Specifies the type of layer backing this view. The layer can be
13489     * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13490     * {@link #LAYER_TYPE_HARDWARE}.</p>
13491     *
13492     * <p>A layer is associated with an optional {@link android.graphics.Paint}
13493     * instance that controls how the layer is composed on screen. The following
13494     * properties of the paint are taken into account when composing the layer:</p>
13495     * <ul>
13496     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
13497     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
13498     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
13499     * </ul>
13500     *
13501     * <p>If this view has an alpha value set to < 1.0 by calling
13502     * {@link #setAlpha(float)}, the alpha value of the layer's paint is superceded
13503     * by this view's alpha value.</p>
13504     *
13505     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE},
13506     * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE}
13507     * for more information on when and how to use layers.</p>
13508     *
13509     * @param layerType The type of layer to use with this view, must be one of
13510     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13511     *        {@link #LAYER_TYPE_HARDWARE}
13512     * @param paint The paint used to compose the layer. This argument is optional
13513     *        and can be null. It is ignored when the layer type is
13514     *        {@link #LAYER_TYPE_NONE}
13515     *
13516     * @see #getLayerType()
13517     * @see #LAYER_TYPE_NONE
13518     * @see #LAYER_TYPE_SOFTWARE
13519     * @see #LAYER_TYPE_HARDWARE
13520     * @see #setAlpha(float)
13521     *
13522     * @attr ref android.R.styleable#View_layerType
13523     */
13524    public void setLayerType(int layerType, Paint paint) {
13525        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
13526            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
13527                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
13528        }
13529
13530        boolean typeChanged = mRenderNode.setLayerType(layerType);
13531
13532        if (!typeChanged) {
13533            setLayerPaint(paint);
13534            return;
13535        }
13536
13537        // Destroy any previous software drawing cache if needed
13538        if (mLayerType == LAYER_TYPE_SOFTWARE) {
13539            destroyDrawingCache();
13540        }
13541
13542        mLayerType = layerType;
13543        final boolean layerDisabled = (mLayerType == LAYER_TYPE_NONE);
13544        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
13545        mRenderNode.setLayerPaint(mLayerPaint);
13546
13547        // draw() behaves differently if we are on a layer, so we need to
13548        // invalidate() here
13549        invalidateParentCaches();
13550        invalidate(true);
13551    }
13552
13553    /**
13554     * Updates the {@link Paint} object used with the current layer (used only if the current
13555     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
13556     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
13557     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
13558     * ensure that the view gets redrawn immediately.
13559     *
13560     * <p>A layer is associated with an optional {@link android.graphics.Paint}
13561     * instance that controls how the layer is composed on screen. The following
13562     * properties of the paint are taken into account when composing the layer:</p>
13563     * <ul>
13564     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
13565     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
13566     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
13567     * </ul>
13568     *
13569     * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the
13570     * alpha value of the layer's paint is superceded by this view's alpha value.</p>
13571     *
13572     * @param paint The paint used to compose the layer. This argument is optional
13573     *        and can be null. It is ignored when the layer type is
13574     *        {@link #LAYER_TYPE_NONE}
13575     *
13576     * @see #setLayerType(int, android.graphics.Paint)
13577     */
13578    public void setLayerPaint(Paint paint) {
13579        int layerType = getLayerType();
13580        if (layerType != LAYER_TYPE_NONE) {
13581            mLayerPaint = paint == null ? new Paint() : paint;
13582            if (layerType == LAYER_TYPE_HARDWARE) {
13583                if (mRenderNode.setLayerPaint(mLayerPaint)) {
13584                    invalidateViewProperty(false, false);
13585                }
13586            } else {
13587                invalidate();
13588            }
13589        }
13590    }
13591
13592    /**
13593     * Indicates whether this view has a static layer. A view with layer type
13594     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
13595     * dynamic.
13596     */
13597    boolean hasStaticLayer() {
13598        return true;
13599    }
13600
13601    /**
13602     * Indicates what type of layer is currently associated with this view. By default
13603     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
13604     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
13605     * for more information on the different types of layers.
13606     *
13607     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13608     *         {@link #LAYER_TYPE_HARDWARE}
13609     *
13610     * @see #setLayerType(int, android.graphics.Paint)
13611     * @see #buildLayer()
13612     * @see #LAYER_TYPE_NONE
13613     * @see #LAYER_TYPE_SOFTWARE
13614     * @see #LAYER_TYPE_HARDWARE
13615     */
13616    public int getLayerType() {
13617        return mLayerType;
13618    }
13619
13620    /**
13621     * Forces this view's layer to be created and this view to be rendered
13622     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
13623     * invoking this method will have no effect.
13624     *
13625     * This method can for instance be used to render a view into its layer before
13626     * starting an animation. If this view is complex, rendering into the layer
13627     * before starting the animation will avoid skipping frames.
13628     *
13629     * @throws IllegalStateException If this view is not attached to a window
13630     *
13631     * @see #setLayerType(int, android.graphics.Paint)
13632     */
13633    public void buildLayer() {
13634        if (mLayerType == LAYER_TYPE_NONE) return;
13635
13636        final AttachInfo attachInfo = mAttachInfo;
13637        if (attachInfo == null) {
13638            throw new IllegalStateException("This view must be attached to a window first");
13639        }
13640
13641        if (getWidth() == 0 || getHeight() == 0) {
13642            return;
13643        }
13644
13645        switch (mLayerType) {
13646            case LAYER_TYPE_HARDWARE:
13647                updateDisplayListIfDirty();
13648                if (attachInfo.mHardwareRenderer != null && mRenderNode.isValid()) {
13649                    attachInfo.mHardwareRenderer.buildLayer(mRenderNode);
13650                }
13651                break;
13652            case LAYER_TYPE_SOFTWARE:
13653                buildDrawingCache(true);
13654                break;
13655        }
13656    }
13657
13658    /**
13659     * If this View draws with a HardwareLayer, returns it.
13660     * Otherwise returns null
13661     *
13662     * TODO: Only TextureView uses this, can we eliminate it?
13663     */
13664    HardwareLayer getHardwareLayer() {
13665        return null;
13666    }
13667
13668    /**
13669     * Destroys all hardware rendering resources. This method is invoked
13670     * when the system needs to reclaim resources. Upon execution of this
13671     * method, you should free any OpenGL resources created by the view.
13672     *
13673     * Note: you <strong>must</strong> call
13674     * <code>super.destroyHardwareResources()</code> when overriding
13675     * this method.
13676     *
13677     * @hide
13678     */
13679    protected void destroyHardwareResources() {
13680        // Although the Layer will be destroyed by RenderNode, we want to release
13681        // the staging display list, which is also a signal to RenderNode that it's
13682        // safe to free its copy of the display list as it knows that we will
13683        // push an updated DisplayList if we try to draw again
13684        resetDisplayList();
13685    }
13686
13687    /**
13688     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
13689     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
13690     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
13691     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
13692     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
13693     * null.</p>
13694     *
13695     * <p>Enabling the drawing cache is similar to
13696     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
13697     * acceleration is turned off. When hardware acceleration is turned on, enabling the
13698     * drawing cache has no effect on rendering because the system uses a different mechanism
13699     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
13700     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
13701     * for information on how to enable software and hardware layers.</p>
13702     *
13703     * <p>This API can be used to manually generate
13704     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
13705     * {@link #getDrawingCache()}.</p>
13706     *
13707     * @param enabled true to enable the drawing cache, false otherwise
13708     *
13709     * @see #isDrawingCacheEnabled()
13710     * @see #getDrawingCache()
13711     * @see #buildDrawingCache()
13712     * @see #setLayerType(int, android.graphics.Paint)
13713     */
13714    public void setDrawingCacheEnabled(boolean enabled) {
13715        mCachingFailed = false;
13716        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
13717    }
13718
13719    /**
13720     * <p>Indicates whether the drawing cache is enabled for this view.</p>
13721     *
13722     * @return true if the drawing cache is enabled
13723     *
13724     * @see #setDrawingCacheEnabled(boolean)
13725     * @see #getDrawingCache()
13726     */
13727    @ViewDebug.ExportedProperty(category = "drawing")
13728    public boolean isDrawingCacheEnabled() {
13729        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
13730    }
13731
13732    /**
13733     * Debugging utility which recursively outputs the dirty state of a view and its
13734     * descendants.
13735     *
13736     * @hide
13737     */
13738    @SuppressWarnings({"UnusedDeclaration"})
13739    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
13740        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
13741                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
13742                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
13743                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
13744        if (clear) {
13745            mPrivateFlags &= clearMask;
13746        }
13747        if (this instanceof ViewGroup) {
13748            ViewGroup parent = (ViewGroup) this;
13749            final int count = parent.getChildCount();
13750            for (int i = 0; i < count; i++) {
13751                final View child = parent.getChildAt(i);
13752                child.outputDirtyFlags(indent + "  ", clear, clearMask);
13753            }
13754        }
13755    }
13756
13757    /**
13758     * This method is used by ViewGroup to cause its children to restore or recreate their
13759     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
13760     * to recreate its own display list, which would happen if it went through the normal
13761     * draw/dispatchDraw mechanisms.
13762     *
13763     * @hide
13764     */
13765    protected void dispatchGetDisplayList() {}
13766
13767    /**
13768     * A view that is not attached or hardware accelerated cannot create a display list.
13769     * This method checks these conditions and returns the appropriate result.
13770     *
13771     * @return true if view has the ability to create a display list, false otherwise.
13772     *
13773     * @hide
13774     */
13775    public boolean canHaveDisplayList() {
13776        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
13777    }
13778
13779    private void updateDisplayListIfDirty() {
13780        final RenderNode renderNode = mRenderNode;
13781        if (!canHaveDisplayList()) {
13782            // can't populate RenderNode, don't try
13783            return;
13784        }
13785
13786        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0
13787                || !renderNode.isValid()
13788                || (mRecreateDisplayList)) {
13789            // Don't need to recreate the display list, just need to tell our
13790            // children to restore/recreate theirs
13791            if (renderNode.isValid()
13792                    && !mRecreateDisplayList) {
13793                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13794                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13795                dispatchGetDisplayList();
13796
13797                return; // no work needed
13798            }
13799
13800            // If we got here, we're recreating it. Mark it as such to ensure that
13801            // we copy in child display lists into ours in drawChild()
13802            mRecreateDisplayList = true;
13803
13804            int width = mRight - mLeft;
13805            int height = mBottom - mTop;
13806            int layerType = getLayerType();
13807
13808            final HardwareCanvas canvas = renderNode.start(width, height);
13809            canvas.setHighContrastText(mAttachInfo.mHighContrastText);
13810
13811            try {
13812                final HardwareLayer layer = getHardwareLayer();
13813                if (layer != null && layer.isValid()) {
13814                    canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
13815                } else if (layerType == LAYER_TYPE_SOFTWARE) {
13816                    buildDrawingCache(true);
13817                    Bitmap cache = getDrawingCache(true);
13818                    if (cache != null) {
13819                        canvas.drawBitmap(cache, 0, 0, mLayerPaint);
13820                    }
13821                } else {
13822                    computeScroll();
13823
13824                    canvas.translate(-mScrollX, -mScrollY);
13825                    mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13826                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13827
13828                    // Fast path for layouts with no backgrounds
13829                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13830                        dispatchDraw(canvas);
13831                        if (mOverlay != null && !mOverlay.isEmpty()) {
13832                            mOverlay.getOverlayView().draw(canvas);
13833                        }
13834                    } else {
13835                        draw(canvas);
13836                    }
13837                    drawAccessibilityFocus(canvas);
13838                }
13839            } finally {
13840                renderNode.end(canvas);
13841                setDisplayListProperties(renderNode);
13842            }
13843        } else {
13844            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13845            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13846        }
13847    }
13848
13849    /**
13850     * Returns a RenderNode with View draw content recorded, which can be
13851     * used to draw this view again without executing its draw method.
13852     *
13853     * @return A RenderNode ready to replay, or null if caching is not enabled.
13854     *
13855     * @hide
13856     */
13857    public RenderNode getDisplayList() {
13858        updateDisplayListIfDirty();
13859        return mRenderNode;
13860    }
13861
13862    private void resetDisplayList() {
13863        if (mRenderNode.isValid()) {
13864            mRenderNode.destroyDisplayListData();
13865        }
13866
13867        if (mBackgroundRenderNode != null && mBackgroundRenderNode.isValid()) {
13868            mBackgroundRenderNode.destroyDisplayListData();
13869        }
13870    }
13871
13872    /**
13873     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
13874     *
13875     * @return A non-scaled bitmap representing this view or null if cache is disabled.
13876     *
13877     * @see #getDrawingCache(boolean)
13878     */
13879    public Bitmap getDrawingCache() {
13880        return getDrawingCache(false);
13881    }
13882
13883    /**
13884     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
13885     * is null when caching is disabled. If caching is enabled and the cache is not ready,
13886     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
13887     * draw from the cache when the cache is enabled. To benefit from the cache, you must
13888     * request the drawing cache by calling this method and draw it on screen if the
13889     * returned bitmap is not null.</p>
13890     *
13891     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
13892     * this method will create a bitmap of the same size as this view. Because this bitmap
13893     * will be drawn scaled by the parent ViewGroup, the result on screen might show
13894     * scaling artifacts. To avoid such artifacts, you should call this method by setting
13895     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
13896     * size than the view. This implies that your application must be able to handle this
13897     * size.</p>
13898     *
13899     * @param autoScale Indicates whether the generated bitmap should be scaled based on
13900     *        the current density of the screen when the application is in compatibility
13901     *        mode.
13902     *
13903     * @return A bitmap representing this view or null if cache is disabled.
13904     *
13905     * @see #setDrawingCacheEnabled(boolean)
13906     * @see #isDrawingCacheEnabled()
13907     * @see #buildDrawingCache(boolean)
13908     * @see #destroyDrawingCache()
13909     */
13910    public Bitmap getDrawingCache(boolean autoScale) {
13911        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
13912            return null;
13913        }
13914        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
13915            buildDrawingCache(autoScale);
13916        }
13917        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
13918    }
13919
13920    /**
13921     * <p>Frees the resources used by the drawing cache. If you call
13922     * {@link #buildDrawingCache()} manually without calling
13923     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
13924     * should cleanup the cache with this method afterwards.</p>
13925     *
13926     * @see #setDrawingCacheEnabled(boolean)
13927     * @see #buildDrawingCache()
13928     * @see #getDrawingCache()
13929     */
13930    public void destroyDrawingCache() {
13931        if (mDrawingCache != null) {
13932            mDrawingCache.recycle();
13933            mDrawingCache = null;
13934        }
13935        if (mUnscaledDrawingCache != null) {
13936            mUnscaledDrawingCache.recycle();
13937            mUnscaledDrawingCache = null;
13938        }
13939    }
13940
13941    /**
13942     * Setting a solid background color for the drawing cache's bitmaps will improve
13943     * performance and memory usage. Note, though that this should only be used if this
13944     * view will always be drawn on top of a solid color.
13945     *
13946     * @param color The background color to use for the drawing cache's bitmap
13947     *
13948     * @see #setDrawingCacheEnabled(boolean)
13949     * @see #buildDrawingCache()
13950     * @see #getDrawingCache()
13951     */
13952    public void setDrawingCacheBackgroundColor(int color) {
13953        if (color != mDrawingCacheBackgroundColor) {
13954            mDrawingCacheBackgroundColor = color;
13955            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
13956        }
13957    }
13958
13959    /**
13960     * @see #setDrawingCacheBackgroundColor(int)
13961     *
13962     * @return The background color to used for the drawing cache's bitmap
13963     */
13964    public int getDrawingCacheBackgroundColor() {
13965        return mDrawingCacheBackgroundColor;
13966    }
13967
13968    /**
13969     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
13970     *
13971     * @see #buildDrawingCache(boolean)
13972     */
13973    public void buildDrawingCache() {
13974        buildDrawingCache(false);
13975    }
13976
13977    /**
13978     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
13979     *
13980     * <p>If you call {@link #buildDrawingCache()} manually without calling
13981     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
13982     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
13983     *
13984     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
13985     * this method will create a bitmap of the same size as this view. Because this bitmap
13986     * will be drawn scaled by the parent ViewGroup, the result on screen might show
13987     * scaling artifacts. To avoid such artifacts, you should call this method by setting
13988     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
13989     * size than the view. This implies that your application must be able to handle this
13990     * size.</p>
13991     *
13992     * <p>You should avoid calling this method when hardware acceleration is enabled. If
13993     * you do not need the drawing cache bitmap, calling this method will increase memory
13994     * usage and cause the view to be rendered in software once, thus negatively impacting
13995     * performance.</p>
13996     *
13997     * @see #getDrawingCache()
13998     * @see #destroyDrawingCache()
13999     */
14000    public void buildDrawingCache(boolean autoScale) {
14001        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
14002                mDrawingCache == null : mUnscaledDrawingCache == null)) {
14003            mCachingFailed = false;
14004
14005            int width = mRight - mLeft;
14006            int height = mBottom - mTop;
14007
14008            final AttachInfo attachInfo = mAttachInfo;
14009            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
14010
14011            if (autoScale && scalingRequired) {
14012                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
14013                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
14014            }
14015
14016            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
14017            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
14018            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
14019
14020            final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
14021            final long drawingCacheSize =
14022                    ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
14023            if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
14024                if (width > 0 && height > 0) {
14025                    Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs "
14026                            + projectedBitmapSize + " bytes, only "
14027                            + drawingCacheSize + " available");
14028                }
14029                destroyDrawingCache();
14030                mCachingFailed = true;
14031                return;
14032            }
14033
14034            boolean clear = true;
14035            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
14036
14037            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
14038                Bitmap.Config quality;
14039                if (!opaque) {
14040                    // Never pick ARGB_4444 because it looks awful
14041                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
14042                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
14043                        case DRAWING_CACHE_QUALITY_AUTO:
14044                        case DRAWING_CACHE_QUALITY_LOW:
14045                        case DRAWING_CACHE_QUALITY_HIGH:
14046                        default:
14047                            quality = Bitmap.Config.ARGB_8888;
14048                            break;
14049                    }
14050                } else {
14051                    // Optimization for translucent windows
14052                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
14053                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
14054                }
14055
14056                // Try to cleanup memory
14057                if (bitmap != null) bitmap.recycle();
14058
14059                try {
14060                    bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
14061                            width, height, quality);
14062                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
14063                    if (autoScale) {
14064                        mDrawingCache = bitmap;
14065                    } else {
14066                        mUnscaledDrawingCache = bitmap;
14067                    }
14068                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
14069                } catch (OutOfMemoryError e) {
14070                    // If there is not enough memory to create the bitmap cache, just
14071                    // ignore the issue as bitmap caches are not required to draw the
14072                    // view hierarchy
14073                    if (autoScale) {
14074                        mDrawingCache = null;
14075                    } else {
14076                        mUnscaledDrawingCache = null;
14077                    }
14078                    mCachingFailed = true;
14079                    return;
14080                }
14081
14082                clear = drawingCacheBackgroundColor != 0;
14083            }
14084
14085            Canvas canvas;
14086            if (attachInfo != null) {
14087                canvas = attachInfo.mCanvas;
14088                if (canvas == null) {
14089                    canvas = new Canvas();
14090                }
14091                canvas.setBitmap(bitmap);
14092                // Temporarily clobber the cached Canvas in case one of our children
14093                // is also using a drawing cache. Without this, the children would
14094                // steal the canvas by attaching their own bitmap to it and bad, bad
14095                // thing would happen (invisible views, corrupted drawings, etc.)
14096                attachInfo.mCanvas = null;
14097            } else {
14098                // This case should hopefully never or seldom happen
14099                canvas = new Canvas(bitmap);
14100            }
14101
14102            if (clear) {
14103                bitmap.eraseColor(drawingCacheBackgroundColor);
14104            }
14105
14106            computeScroll();
14107            final int restoreCount = canvas.save();
14108
14109            if (autoScale && scalingRequired) {
14110                final float scale = attachInfo.mApplicationScale;
14111                canvas.scale(scale, scale);
14112            }
14113
14114            canvas.translate(-mScrollX, -mScrollY);
14115
14116            mPrivateFlags |= PFLAG_DRAWN;
14117            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
14118                    mLayerType != LAYER_TYPE_NONE) {
14119                mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
14120            }
14121
14122            // Fast path for layouts with no backgrounds
14123            if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14124                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14125                dispatchDraw(canvas);
14126                if (mOverlay != null && !mOverlay.isEmpty()) {
14127                    mOverlay.getOverlayView().draw(canvas);
14128                }
14129            } else {
14130                draw(canvas);
14131            }
14132            drawAccessibilityFocus(canvas);
14133
14134            canvas.restoreToCount(restoreCount);
14135            canvas.setBitmap(null);
14136
14137            if (attachInfo != null) {
14138                // Restore the cached Canvas for our siblings
14139                attachInfo.mCanvas = canvas;
14140            }
14141        }
14142    }
14143
14144    /**
14145     * Create a snapshot of the view into a bitmap.  We should probably make
14146     * some form of this public, but should think about the API.
14147     */
14148    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
14149        int width = mRight - mLeft;
14150        int height = mBottom - mTop;
14151
14152        final AttachInfo attachInfo = mAttachInfo;
14153        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
14154        width = (int) ((width * scale) + 0.5f);
14155        height = (int) ((height * scale) + 0.5f);
14156
14157        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
14158                width > 0 ? width : 1, height > 0 ? height : 1, quality);
14159        if (bitmap == null) {
14160            throw new OutOfMemoryError();
14161        }
14162
14163        Resources resources = getResources();
14164        if (resources != null) {
14165            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
14166        }
14167
14168        Canvas canvas;
14169        if (attachInfo != null) {
14170            canvas = attachInfo.mCanvas;
14171            if (canvas == null) {
14172                canvas = new Canvas();
14173            }
14174            canvas.setBitmap(bitmap);
14175            // Temporarily clobber the cached Canvas in case one of our children
14176            // is also using a drawing cache. Without this, the children would
14177            // steal the canvas by attaching their own bitmap to it and bad, bad
14178            // things would happen (invisible views, corrupted drawings, etc.)
14179            attachInfo.mCanvas = null;
14180        } else {
14181            // This case should hopefully never or seldom happen
14182            canvas = new Canvas(bitmap);
14183        }
14184
14185        if ((backgroundColor & 0xff000000) != 0) {
14186            bitmap.eraseColor(backgroundColor);
14187        }
14188
14189        computeScroll();
14190        final int restoreCount = canvas.save();
14191        canvas.scale(scale, scale);
14192        canvas.translate(-mScrollX, -mScrollY);
14193
14194        // Temporarily remove the dirty mask
14195        int flags = mPrivateFlags;
14196        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14197
14198        // Fast path for layouts with no backgrounds
14199        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14200            dispatchDraw(canvas);
14201            if (mOverlay != null && !mOverlay.isEmpty()) {
14202                mOverlay.getOverlayView().draw(canvas);
14203            }
14204        } else {
14205            draw(canvas);
14206        }
14207        drawAccessibilityFocus(canvas);
14208
14209        mPrivateFlags = flags;
14210
14211        canvas.restoreToCount(restoreCount);
14212        canvas.setBitmap(null);
14213
14214        if (attachInfo != null) {
14215            // Restore the cached Canvas for our siblings
14216            attachInfo.mCanvas = canvas;
14217        }
14218
14219        return bitmap;
14220    }
14221
14222    /**
14223     * Indicates whether this View is currently in edit mode. A View is usually
14224     * in edit mode when displayed within a developer tool. For instance, if
14225     * this View is being drawn by a visual user interface builder, this method
14226     * should return true.
14227     *
14228     * Subclasses should check the return value of this method to provide
14229     * different behaviors if their normal behavior might interfere with the
14230     * host environment. For instance: the class spawns a thread in its
14231     * constructor, the drawing code relies on device-specific features, etc.
14232     *
14233     * This method is usually checked in the drawing code of custom widgets.
14234     *
14235     * @return True if this View is in edit mode, false otherwise.
14236     */
14237    public boolean isInEditMode() {
14238        return false;
14239    }
14240
14241    /**
14242     * If the View draws content inside its padding and enables fading edges,
14243     * it needs to support padding offsets. Padding offsets are added to the
14244     * fading edges to extend the length of the fade so that it covers pixels
14245     * drawn inside the padding.
14246     *
14247     * Subclasses of this class should override this method if they need
14248     * to draw content inside the padding.
14249     *
14250     * @return True if padding offset must be applied, false otherwise.
14251     *
14252     * @see #getLeftPaddingOffset()
14253     * @see #getRightPaddingOffset()
14254     * @see #getTopPaddingOffset()
14255     * @see #getBottomPaddingOffset()
14256     *
14257     * @since CURRENT
14258     */
14259    protected boolean isPaddingOffsetRequired() {
14260        return false;
14261    }
14262
14263    /**
14264     * Amount by which to extend the left fading region. Called only when
14265     * {@link #isPaddingOffsetRequired()} returns true.
14266     *
14267     * @return The left padding offset in pixels.
14268     *
14269     * @see #isPaddingOffsetRequired()
14270     *
14271     * @since CURRENT
14272     */
14273    protected int getLeftPaddingOffset() {
14274        return 0;
14275    }
14276
14277    /**
14278     * Amount by which to extend the right fading region. Called only when
14279     * {@link #isPaddingOffsetRequired()} returns true.
14280     *
14281     * @return The right padding offset in pixels.
14282     *
14283     * @see #isPaddingOffsetRequired()
14284     *
14285     * @since CURRENT
14286     */
14287    protected int getRightPaddingOffset() {
14288        return 0;
14289    }
14290
14291    /**
14292     * Amount by which to extend the top fading region. Called only when
14293     * {@link #isPaddingOffsetRequired()} returns true.
14294     *
14295     * @return The top padding offset in pixels.
14296     *
14297     * @see #isPaddingOffsetRequired()
14298     *
14299     * @since CURRENT
14300     */
14301    protected int getTopPaddingOffset() {
14302        return 0;
14303    }
14304
14305    /**
14306     * Amount by which to extend the bottom fading region. Called only when
14307     * {@link #isPaddingOffsetRequired()} returns true.
14308     *
14309     * @return The bottom padding offset in pixels.
14310     *
14311     * @see #isPaddingOffsetRequired()
14312     *
14313     * @since CURRENT
14314     */
14315    protected int getBottomPaddingOffset() {
14316        return 0;
14317    }
14318
14319    /**
14320     * @hide
14321     * @param offsetRequired
14322     */
14323    protected int getFadeTop(boolean offsetRequired) {
14324        int top = mPaddingTop;
14325        if (offsetRequired) top += getTopPaddingOffset();
14326        return top;
14327    }
14328
14329    /**
14330     * @hide
14331     * @param offsetRequired
14332     */
14333    protected int getFadeHeight(boolean offsetRequired) {
14334        int padding = mPaddingTop;
14335        if (offsetRequired) padding += getTopPaddingOffset();
14336        return mBottom - mTop - mPaddingBottom - padding;
14337    }
14338
14339    /**
14340     * <p>Indicates whether this view is attached to a hardware accelerated
14341     * window or not.</p>
14342     *
14343     * <p>Even if this method returns true, it does not mean that every call
14344     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
14345     * accelerated {@link android.graphics.Canvas}. For instance, if this view
14346     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
14347     * window is hardware accelerated,
14348     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
14349     * return false, and this method will return true.</p>
14350     *
14351     * @return True if the view is attached to a window and the window is
14352     *         hardware accelerated; false in any other case.
14353     */
14354    @ViewDebug.ExportedProperty(category = "drawing")
14355    public boolean isHardwareAccelerated() {
14356        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
14357    }
14358
14359    /**
14360     * Sets a rectangular area on this view to which the view will be clipped
14361     * when it is drawn. Setting the value to null will remove the clip bounds
14362     * and the view will draw normally, using its full bounds.
14363     *
14364     * @param clipBounds The rectangular area, in the local coordinates of
14365     * this view, to which future drawing operations will be clipped.
14366     */
14367    public void setClipBounds(Rect clipBounds) {
14368        if (clipBounds != null) {
14369            if (clipBounds.equals(mClipBounds)) {
14370                return;
14371            }
14372            if (mClipBounds == null) {
14373                invalidate();
14374                mClipBounds = new Rect(clipBounds);
14375            } else {
14376                invalidate(Math.min(mClipBounds.left, clipBounds.left),
14377                        Math.min(mClipBounds.top, clipBounds.top),
14378                        Math.max(mClipBounds.right, clipBounds.right),
14379                        Math.max(mClipBounds.bottom, clipBounds.bottom));
14380                mClipBounds.set(clipBounds);
14381            }
14382        } else {
14383            if (mClipBounds != null) {
14384                invalidate();
14385                mClipBounds = null;
14386            }
14387        }
14388        mRenderNode.setClipBounds(mClipBounds);
14389    }
14390
14391    /**
14392     * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}.
14393     *
14394     * @return A copy of the current clip bounds if clip bounds are set,
14395     * otherwise null.
14396     */
14397    public Rect getClipBounds() {
14398        return (mClipBounds != null) ? new Rect(mClipBounds) : null;
14399    }
14400
14401    /**
14402     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
14403     * case of an active Animation being run on the view.
14404     */
14405    private boolean drawAnimation(ViewGroup parent, long drawingTime,
14406            Animation a, boolean scalingRequired) {
14407        Transformation invalidationTransform;
14408        final int flags = parent.mGroupFlags;
14409        final boolean initialized = a.isInitialized();
14410        if (!initialized) {
14411            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
14412            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
14413            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
14414            onAnimationStart();
14415        }
14416
14417        final Transformation t = parent.getChildTransformation();
14418        boolean more = a.getTransformation(drawingTime, t, 1f);
14419        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
14420            if (parent.mInvalidationTransformation == null) {
14421                parent.mInvalidationTransformation = new Transformation();
14422            }
14423            invalidationTransform = parent.mInvalidationTransformation;
14424            a.getTransformation(drawingTime, invalidationTransform, 1f);
14425        } else {
14426            invalidationTransform = t;
14427        }
14428
14429        if (more) {
14430            if (!a.willChangeBounds()) {
14431                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
14432                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
14433                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
14434                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
14435                    // The child need to draw an animation, potentially offscreen, so
14436                    // make sure we do not cancel invalidate requests
14437                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
14438                    parent.invalidate(mLeft, mTop, mRight, mBottom);
14439                }
14440            } else {
14441                if (parent.mInvalidateRegion == null) {
14442                    parent.mInvalidateRegion = new RectF();
14443                }
14444                final RectF region = parent.mInvalidateRegion;
14445                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
14446                        invalidationTransform);
14447
14448                // The child need to draw an animation, potentially offscreen, so
14449                // make sure we do not cancel invalidate requests
14450                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
14451
14452                final int left = mLeft + (int) region.left;
14453                final int top = mTop + (int) region.top;
14454                parent.invalidate(left, top, left + (int) (region.width() + .5f),
14455                        top + (int) (region.height() + .5f));
14456            }
14457        }
14458        return more;
14459    }
14460
14461    /**
14462     * This method is called by getDisplayList() when a display list is recorded for a View.
14463     * It pushes any properties to the RenderNode that aren't managed by the RenderNode.
14464     */
14465    void setDisplayListProperties(RenderNode renderNode) {
14466        if (renderNode != null) {
14467            renderNode.setHasOverlappingRendering(hasOverlappingRendering());
14468            if (mParent instanceof ViewGroup) {
14469                renderNode.setClipToBounds(
14470                        (((ViewGroup) mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0);
14471            }
14472            float alpha = 1;
14473            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
14474                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
14475                ViewGroup parentVG = (ViewGroup) mParent;
14476                final Transformation t = parentVG.getChildTransformation();
14477                if (parentVG.getChildStaticTransformation(this, t)) {
14478                    final int transformType = t.getTransformationType();
14479                    if (transformType != Transformation.TYPE_IDENTITY) {
14480                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
14481                            alpha = t.getAlpha();
14482                        }
14483                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
14484                            renderNode.setStaticMatrix(t.getMatrix());
14485                        }
14486                    }
14487                }
14488            }
14489            if (mTransformationInfo != null) {
14490                alpha *= getFinalAlpha();
14491                if (alpha < 1) {
14492                    final int multipliedAlpha = (int) (255 * alpha);
14493                    if (onSetAlpha(multipliedAlpha)) {
14494                        alpha = 1;
14495                    }
14496                }
14497                renderNode.setAlpha(alpha);
14498            } else if (alpha < 1) {
14499                renderNode.setAlpha(alpha);
14500            }
14501        }
14502    }
14503
14504    /**
14505     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
14506     * This draw() method is an implementation detail and is not intended to be overridden or
14507     * to be called from anywhere else other than ViewGroup.drawChild().
14508     */
14509    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
14510        boolean usingRenderNodeProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
14511        boolean more = false;
14512        final boolean childHasIdentityMatrix = hasIdentityMatrix();
14513        final int flags = parent.mGroupFlags;
14514
14515        if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) {
14516            parent.getChildTransformation().clear();
14517            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14518        }
14519
14520        Transformation transformToApply = null;
14521        boolean concatMatrix = false;
14522
14523        boolean scalingRequired = false;
14524        boolean caching;
14525        int layerType = getLayerType();
14526
14527        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
14528        if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 ||
14529                (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) {
14530            caching = true;
14531            // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList
14532            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
14533        } else {
14534            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
14535        }
14536
14537        final Animation a = getAnimation();
14538        if (a != null) {
14539            more = drawAnimation(parent, drawingTime, a, scalingRequired);
14540            concatMatrix = a.willChangeTransformationMatrix();
14541            if (concatMatrix) {
14542                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
14543            }
14544            transformToApply = parent.getChildTransformation();
14545        } else {
14546            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) {
14547                // No longer animating: clear out old animation matrix
14548                mRenderNode.setAnimationMatrix(null);
14549                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
14550            }
14551            if (!usingRenderNodeProperties &&
14552                    (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
14553                final Transformation t = parent.getChildTransformation();
14554                final boolean hasTransform = parent.getChildStaticTransformation(this, t);
14555                if (hasTransform) {
14556                    final int transformType = t.getTransformationType();
14557                    transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null;
14558                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
14559                }
14560            }
14561        }
14562
14563        concatMatrix |= !childHasIdentityMatrix;
14564
14565        // Sets the flag as early as possible to allow draw() implementations
14566        // to call invalidate() successfully when doing animations
14567        mPrivateFlags |= PFLAG_DRAWN;
14568
14569        if (!concatMatrix &&
14570                (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
14571                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
14572                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
14573                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
14574            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
14575            return more;
14576        }
14577        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
14578
14579        if (hardwareAccelerated) {
14580            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
14581            // retain the flag's value temporarily in the mRecreateDisplayList flag
14582            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED;
14583            mPrivateFlags &= ~PFLAG_INVALIDATED;
14584        }
14585
14586        RenderNode renderNode = null;
14587        Bitmap cache = null;
14588        boolean hasDisplayList = false;
14589        if (caching) {
14590            if (!hardwareAccelerated) {
14591                if (layerType != LAYER_TYPE_NONE) {
14592                    layerType = LAYER_TYPE_SOFTWARE;
14593                    buildDrawingCache(true);
14594                }
14595                cache = getDrawingCache(true);
14596            } else {
14597                switch (layerType) {
14598                    case LAYER_TYPE_SOFTWARE:
14599                        if (usingRenderNodeProperties) {
14600                            hasDisplayList = canHaveDisplayList();
14601                        } else {
14602                            buildDrawingCache(true);
14603                            cache = getDrawingCache(true);
14604                        }
14605                        break;
14606                    case LAYER_TYPE_HARDWARE:
14607                        if (usingRenderNodeProperties) {
14608                            hasDisplayList = canHaveDisplayList();
14609                        }
14610                        break;
14611                    case LAYER_TYPE_NONE:
14612                        // Delay getting the display list until animation-driven alpha values are
14613                        // set up and possibly passed on to the view
14614                        hasDisplayList = canHaveDisplayList();
14615                        break;
14616                }
14617            }
14618        }
14619        usingRenderNodeProperties &= hasDisplayList;
14620        if (usingRenderNodeProperties) {
14621            renderNode = getDisplayList();
14622            if (!renderNode.isValid()) {
14623                // Uncommon, but possible. If a view is removed from the hierarchy during the call
14624                // to getDisplayList(), the display list will be marked invalid and we should not
14625                // try to use it again.
14626                renderNode = null;
14627                hasDisplayList = false;
14628                usingRenderNodeProperties = false;
14629            }
14630        }
14631
14632        int sx = 0;
14633        int sy = 0;
14634        if (!hasDisplayList) {
14635            computeScroll();
14636            sx = mScrollX;
14637            sy = mScrollY;
14638        }
14639
14640        final boolean hasNoCache = cache == null || hasDisplayList;
14641        final boolean offsetForScroll = cache == null && !hasDisplayList &&
14642                layerType != LAYER_TYPE_HARDWARE;
14643
14644        int restoreTo = -1;
14645        if (!usingRenderNodeProperties || transformToApply != null) {
14646            restoreTo = canvas.save();
14647        }
14648        if (offsetForScroll) {
14649            canvas.translate(mLeft - sx, mTop - sy);
14650        } else {
14651            if (!usingRenderNodeProperties) {
14652                canvas.translate(mLeft, mTop);
14653            }
14654            if (scalingRequired) {
14655                if (usingRenderNodeProperties) {
14656                    // TODO: Might not need this if we put everything inside the DL
14657                    restoreTo = canvas.save();
14658                }
14659                // mAttachInfo cannot be null, otherwise scalingRequired == false
14660                final float scale = 1.0f / mAttachInfo.mApplicationScale;
14661                canvas.scale(scale, scale);
14662            }
14663        }
14664
14665        float alpha = usingRenderNodeProperties ? 1 : (getAlpha() * getTransitionAlpha());
14666        if (transformToApply != null || alpha < 1 ||  !hasIdentityMatrix() ||
14667                (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
14668            if (transformToApply != null || !childHasIdentityMatrix) {
14669                int transX = 0;
14670                int transY = 0;
14671
14672                if (offsetForScroll) {
14673                    transX = -sx;
14674                    transY = -sy;
14675                }
14676
14677                if (transformToApply != null) {
14678                    if (concatMatrix) {
14679                        if (usingRenderNodeProperties) {
14680                            renderNode.setAnimationMatrix(transformToApply.getMatrix());
14681                        } else {
14682                            // Undo the scroll translation, apply the transformation matrix,
14683                            // then redo the scroll translate to get the correct result.
14684                            canvas.translate(-transX, -transY);
14685                            canvas.concat(transformToApply.getMatrix());
14686                            canvas.translate(transX, transY);
14687                        }
14688                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14689                    }
14690
14691                    float transformAlpha = transformToApply.getAlpha();
14692                    if (transformAlpha < 1) {
14693                        alpha *= transformAlpha;
14694                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14695                    }
14696                }
14697
14698                if (!childHasIdentityMatrix && !usingRenderNodeProperties) {
14699                    canvas.translate(-transX, -transY);
14700                    canvas.concat(getMatrix());
14701                    canvas.translate(transX, transY);
14702                }
14703            }
14704
14705            // Deal with alpha if it is or used to be <1
14706            if (alpha < 1 ||
14707                    (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
14708                if (alpha < 1) {
14709                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
14710                } else {
14711                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
14712                }
14713                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14714                if (hasNoCache) {
14715                    final int multipliedAlpha = (int) (255 * alpha);
14716                    if (!onSetAlpha(multipliedAlpha)) {
14717                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
14718                        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 ||
14719                                layerType != LAYER_TYPE_NONE) {
14720                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
14721                        }
14722                        if (usingRenderNodeProperties) {
14723                            renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha());
14724                        } else  if (layerType == LAYER_TYPE_NONE) {
14725                            final int scrollX = hasDisplayList ? 0 : sx;
14726                            final int scrollY = hasDisplayList ? 0 : sy;
14727                            canvas.saveLayerAlpha(scrollX, scrollY,
14728                                    scrollX + (mRight - mLeft), scrollY + (mBottom - mTop),
14729                                    multipliedAlpha, layerFlags);
14730                        }
14731                    } else {
14732                        // Alpha is handled by the child directly, clobber the layer's alpha
14733                        mPrivateFlags |= PFLAG_ALPHA_SET;
14734                    }
14735                }
14736            }
14737        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
14738            onSetAlpha(255);
14739            mPrivateFlags &= ~PFLAG_ALPHA_SET;
14740        }
14741
14742        if (!usingRenderNodeProperties) {
14743            // apply clips directly, since RenderNode won't do it for this draw
14744            if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN
14745                    && cache == null) {
14746                if (offsetForScroll) {
14747                    canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
14748                } else {
14749                    if (!scalingRequired || cache == null) {
14750                        canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
14751                    } else {
14752                        canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
14753                    }
14754                }
14755            }
14756
14757            if (mClipBounds != null) {
14758                // clip bounds ignore scroll
14759                canvas.clipRect(mClipBounds);
14760            }
14761        }
14762
14763
14764
14765        if (!usingRenderNodeProperties && hasDisplayList) {
14766            renderNode = getDisplayList();
14767            if (!renderNode.isValid()) {
14768                // Uncommon, but possible. If a view is removed from the hierarchy during the call
14769                // to getDisplayList(), the display list will be marked invalid and we should not
14770                // try to use it again.
14771                renderNode = null;
14772                hasDisplayList = false;
14773            }
14774        }
14775
14776        if (hasNoCache) {
14777            boolean layerRendered = false;
14778            if (layerType == LAYER_TYPE_HARDWARE && !usingRenderNodeProperties) {
14779                final HardwareLayer layer = getHardwareLayer();
14780                if (layer != null && layer.isValid()) {
14781                    int restoreAlpha = mLayerPaint.getAlpha();
14782                    mLayerPaint.setAlpha((int) (alpha * 255));
14783                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
14784                    mLayerPaint.setAlpha(restoreAlpha);
14785                    layerRendered = true;
14786                } else {
14787                    final int scrollX = hasDisplayList ? 0 : sx;
14788                    final int scrollY = hasDisplayList ? 0 : sy;
14789                    canvas.saveLayer(scrollX, scrollY,
14790                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
14791                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
14792                }
14793            }
14794
14795            if (!layerRendered) {
14796                if (!hasDisplayList) {
14797                    // Fast path for layouts with no backgrounds
14798                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14799                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14800                        dispatchDraw(canvas);
14801                        if (mOverlay != null && !mOverlay.isEmpty()) {
14802                            mOverlay.getOverlayView().draw(canvas);
14803                        }
14804                    } else {
14805                        draw(canvas);
14806                    }
14807                    drawAccessibilityFocus(canvas);
14808                } else {
14809                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14810                    ((HardwareCanvas) canvas).drawRenderNode(renderNode, null, flags);
14811                }
14812            }
14813        } else if (cache != null) {
14814            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14815            Paint cachePaint;
14816            int restoreAlpha = 0;
14817
14818            if (layerType == LAYER_TYPE_NONE) {
14819                cachePaint = parent.mCachePaint;
14820                if (cachePaint == null) {
14821                    cachePaint = new Paint();
14822                    cachePaint.setDither(false);
14823                    parent.mCachePaint = cachePaint;
14824                }
14825            } else {
14826                cachePaint = mLayerPaint;
14827                restoreAlpha = mLayerPaint.getAlpha();
14828            }
14829            cachePaint.setAlpha((int) (alpha * 255));
14830            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
14831            cachePaint.setAlpha(restoreAlpha);
14832        }
14833
14834        if (restoreTo >= 0) {
14835            canvas.restoreToCount(restoreTo);
14836        }
14837
14838        if (a != null && !more) {
14839            if (!hardwareAccelerated && !a.getFillAfter()) {
14840                onSetAlpha(255);
14841            }
14842            parent.finishAnimatingView(this, a);
14843        }
14844
14845        if (more && hardwareAccelerated) {
14846            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
14847                // alpha animations should cause the child to recreate its display list
14848                invalidate(true);
14849            }
14850        }
14851
14852        mRecreateDisplayList = false;
14853
14854        return more;
14855    }
14856
14857    /**
14858     * Manually render this view (and all of its children) to the given Canvas.
14859     * The view must have already done a full layout before this function is
14860     * called.  When implementing a view, implement
14861     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
14862     * If you do need to override this method, call the superclass version.
14863     *
14864     * @param canvas The Canvas to which the View is rendered.
14865     */
14866    public void draw(Canvas canvas) {
14867        final int privateFlags = mPrivateFlags;
14868        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
14869                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
14870        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
14871
14872        /*
14873         * Draw traversal performs several drawing steps which must be executed
14874         * in the appropriate order:
14875         *
14876         *      1. Draw the background
14877         *      2. If necessary, save the canvas' layers to prepare for fading
14878         *      3. Draw view's content
14879         *      4. Draw children
14880         *      5. If necessary, draw the fading edges and restore layers
14881         *      6. Draw decorations (scrollbars for instance)
14882         */
14883
14884        // Step 1, draw the background, if needed
14885        int saveCount;
14886
14887        if (!dirtyOpaque) {
14888            drawBackground(canvas);
14889        }
14890
14891        // skip step 2 & 5 if possible (common case)
14892        final int viewFlags = mViewFlags;
14893        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
14894        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
14895        if (!verticalEdges && !horizontalEdges) {
14896            // Step 3, draw the content
14897            if (!dirtyOpaque) onDraw(canvas);
14898
14899            // Step 4, draw the children
14900            dispatchDraw(canvas);
14901
14902            // Step 6, draw decorations (scrollbars)
14903            onDrawScrollBars(canvas);
14904
14905            if (mOverlay != null && !mOverlay.isEmpty()) {
14906                mOverlay.getOverlayView().dispatchDraw(canvas);
14907            }
14908
14909            // we're done...
14910            return;
14911        }
14912
14913        /*
14914         * Here we do the full fledged routine...
14915         * (this is an uncommon case where speed matters less,
14916         * this is why we repeat some of the tests that have been
14917         * done above)
14918         */
14919
14920        boolean drawTop = false;
14921        boolean drawBottom = false;
14922        boolean drawLeft = false;
14923        boolean drawRight = false;
14924
14925        float topFadeStrength = 0.0f;
14926        float bottomFadeStrength = 0.0f;
14927        float leftFadeStrength = 0.0f;
14928        float rightFadeStrength = 0.0f;
14929
14930        // Step 2, save the canvas' layers
14931        int paddingLeft = mPaddingLeft;
14932
14933        final boolean offsetRequired = isPaddingOffsetRequired();
14934        if (offsetRequired) {
14935            paddingLeft += getLeftPaddingOffset();
14936        }
14937
14938        int left = mScrollX + paddingLeft;
14939        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
14940        int top = mScrollY + getFadeTop(offsetRequired);
14941        int bottom = top + getFadeHeight(offsetRequired);
14942
14943        if (offsetRequired) {
14944            right += getRightPaddingOffset();
14945            bottom += getBottomPaddingOffset();
14946        }
14947
14948        final ScrollabilityCache scrollabilityCache = mScrollCache;
14949        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
14950        int length = (int) fadeHeight;
14951
14952        // clip the fade length if top and bottom fades overlap
14953        // overlapping fades produce odd-looking artifacts
14954        if (verticalEdges && (top + length > bottom - length)) {
14955            length = (bottom - top) / 2;
14956        }
14957
14958        // also clip horizontal fades if necessary
14959        if (horizontalEdges && (left + length > right - length)) {
14960            length = (right - left) / 2;
14961        }
14962
14963        if (verticalEdges) {
14964            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
14965            drawTop = topFadeStrength * fadeHeight > 1.0f;
14966            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
14967            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
14968        }
14969
14970        if (horizontalEdges) {
14971            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
14972            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
14973            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
14974            drawRight = rightFadeStrength * fadeHeight > 1.0f;
14975        }
14976
14977        saveCount = canvas.getSaveCount();
14978
14979        int solidColor = getSolidColor();
14980        if (solidColor == 0) {
14981            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
14982
14983            if (drawTop) {
14984                canvas.saveLayer(left, top, right, top + length, null, flags);
14985            }
14986
14987            if (drawBottom) {
14988                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
14989            }
14990
14991            if (drawLeft) {
14992                canvas.saveLayer(left, top, left + length, bottom, null, flags);
14993            }
14994
14995            if (drawRight) {
14996                canvas.saveLayer(right - length, top, right, bottom, null, flags);
14997            }
14998        } else {
14999            scrollabilityCache.setFadeColor(solidColor);
15000        }
15001
15002        // Step 3, draw the content
15003        if (!dirtyOpaque) onDraw(canvas);
15004
15005        // Step 4, draw the children
15006        dispatchDraw(canvas);
15007
15008        // Step 5, draw the fade effect and restore layers
15009        final Paint p = scrollabilityCache.paint;
15010        final Matrix matrix = scrollabilityCache.matrix;
15011        final Shader fade = scrollabilityCache.shader;
15012
15013        if (drawTop) {
15014            matrix.setScale(1, fadeHeight * topFadeStrength);
15015            matrix.postTranslate(left, top);
15016            fade.setLocalMatrix(matrix);
15017            p.setShader(fade);
15018            canvas.drawRect(left, top, right, top + length, p);
15019        }
15020
15021        if (drawBottom) {
15022            matrix.setScale(1, fadeHeight * bottomFadeStrength);
15023            matrix.postRotate(180);
15024            matrix.postTranslate(left, bottom);
15025            fade.setLocalMatrix(matrix);
15026            p.setShader(fade);
15027            canvas.drawRect(left, bottom - length, right, bottom, p);
15028        }
15029
15030        if (drawLeft) {
15031            matrix.setScale(1, fadeHeight * leftFadeStrength);
15032            matrix.postRotate(-90);
15033            matrix.postTranslate(left, top);
15034            fade.setLocalMatrix(matrix);
15035            p.setShader(fade);
15036            canvas.drawRect(left, top, left + length, bottom, p);
15037        }
15038
15039        if (drawRight) {
15040            matrix.setScale(1, fadeHeight * rightFadeStrength);
15041            matrix.postRotate(90);
15042            matrix.postTranslate(right, top);
15043            fade.setLocalMatrix(matrix);
15044            p.setShader(fade);
15045            canvas.drawRect(right - length, top, right, bottom, p);
15046        }
15047
15048        canvas.restoreToCount(saveCount);
15049
15050        // Step 6, draw decorations (scrollbars)
15051        onDrawScrollBars(canvas);
15052
15053        if (mOverlay != null && !mOverlay.isEmpty()) {
15054            mOverlay.getOverlayView().dispatchDraw(canvas);
15055        }
15056    }
15057
15058    /**
15059     * Draws the accessibility focus rect onto the specified canvas.
15060     *
15061     * @param canvas Canvas on which to draw the focus rect
15062     */
15063    private void drawAccessibilityFocus(Canvas canvas) {
15064        if (mAttachInfo == null) {
15065            return;
15066        }
15067
15068        final Rect bounds = mAttachInfo.mTmpInvalRect;
15069        final ViewRootImpl viewRoot = getViewRootImpl();
15070        if (viewRoot == null || viewRoot.getAccessibilityFocusedHost() != this) {
15071            return;
15072        }
15073
15074        final AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
15075        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
15076            return;
15077        }
15078
15079        final Drawable drawable = viewRoot.getAccessibilityFocusedDrawable();
15080        if (drawable == null) {
15081            return;
15082        }
15083
15084        final AccessibilityNodeInfo virtualView = viewRoot.getAccessibilityFocusedVirtualView();
15085        if (virtualView != null) {
15086            virtualView.getBoundsInScreen(bounds);
15087            final int[] offset = mAttachInfo.mTmpLocation;
15088            getLocationOnScreen(offset);
15089            bounds.offset(-offset[0], -offset[1]);
15090        } else {
15091            bounds.set(0, 0, mRight - mLeft, mBottom - mTop);
15092        }
15093
15094        canvas.translate(mScrollX, mScrollY);
15095        drawable.setBounds(bounds);
15096        drawable.draw(canvas);
15097        canvas.translate(-mScrollX, -mScrollY);
15098    }
15099
15100    /**
15101     * Draws the background onto the specified canvas.
15102     *
15103     * @param canvas Canvas on which to draw the background
15104     */
15105    private void drawBackground(Canvas canvas) {
15106        final Drawable background = mBackground;
15107        if (background == null) {
15108            return;
15109        }
15110
15111        if (mBackgroundSizeChanged) {
15112            background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
15113            mBackgroundSizeChanged = false;
15114            invalidateOutline();
15115        }
15116
15117        // Attempt to use a display list if requested.
15118        if (canvas.isHardwareAccelerated() && mAttachInfo != null
15119                && mAttachInfo.mHardwareRenderer != null) {
15120            mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode);
15121
15122            final RenderNode displayList = mBackgroundRenderNode;
15123            if (displayList != null && displayList.isValid()) {
15124                setBackgroundDisplayListProperties(displayList);
15125                ((HardwareCanvas) canvas).drawRenderNode(displayList);
15126                return;
15127            }
15128        }
15129
15130        final int scrollX = mScrollX;
15131        final int scrollY = mScrollY;
15132        if ((scrollX | scrollY) == 0) {
15133            background.draw(canvas);
15134        } else {
15135            canvas.translate(scrollX, scrollY);
15136            background.draw(canvas);
15137            canvas.translate(-scrollX, -scrollY);
15138        }
15139    }
15140
15141    /**
15142     * Set up background drawable display list properties.
15143     *
15144     * @param displayList Valid display list for the background drawable
15145     */
15146    private void setBackgroundDisplayListProperties(RenderNode displayList) {
15147        displayList.setTranslationX(mScrollX);
15148        displayList.setTranslationY(mScrollY);
15149    }
15150
15151    /**
15152     * Creates a new display list or updates the existing display list for the
15153     * specified Drawable.
15154     *
15155     * @param drawable Drawable for which to create a display list
15156     * @param renderNode Existing RenderNode, or {@code null}
15157     * @return A valid display list for the specified drawable
15158     */
15159    private RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) {
15160        if (renderNode == null) {
15161            renderNode = RenderNode.create(drawable.getClass().getName(), this);
15162        }
15163
15164        final Rect bounds = drawable.getBounds();
15165        final int width = bounds.width();
15166        final int height = bounds.height();
15167        final HardwareCanvas canvas = renderNode.start(width, height);
15168        try {
15169            drawable.draw(canvas);
15170        } finally {
15171            renderNode.end(canvas);
15172        }
15173
15174        // Set up drawable properties that are view-independent.
15175        renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom);
15176        renderNode.setProjectBackwards(drawable.isProjected());
15177        renderNode.setProjectionReceiver(true);
15178        renderNode.setClipToBounds(false);
15179        return renderNode;
15180    }
15181
15182    /**
15183     * Returns the overlay for this view, creating it if it does not yet exist.
15184     * Adding drawables to the overlay will cause them to be displayed whenever
15185     * the view itself is redrawn. Objects in the overlay should be actively
15186     * managed: remove them when they should not be displayed anymore. The
15187     * overlay will always have the same size as its host view.
15188     *
15189     * <p>Note: Overlays do not currently work correctly with {@link
15190     * SurfaceView} or {@link TextureView}; contents in overlays for these
15191     * types of views may not display correctly.</p>
15192     *
15193     * @return The ViewOverlay object for this view.
15194     * @see ViewOverlay
15195     */
15196    public ViewOverlay getOverlay() {
15197        if (mOverlay == null) {
15198            mOverlay = new ViewOverlay(mContext, this);
15199        }
15200        return mOverlay;
15201    }
15202
15203    /**
15204     * Override this if your view is known to always be drawn on top of a solid color background,
15205     * and needs to draw fading edges. Returning a non-zero color enables the view system to
15206     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
15207     * should be set to 0xFF.
15208     *
15209     * @see #setVerticalFadingEdgeEnabled(boolean)
15210     * @see #setHorizontalFadingEdgeEnabled(boolean)
15211     *
15212     * @return The known solid color background for this view, or 0 if the color may vary
15213     */
15214    @ViewDebug.ExportedProperty(category = "drawing")
15215    public int getSolidColor() {
15216        return 0;
15217    }
15218
15219    /**
15220     * Build a human readable string representation of the specified view flags.
15221     *
15222     * @param flags the view flags to convert to a string
15223     * @return a String representing the supplied flags
15224     */
15225    private static String printFlags(int flags) {
15226        String output = "";
15227        int numFlags = 0;
15228        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
15229            output += "TAKES_FOCUS";
15230            numFlags++;
15231        }
15232
15233        switch (flags & VISIBILITY_MASK) {
15234        case INVISIBLE:
15235            if (numFlags > 0) {
15236                output += " ";
15237            }
15238            output += "INVISIBLE";
15239            // USELESS HERE numFlags++;
15240            break;
15241        case GONE:
15242            if (numFlags > 0) {
15243                output += " ";
15244            }
15245            output += "GONE";
15246            // USELESS HERE numFlags++;
15247            break;
15248        default:
15249            break;
15250        }
15251        return output;
15252    }
15253
15254    /**
15255     * Build a human readable string representation of the specified private
15256     * view flags.
15257     *
15258     * @param privateFlags the private view flags to convert to a string
15259     * @return a String representing the supplied flags
15260     */
15261    private static String printPrivateFlags(int privateFlags) {
15262        String output = "";
15263        int numFlags = 0;
15264
15265        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
15266            output += "WANTS_FOCUS";
15267            numFlags++;
15268        }
15269
15270        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
15271            if (numFlags > 0) {
15272                output += " ";
15273            }
15274            output += "FOCUSED";
15275            numFlags++;
15276        }
15277
15278        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
15279            if (numFlags > 0) {
15280                output += " ";
15281            }
15282            output += "SELECTED";
15283            numFlags++;
15284        }
15285
15286        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
15287            if (numFlags > 0) {
15288                output += " ";
15289            }
15290            output += "IS_ROOT_NAMESPACE";
15291            numFlags++;
15292        }
15293
15294        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
15295            if (numFlags > 0) {
15296                output += " ";
15297            }
15298            output += "HAS_BOUNDS";
15299            numFlags++;
15300        }
15301
15302        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
15303            if (numFlags > 0) {
15304                output += " ";
15305            }
15306            output += "DRAWN";
15307            // USELESS HERE numFlags++;
15308        }
15309        return output;
15310    }
15311
15312    /**
15313     * <p>Indicates whether or not this view's layout will be requested during
15314     * the next hierarchy layout pass.</p>
15315     *
15316     * @return true if the layout will be forced during next layout pass
15317     */
15318    public boolean isLayoutRequested() {
15319        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
15320    }
15321
15322    /**
15323     * Return true if o is a ViewGroup that is laying out using optical bounds.
15324     * @hide
15325     */
15326    public static boolean isLayoutModeOptical(Object o) {
15327        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
15328    }
15329
15330    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
15331        Insets parentInsets = mParent instanceof View ?
15332                ((View) mParent).getOpticalInsets() : Insets.NONE;
15333        Insets childInsets = getOpticalInsets();
15334        return setFrame(
15335                left   + parentInsets.left - childInsets.left,
15336                top    + parentInsets.top  - childInsets.top,
15337                right  + parentInsets.left + childInsets.right,
15338                bottom + parentInsets.top  + childInsets.bottom);
15339    }
15340
15341    /**
15342     * Assign a size and position to a view and all of its
15343     * descendants
15344     *
15345     * <p>This is the second phase of the layout mechanism.
15346     * (The first is measuring). In this phase, each parent calls
15347     * layout on all of its children to position them.
15348     * This is typically done using the child measurements
15349     * that were stored in the measure pass().</p>
15350     *
15351     * <p>Derived classes should not override this method.
15352     * Derived classes with children should override
15353     * onLayout. In that method, they should
15354     * call layout on each of their children.</p>
15355     *
15356     * @param l Left position, relative to parent
15357     * @param t Top position, relative to parent
15358     * @param r Right position, relative to parent
15359     * @param b Bottom position, relative to parent
15360     */
15361    @SuppressWarnings({"unchecked"})
15362    public void layout(int l, int t, int r, int b) {
15363        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
15364            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
15365            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
15366        }
15367
15368        int oldL = mLeft;
15369        int oldT = mTop;
15370        int oldB = mBottom;
15371        int oldR = mRight;
15372
15373        boolean changed = isLayoutModeOptical(mParent) ?
15374                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
15375
15376        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
15377            onLayout(changed, l, t, r, b);
15378            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
15379
15380            ListenerInfo li = mListenerInfo;
15381            if (li != null && li.mOnLayoutChangeListeners != null) {
15382                ArrayList<OnLayoutChangeListener> listenersCopy =
15383                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
15384                int numListeners = listenersCopy.size();
15385                for (int i = 0; i < numListeners; ++i) {
15386                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
15387                }
15388            }
15389        }
15390
15391        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
15392        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
15393    }
15394
15395    /**
15396     * Called from layout when this view should
15397     * assign a size and position to each of its children.
15398     *
15399     * Derived classes with children should override
15400     * this method and call layout on each of
15401     * their children.
15402     * @param changed This is a new size or position for this view
15403     * @param left Left position, relative to parent
15404     * @param top Top position, relative to parent
15405     * @param right Right position, relative to parent
15406     * @param bottom Bottom position, relative to parent
15407     */
15408    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
15409    }
15410
15411    /**
15412     * Assign a size and position to this view.
15413     *
15414     * This is called from layout.
15415     *
15416     * @param left Left position, relative to parent
15417     * @param top Top position, relative to parent
15418     * @param right Right position, relative to parent
15419     * @param bottom Bottom position, relative to parent
15420     * @return true if the new size and position are different than the
15421     *         previous ones
15422     * {@hide}
15423     */
15424    protected boolean setFrame(int left, int top, int right, int bottom) {
15425        boolean changed = false;
15426
15427        if (DBG) {
15428            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
15429                    + right + "," + bottom + ")");
15430        }
15431
15432        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
15433            changed = true;
15434
15435            // Remember our drawn bit
15436            int drawn = mPrivateFlags & PFLAG_DRAWN;
15437
15438            int oldWidth = mRight - mLeft;
15439            int oldHeight = mBottom - mTop;
15440            int newWidth = right - left;
15441            int newHeight = bottom - top;
15442            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
15443
15444            // Invalidate our old position
15445            invalidate(sizeChanged);
15446
15447            mLeft = left;
15448            mTop = top;
15449            mRight = right;
15450            mBottom = bottom;
15451            mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
15452
15453            mPrivateFlags |= PFLAG_HAS_BOUNDS;
15454
15455
15456            if (sizeChanged) {
15457                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
15458            }
15459
15460            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
15461                // If we are visible, force the DRAWN bit to on so that
15462                // this invalidate will go through (at least to our parent).
15463                // This is because someone may have invalidated this view
15464                // before this call to setFrame came in, thereby clearing
15465                // the DRAWN bit.
15466                mPrivateFlags |= PFLAG_DRAWN;
15467                invalidate(sizeChanged);
15468                // parent display list may need to be recreated based on a change in the bounds
15469                // of any child
15470                invalidateParentCaches();
15471            }
15472
15473            // Reset drawn bit to original value (invalidate turns it off)
15474            mPrivateFlags |= drawn;
15475
15476            mBackgroundSizeChanged = true;
15477
15478            notifySubtreeAccessibilityStateChangedIfNeeded();
15479        }
15480        return changed;
15481    }
15482
15483    private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
15484        onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
15485        if (mOverlay != null) {
15486            mOverlay.getOverlayView().setRight(newWidth);
15487            mOverlay.getOverlayView().setBottom(newHeight);
15488        }
15489        invalidateOutline();
15490    }
15491
15492    /**
15493     * Finalize inflating a view from XML.  This is called as the last phase
15494     * of inflation, after all child views have been added.
15495     *
15496     * <p>Even if the subclass overrides onFinishInflate, they should always be
15497     * sure to call the super method, so that we get called.
15498     */
15499    protected void onFinishInflate() {
15500    }
15501
15502    /**
15503     * Returns the resources associated with this view.
15504     *
15505     * @return Resources object.
15506     */
15507    public Resources getResources() {
15508        return mResources;
15509    }
15510
15511    /**
15512     * Invalidates the specified Drawable.
15513     *
15514     * @param drawable the drawable to invalidate
15515     */
15516    @Override
15517    public void invalidateDrawable(@NonNull Drawable drawable) {
15518        if (verifyDrawable(drawable)) {
15519            final Rect dirty = drawable.getDirtyBounds();
15520            final int scrollX = mScrollX;
15521            final int scrollY = mScrollY;
15522
15523            invalidate(dirty.left + scrollX, dirty.top + scrollY,
15524                    dirty.right + scrollX, dirty.bottom + scrollY);
15525
15526            invalidateOutline();
15527        }
15528    }
15529
15530    /**
15531     * Schedules an action on a drawable to occur at a specified time.
15532     *
15533     * @param who the recipient of the action
15534     * @param what the action to run on the drawable
15535     * @param when the time at which the action must occur. Uses the
15536     *        {@link SystemClock#uptimeMillis} timebase.
15537     */
15538    @Override
15539    public void scheduleDrawable(Drawable who, Runnable what, long when) {
15540        if (verifyDrawable(who) && what != null) {
15541            final long delay = when - SystemClock.uptimeMillis();
15542            if (mAttachInfo != null) {
15543                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
15544                        Choreographer.CALLBACK_ANIMATION, what, who,
15545                        Choreographer.subtractFrameDelay(delay));
15546            } else {
15547                ViewRootImpl.getRunQueue().postDelayed(what, delay);
15548            }
15549        }
15550    }
15551
15552    /**
15553     * Cancels a scheduled action on a drawable.
15554     *
15555     * @param who the recipient of the action
15556     * @param what the action to cancel
15557     */
15558    @Override
15559    public void unscheduleDrawable(Drawable who, Runnable what) {
15560        if (verifyDrawable(who) && what != null) {
15561            if (mAttachInfo != null) {
15562                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
15563                        Choreographer.CALLBACK_ANIMATION, what, who);
15564            }
15565            ViewRootImpl.getRunQueue().removeCallbacks(what);
15566        }
15567    }
15568
15569    /**
15570     * Unschedule any events associated with the given Drawable.  This can be
15571     * used when selecting a new Drawable into a view, so that the previous
15572     * one is completely unscheduled.
15573     *
15574     * @param who The Drawable to unschedule.
15575     *
15576     * @see #drawableStateChanged
15577     */
15578    public void unscheduleDrawable(Drawable who) {
15579        if (mAttachInfo != null && who != null) {
15580            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
15581                    Choreographer.CALLBACK_ANIMATION, null, who);
15582        }
15583    }
15584
15585    /**
15586     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
15587     * that the View directionality can and will be resolved before its Drawables.
15588     *
15589     * Will call {@link View#onResolveDrawables} when resolution is done.
15590     *
15591     * @hide
15592     */
15593    protected void resolveDrawables() {
15594        // Drawables resolution may need to happen before resolving the layout direction (which is
15595        // done only during the measure() call).
15596        // If the layout direction is not resolved yet, we cannot resolve the Drawables except in
15597        // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT.
15598        // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or
15599        // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout
15600        // direction to be resolved as its resolved value will be the same as its raw value.
15601        if (!isLayoutDirectionResolved() &&
15602                getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) {
15603            return;
15604        }
15605
15606        final int layoutDirection = isLayoutDirectionResolved() ?
15607                getLayoutDirection() : getRawLayoutDirection();
15608
15609        if (mBackground != null) {
15610            mBackground.setLayoutDirection(layoutDirection);
15611        }
15612        mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
15613        onResolveDrawables(layoutDirection);
15614    }
15615
15616    /**
15617     * Called when layout direction has been resolved.
15618     *
15619     * The default implementation does nothing.
15620     *
15621     * @param layoutDirection The resolved layout direction.
15622     *
15623     * @see #LAYOUT_DIRECTION_LTR
15624     * @see #LAYOUT_DIRECTION_RTL
15625     *
15626     * @hide
15627     */
15628    public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) {
15629    }
15630
15631    /**
15632     * @hide
15633     */
15634    protected void resetResolvedDrawables() {
15635        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
15636    }
15637
15638    private boolean isDrawablesResolved() {
15639        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
15640    }
15641
15642    /**
15643     * If your view subclass is displaying its own Drawable objects, it should
15644     * override this function and return true for any Drawable it is
15645     * displaying.  This allows animations for those drawables to be
15646     * scheduled.
15647     *
15648     * <p>Be sure to call through to the super class when overriding this
15649     * function.
15650     *
15651     * @param who The Drawable to verify.  Return true if it is one you are
15652     *            displaying, else return the result of calling through to the
15653     *            super class.
15654     *
15655     * @return boolean If true than the Drawable is being displayed in the
15656     *         view; else false and it is not allowed to animate.
15657     *
15658     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
15659     * @see #drawableStateChanged()
15660     */
15661    protected boolean verifyDrawable(Drawable who) {
15662        return who == mBackground;
15663    }
15664
15665    /**
15666     * This function is called whenever the state of the view changes in such
15667     * a way that it impacts the state of drawables being shown.
15668     * <p>
15669     * If the View has a StateListAnimator, it will also be called to run necessary state
15670     * change animations.
15671     * <p>
15672     * Be sure to call through to the superclass when overriding this function.
15673     *
15674     * @see Drawable#setState(int[])
15675     */
15676    protected void drawableStateChanged() {
15677        final Drawable d = mBackground;
15678        if (d != null && d.isStateful()) {
15679            d.setState(getDrawableState());
15680        }
15681
15682        if (mStateListAnimator != null) {
15683            mStateListAnimator.setState(getDrawableState());
15684        }
15685    }
15686
15687    /**
15688     * This function is called whenever the view hotspot changes and needs to
15689     * be propagated to drawables managed by the view.
15690     * <p>
15691     * Be sure to call through to the superclass when overriding this function.
15692     *
15693     * @param x hotspot x coordinate
15694     * @param y hotspot y coordinate
15695     */
15696    public void drawableHotspotChanged(float x, float y) {
15697        if (mBackground != null) {
15698            mBackground.setHotspot(x, y);
15699        }
15700    }
15701
15702    /**
15703     * Call this to force a view to update its drawable state. This will cause
15704     * drawableStateChanged to be called on this view. Views that are interested
15705     * in the new state should call getDrawableState.
15706     *
15707     * @see #drawableStateChanged
15708     * @see #getDrawableState
15709     */
15710    public void refreshDrawableState() {
15711        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
15712        drawableStateChanged();
15713
15714        ViewParent parent = mParent;
15715        if (parent != null) {
15716            parent.childDrawableStateChanged(this);
15717        }
15718    }
15719
15720    /**
15721     * Return an array of resource IDs of the drawable states representing the
15722     * current state of the view.
15723     *
15724     * @return The current drawable state
15725     *
15726     * @see Drawable#setState(int[])
15727     * @see #drawableStateChanged()
15728     * @see #onCreateDrawableState(int)
15729     */
15730    public final int[] getDrawableState() {
15731        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
15732            return mDrawableState;
15733        } else {
15734            mDrawableState = onCreateDrawableState(0);
15735            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
15736            return mDrawableState;
15737        }
15738    }
15739
15740    /**
15741     * Generate the new {@link android.graphics.drawable.Drawable} state for
15742     * this view. This is called by the view
15743     * system when the cached Drawable state is determined to be invalid.  To
15744     * retrieve the current state, you should use {@link #getDrawableState}.
15745     *
15746     * @param extraSpace if non-zero, this is the number of extra entries you
15747     * would like in the returned array in which you can place your own
15748     * states.
15749     *
15750     * @return Returns an array holding the current {@link Drawable} state of
15751     * the view.
15752     *
15753     * @see #mergeDrawableStates(int[], int[])
15754     */
15755    protected int[] onCreateDrawableState(int extraSpace) {
15756        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
15757                mParent instanceof View) {
15758            return ((View) mParent).onCreateDrawableState(extraSpace);
15759        }
15760
15761        int[] drawableState;
15762
15763        int privateFlags = mPrivateFlags;
15764
15765        int viewStateIndex = 0;
15766        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
15767        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
15768        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
15769        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
15770        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
15771        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
15772        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
15773                HardwareRenderer.isAvailable()) {
15774            // This is set if HW acceleration is requested, even if the current
15775            // process doesn't allow it.  This is just to allow app preview
15776            // windows to better match their app.
15777            viewStateIndex |= VIEW_STATE_ACCELERATED;
15778        }
15779        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
15780
15781        final int privateFlags2 = mPrivateFlags2;
15782        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
15783        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
15784
15785        drawableState = VIEW_STATE_SETS[viewStateIndex];
15786
15787        //noinspection ConstantIfStatement
15788        if (false) {
15789            Log.i("View", "drawableStateIndex=" + viewStateIndex);
15790            Log.i("View", toString()
15791                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
15792                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
15793                    + " fo=" + hasFocus()
15794                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
15795                    + " wf=" + hasWindowFocus()
15796                    + ": " + Arrays.toString(drawableState));
15797        }
15798
15799        if (extraSpace == 0) {
15800            return drawableState;
15801        }
15802
15803        final int[] fullState;
15804        if (drawableState != null) {
15805            fullState = new int[drawableState.length + extraSpace];
15806            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
15807        } else {
15808            fullState = new int[extraSpace];
15809        }
15810
15811        return fullState;
15812    }
15813
15814    /**
15815     * Merge your own state values in <var>additionalState</var> into the base
15816     * state values <var>baseState</var> that were returned by
15817     * {@link #onCreateDrawableState(int)}.
15818     *
15819     * @param baseState The base state values returned by
15820     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
15821     * own additional state values.
15822     *
15823     * @param additionalState The additional state values you would like
15824     * added to <var>baseState</var>; this array is not modified.
15825     *
15826     * @return As a convenience, the <var>baseState</var> array you originally
15827     * passed into the function is returned.
15828     *
15829     * @see #onCreateDrawableState(int)
15830     */
15831    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
15832        final int N = baseState.length;
15833        int i = N - 1;
15834        while (i >= 0 && baseState[i] == 0) {
15835            i--;
15836        }
15837        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
15838        return baseState;
15839    }
15840
15841    /**
15842     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
15843     * on all Drawable objects associated with this view.
15844     * <p>
15845     * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator
15846     * attached to this view.
15847     */
15848    public void jumpDrawablesToCurrentState() {
15849        if (mBackground != null) {
15850            mBackground.jumpToCurrentState();
15851        }
15852        if (mStateListAnimator != null) {
15853            mStateListAnimator.jumpToCurrentState();
15854        }
15855    }
15856
15857    /**
15858     * Sets the background color for this view.
15859     * @param color the color of the background
15860     */
15861    @RemotableViewMethod
15862    public void setBackgroundColor(int color) {
15863        if (mBackground instanceof ColorDrawable) {
15864            ((ColorDrawable) mBackground.mutate()).setColor(color);
15865            computeOpaqueFlags();
15866            mBackgroundResource = 0;
15867        } else {
15868            setBackground(new ColorDrawable(color));
15869        }
15870    }
15871
15872    /**
15873     * Set the background to a given resource. The resource should refer to
15874     * a Drawable object or 0 to remove the background.
15875     * @param resid The identifier of the resource.
15876     *
15877     * @attr ref android.R.styleable#View_background
15878     */
15879    @RemotableViewMethod
15880    public void setBackgroundResource(int resid) {
15881        if (resid != 0 && resid == mBackgroundResource) {
15882            return;
15883        }
15884
15885        Drawable d = null;
15886        if (resid != 0) {
15887            d = mContext.getDrawable(resid);
15888        }
15889        setBackground(d);
15890
15891        mBackgroundResource = resid;
15892    }
15893
15894    /**
15895     * Set the background to a given Drawable, or remove the background. If the
15896     * background has padding, this View's padding is set to the background's
15897     * padding. However, when a background is removed, this View's padding isn't
15898     * touched. If setting the padding is desired, please use
15899     * {@link #setPadding(int, int, int, int)}.
15900     *
15901     * @param background The Drawable to use as the background, or null to remove the
15902     *        background
15903     */
15904    public void setBackground(Drawable background) {
15905        //noinspection deprecation
15906        setBackgroundDrawable(background);
15907    }
15908
15909    /**
15910     * @deprecated use {@link #setBackground(Drawable)} instead
15911     */
15912    @Deprecated
15913    public void setBackgroundDrawable(Drawable background) {
15914        computeOpaqueFlags();
15915
15916        if (background == mBackground) {
15917            return;
15918        }
15919
15920        boolean requestLayout = false;
15921
15922        mBackgroundResource = 0;
15923
15924        /*
15925         * Regardless of whether we're setting a new background or not, we want
15926         * to clear the previous drawable.
15927         */
15928        if (mBackground != null) {
15929            mBackground.setCallback(null);
15930            unscheduleDrawable(mBackground);
15931        }
15932
15933        if (background != null) {
15934            Rect padding = sThreadLocal.get();
15935            if (padding == null) {
15936                padding = new Rect();
15937                sThreadLocal.set(padding);
15938            }
15939            resetResolvedDrawables();
15940            background.setLayoutDirection(getLayoutDirection());
15941            if (background.getPadding(padding)) {
15942                resetResolvedPadding();
15943                switch (background.getLayoutDirection()) {
15944                    case LAYOUT_DIRECTION_RTL:
15945                        mUserPaddingLeftInitial = padding.right;
15946                        mUserPaddingRightInitial = padding.left;
15947                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
15948                        break;
15949                    case LAYOUT_DIRECTION_LTR:
15950                    default:
15951                        mUserPaddingLeftInitial = padding.left;
15952                        mUserPaddingRightInitial = padding.right;
15953                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
15954                }
15955                mLeftPaddingDefined = false;
15956                mRightPaddingDefined = false;
15957            }
15958
15959            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
15960            // if it has a different minimum size, we should layout again
15961            if (mBackground == null
15962                    || mBackground.getMinimumHeight() != background.getMinimumHeight()
15963                    || mBackground.getMinimumWidth() != background.getMinimumWidth()) {
15964                requestLayout = true;
15965            }
15966
15967            background.setCallback(this);
15968            if (background.isStateful()) {
15969                background.setState(getDrawableState());
15970            }
15971            background.setVisible(getVisibility() == VISIBLE, false);
15972            mBackground = background;
15973
15974            applyBackgroundTint();
15975
15976            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
15977                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
15978                mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
15979                requestLayout = true;
15980            }
15981        } else {
15982            /* Remove the background */
15983            mBackground = null;
15984
15985            if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) {
15986                /*
15987                 * This view ONLY drew the background before and we're removing
15988                 * the background, so now it won't draw anything
15989                 * (hence we SKIP_DRAW)
15990                 */
15991                mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND;
15992                mPrivateFlags |= PFLAG_SKIP_DRAW;
15993            }
15994
15995            /*
15996             * When the background is set, we try to apply its padding to this
15997             * View. When the background is removed, we don't touch this View's
15998             * padding. This is noted in the Javadocs. Hence, we don't need to
15999             * requestLayout(), the invalidate() below is sufficient.
16000             */
16001
16002            // The old background's minimum size could have affected this
16003            // View's layout, so let's requestLayout
16004            requestLayout = true;
16005        }
16006
16007        computeOpaqueFlags();
16008
16009        if (requestLayout) {
16010            requestLayout();
16011        }
16012
16013        mBackgroundSizeChanged = true;
16014        invalidate(true);
16015    }
16016
16017    /**
16018     * Gets the background drawable
16019     *
16020     * @return The drawable used as the background for this view, if any.
16021     *
16022     * @see #setBackground(Drawable)
16023     *
16024     * @attr ref android.R.styleable#View_background
16025     */
16026    public Drawable getBackground() {
16027        return mBackground;
16028    }
16029
16030    /**
16031     * Applies a tint to the background drawable. Does not modify the current tint
16032     * mode, which is {@link PorterDuff.Mode#SRC_ATOP} by default.
16033     * <p>
16034     * Subsequent calls to {@link #setBackground(Drawable)} will automatically
16035     * mutate the drawable and apply the specified tint and tint mode using
16036     * {@link Drawable#setTintList(ColorStateList)}.
16037     *
16038     * @param tint the tint to apply, may be {@code null} to clear tint
16039     *
16040     * @attr ref android.R.styleable#View_backgroundTint
16041     * @see #getBackgroundTintList()
16042     * @see Drawable#setTintList(ColorStateList)
16043     */
16044    public void setBackgroundTintList(@Nullable ColorStateList tint) {
16045        mBackgroundTintList = tint;
16046        mHasBackgroundTint = true;
16047
16048        applyBackgroundTint();
16049    }
16050
16051    /**
16052     * @return the tint applied to the background drawable
16053     * @attr ref android.R.styleable#View_backgroundTint
16054     * @see #setBackgroundTintList(ColorStateList)
16055     */
16056    @Nullable
16057    public ColorStateList getBackgroundTintList() {
16058        return mBackgroundTintList;
16059    }
16060
16061    /**
16062     * Specifies the blending mode used to apply the tint specified by
16063     * {@link #setBackgroundTintList(ColorStateList)}} to the background drawable.
16064     * The default mode is {@link PorterDuff.Mode#SRC_ATOP}.
16065     *
16066     * @param tintMode the blending mode used to apply the tint, may be
16067     *                 {@code null} to clear tint
16068     * @attr ref android.R.styleable#View_backgroundTintMode
16069     * @see #getBackgroundTintMode()
16070     * @see Drawable#setTintMode(PorterDuff.Mode)
16071     */
16072    public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) {
16073        mBackgroundTintMode = tintMode;
16074
16075        applyBackgroundTint();
16076    }
16077
16078    /**
16079     * @return the blending mode used to apply the tint to the background drawable
16080     * @attr ref android.R.styleable#View_backgroundTintMode
16081     * @see #setBackgroundTintMode(PorterDuff.Mode)
16082     */
16083    @Nullable
16084    public PorterDuff.Mode getBackgroundTintMode() {
16085        return mBackgroundTintMode;
16086    }
16087
16088    private void applyBackgroundTint() {
16089        if (mBackground != null && mHasBackgroundTint) {
16090            mBackground = mBackground.mutate();
16091            mBackground.setTintList(mBackgroundTintList);
16092            mBackground.setTintMode(mBackgroundTintMode);
16093        }
16094    }
16095
16096    /**
16097     * Sets the padding. The view may add on the space required to display
16098     * the scrollbars, depending on the style and visibility of the scrollbars.
16099     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
16100     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
16101     * from the values set in this call.
16102     *
16103     * @attr ref android.R.styleable#View_padding
16104     * @attr ref android.R.styleable#View_paddingBottom
16105     * @attr ref android.R.styleable#View_paddingLeft
16106     * @attr ref android.R.styleable#View_paddingRight
16107     * @attr ref android.R.styleable#View_paddingTop
16108     * @param left the left padding in pixels
16109     * @param top the top padding in pixels
16110     * @param right the right padding in pixels
16111     * @param bottom the bottom padding in pixels
16112     */
16113    public void setPadding(int left, int top, int right, int bottom) {
16114        resetResolvedPadding();
16115
16116        mUserPaddingStart = UNDEFINED_PADDING;
16117        mUserPaddingEnd = UNDEFINED_PADDING;
16118
16119        mUserPaddingLeftInitial = left;
16120        mUserPaddingRightInitial = right;
16121
16122        mLeftPaddingDefined = true;
16123        mRightPaddingDefined = true;
16124
16125        internalSetPadding(left, top, right, bottom);
16126    }
16127
16128    /**
16129     * @hide
16130     */
16131    protected void internalSetPadding(int left, int top, int right, int bottom) {
16132        mUserPaddingLeft = left;
16133        mUserPaddingRight = right;
16134        mUserPaddingBottom = bottom;
16135
16136        final int viewFlags = mViewFlags;
16137        boolean changed = false;
16138
16139        // Common case is there are no scroll bars.
16140        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
16141            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
16142                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
16143                        ? 0 : getVerticalScrollbarWidth();
16144                switch (mVerticalScrollbarPosition) {
16145                    case SCROLLBAR_POSITION_DEFAULT:
16146                        if (isLayoutRtl()) {
16147                            left += offset;
16148                        } else {
16149                            right += offset;
16150                        }
16151                        break;
16152                    case SCROLLBAR_POSITION_RIGHT:
16153                        right += offset;
16154                        break;
16155                    case SCROLLBAR_POSITION_LEFT:
16156                        left += offset;
16157                        break;
16158                }
16159            }
16160            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
16161                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
16162                        ? 0 : getHorizontalScrollbarHeight();
16163            }
16164        }
16165
16166        if (mPaddingLeft != left) {
16167            changed = true;
16168            mPaddingLeft = left;
16169        }
16170        if (mPaddingTop != top) {
16171            changed = true;
16172            mPaddingTop = top;
16173        }
16174        if (mPaddingRight != right) {
16175            changed = true;
16176            mPaddingRight = right;
16177        }
16178        if (mPaddingBottom != bottom) {
16179            changed = true;
16180            mPaddingBottom = bottom;
16181        }
16182
16183        if (changed) {
16184            requestLayout();
16185        }
16186    }
16187
16188    /**
16189     * Sets the relative padding. The view may add on the space required to display
16190     * the scrollbars, depending on the style and visibility of the scrollbars.
16191     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
16192     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
16193     * from the values set in this call.
16194     *
16195     * @attr ref android.R.styleable#View_padding
16196     * @attr ref android.R.styleable#View_paddingBottom
16197     * @attr ref android.R.styleable#View_paddingStart
16198     * @attr ref android.R.styleable#View_paddingEnd
16199     * @attr ref android.R.styleable#View_paddingTop
16200     * @param start the start padding in pixels
16201     * @param top the top padding in pixels
16202     * @param end the end padding in pixels
16203     * @param bottom the bottom padding in pixels
16204     */
16205    public void setPaddingRelative(int start, int top, int end, int bottom) {
16206        resetResolvedPadding();
16207
16208        mUserPaddingStart = start;
16209        mUserPaddingEnd = end;
16210        mLeftPaddingDefined = true;
16211        mRightPaddingDefined = true;
16212
16213        switch(getLayoutDirection()) {
16214            case LAYOUT_DIRECTION_RTL:
16215                mUserPaddingLeftInitial = end;
16216                mUserPaddingRightInitial = start;
16217                internalSetPadding(end, top, start, bottom);
16218                break;
16219            case LAYOUT_DIRECTION_LTR:
16220            default:
16221                mUserPaddingLeftInitial = start;
16222                mUserPaddingRightInitial = end;
16223                internalSetPadding(start, top, end, bottom);
16224        }
16225    }
16226
16227    /**
16228     * Returns the top padding of this view.
16229     *
16230     * @return the top padding in pixels
16231     */
16232    public int getPaddingTop() {
16233        return mPaddingTop;
16234    }
16235
16236    /**
16237     * Returns the bottom padding of this view. If there are inset and enabled
16238     * scrollbars, this value may include the space required to display the
16239     * scrollbars as well.
16240     *
16241     * @return the bottom padding in pixels
16242     */
16243    public int getPaddingBottom() {
16244        return mPaddingBottom;
16245    }
16246
16247    /**
16248     * Returns the left padding of this view. If there are inset and enabled
16249     * scrollbars, this value may include the space required to display the
16250     * scrollbars as well.
16251     *
16252     * @return the left padding in pixels
16253     */
16254    public int getPaddingLeft() {
16255        if (!isPaddingResolved()) {
16256            resolvePadding();
16257        }
16258        return mPaddingLeft;
16259    }
16260
16261    /**
16262     * Returns the start padding of this view depending on its resolved layout direction.
16263     * If there are inset and enabled scrollbars, this value may include the space
16264     * required to display the scrollbars as well.
16265     *
16266     * @return the start padding in pixels
16267     */
16268    public int getPaddingStart() {
16269        if (!isPaddingResolved()) {
16270            resolvePadding();
16271        }
16272        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
16273                mPaddingRight : mPaddingLeft;
16274    }
16275
16276    /**
16277     * Returns the right padding of this view. If there are inset and enabled
16278     * scrollbars, this value may include the space required to display the
16279     * scrollbars as well.
16280     *
16281     * @return the right padding in pixels
16282     */
16283    public int getPaddingRight() {
16284        if (!isPaddingResolved()) {
16285            resolvePadding();
16286        }
16287        return mPaddingRight;
16288    }
16289
16290    /**
16291     * Returns the end padding of this view depending on its resolved layout direction.
16292     * If there are inset and enabled scrollbars, this value may include the space
16293     * required to display the scrollbars as well.
16294     *
16295     * @return the end padding in pixels
16296     */
16297    public int getPaddingEnd() {
16298        if (!isPaddingResolved()) {
16299            resolvePadding();
16300        }
16301        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
16302                mPaddingLeft : mPaddingRight;
16303    }
16304
16305    /**
16306     * Return if the padding as been set thru relative values
16307     * {@link #setPaddingRelative(int, int, int, int)} or thru
16308     * @attr ref android.R.styleable#View_paddingStart or
16309     * @attr ref android.R.styleable#View_paddingEnd
16310     *
16311     * @return true if the padding is relative or false if it is not.
16312     */
16313    public boolean isPaddingRelative() {
16314        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
16315    }
16316
16317    Insets computeOpticalInsets() {
16318        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
16319    }
16320
16321    /**
16322     * @hide
16323     */
16324    public void resetPaddingToInitialValues() {
16325        if (isRtlCompatibilityMode()) {
16326            mPaddingLeft = mUserPaddingLeftInitial;
16327            mPaddingRight = mUserPaddingRightInitial;
16328            return;
16329        }
16330        if (isLayoutRtl()) {
16331            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
16332            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
16333        } else {
16334            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
16335            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
16336        }
16337    }
16338
16339    /**
16340     * @hide
16341     */
16342    public Insets getOpticalInsets() {
16343        if (mLayoutInsets == null) {
16344            mLayoutInsets = computeOpticalInsets();
16345        }
16346        return mLayoutInsets;
16347    }
16348
16349    /**
16350     * Set this view's optical insets.
16351     *
16352     * <p>This method should be treated similarly to setMeasuredDimension and not as a general
16353     * property. Views that compute their own optical insets should call it as part of measurement.
16354     * This method does not request layout. If you are setting optical insets outside of
16355     * measure/layout itself you will want to call requestLayout() yourself.
16356     * </p>
16357     * @hide
16358     */
16359    public void setOpticalInsets(Insets insets) {
16360        mLayoutInsets = insets;
16361    }
16362
16363    /**
16364     * Changes the selection state of this view. A view can be selected or not.
16365     * Note that selection is not the same as focus. Views are typically
16366     * selected in the context of an AdapterView like ListView or GridView;
16367     * the selected view is the view that is highlighted.
16368     *
16369     * @param selected true if the view must be selected, false otherwise
16370     */
16371    public void setSelected(boolean selected) {
16372        //noinspection DoubleNegation
16373        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
16374            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
16375            if (!selected) resetPressedState();
16376            invalidate(true);
16377            refreshDrawableState();
16378            dispatchSetSelected(selected);
16379            notifyViewAccessibilityStateChangedIfNeeded(
16380                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
16381        }
16382    }
16383
16384    /**
16385     * Dispatch setSelected to all of this View's children.
16386     *
16387     * @see #setSelected(boolean)
16388     *
16389     * @param selected The new selected state
16390     */
16391    protected void dispatchSetSelected(boolean selected) {
16392    }
16393
16394    /**
16395     * Indicates the selection state of this view.
16396     *
16397     * @return true if the view is selected, false otherwise
16398     */
16399    @ViewDebug.ExportedProperty
16400    public boolean isSelected() {
16401        return (mPrivateFlags & PFLAG_SELECTED) != 0;
16402    }
16403
16404    /**
16405     * Changes the activated state of this view. A view can be activated or not.
16406     * Note that activation is not the same as selection.  Selection is
16407     * a transient property, representing the view (hierarchy) the user is
16408     * currently interacting with.  Activation is a longer-term state that the
16409     * user can move views in and out of.  For example, in a list view with
16410     * single or multiple selection enabled, the views in the current selection
16411     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
16412     * here.)  The activated state is propagated down to children of the view it
16413     * is set on.
16414     *
16415     * @param activated true if the view must be activated, false otherwise
16416     */
16417    public void setActivated(boolean activated) {
16418        //noinspection DoubleNegation
16419        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
16420            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
16421            invalidate(true);
16422            refreshDrawableState();
16423            dispatchSetActivated(activated);
16424        }
16425    }
16426
16427    /**
16428     * Dispatch setActivated to all of this View's children.
16429     *
16430     * @see #setActivated(boolean)
16431     *
16432     * @param activated The new activated state
16433     */
16434    protected void dispatchSetActivated(boolean activated) {
16435    }
16436
16437    /**
16438     * Indicates the activation state of this view.
16439     *
16440     * @return true if the view is activated, false otherwise
16441     */
16442    @ViewDebug.ExportedProperty
16443    public boolean isActivated() {
16444        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
16445    }
16446
16447    /**
16448     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
16449     * observer can be used to get notifications when global events, like
16450     * layout, happen.
16451     *
16452     * The returned ViewTreeObserver observer is not guaranteed to remain
16453     * valid for the lifetime of this View. If the caller of this method keeps
16454     * a long-lived reference to ViewTreeObserver, it should always check for
16455     * the return value of {@link ViewTreeObserver#isAlive()}.
16456     *
16457     * @return The ViewTreeObserver for this view's hierarchy.
16458     */
16459    public ViewTreeObserver getViewTreeObserver() {
16460        if (mAttachInfo != null) {
16461            return mAttachInfo.mTreeObserver;
16462        }
16463        if (mFloatingTreeObserver == null) {
16464            mFloatingTreeObserver = new ViewTreeObserver();
16465        }
16466        return mFloatingTreeObserver;
16467    }
16468
16469    /**
16470     * <p>Finds the topmost view in the current view hierarchy.</p>
16471     *
16472     * @return the topmost view containing this view
16473     */
16474    public View getRootView() {
16475        if (mAttachInfo != null) {
16476            final View v = mAttachInfo.mRootView;
16477            if (v != null) {
16478                return v;
16479            }
16480        }
16481
16482        View parent = this;
16483
16484        while (parent.mParent != null && parent.mParent instanceof View) {
16485            parent = (View) parent.mParent;
16486        }
16487
16488        return parent;
16489    }
16490
16491    /**
16492     * Transforms a motion event from view-local coordinates to on-screen
16493     * coordinates.
16494     *
16495     * @param ev the view-local motion event
16496     * @return false if the transformation could not be applied
16497     * @hide
16498     */
16499    public boolean toGlobalMotionEvent(MotionEvent ev) {
16500        final AttachInfo info = mAttachInfo;
16501        if (info == null) {
16502            return false;
16503        }
16504
16505        final Matrix m = info.mTmpMatrix;
16506        m.set(Matrix.IDENTITY_MATRIX);
16507        transformMatrixToGlobal(m);
16508        ev.transform(m);
16509        return true;
16510    }
16511
16512    /**
16513     * Transforms a motion event from on-screen coordinates to view-local
16514     * coordinates.
16515     *
16516     * @param ev the on-screen motion event
16517     * @return false if the transformation could not be applied
16518     * @hide
16519     */
16520    public boolean toLocalMotionEvent(MotionEvent ev) {
16521        final AttachInfo info = mAttachInfo;
16522        if (info == null) {
16523            return false;
16524        }
16525
16526        final Matrix m = info.mTmpMatrix;
16527        m.set(Matrix.IDENTITY_MATRIX);
16528        transformMatrixToLocal(m);
16529        ev.transform(m);
16530        return true;
16531    }
16532
16533    /**
16534     * Modifies the input matrix such that it maps view-local coordinates to
16535     * on-screen coordinates.
16536     *
16537     * @param m input matrix to modify
16538     * @hide
16539     */
16540    public void transformMatrixToGlobal(Matrix m) {
16541        final ViewParent parent = mParent;
16542        if (parent instanceof View) {
16543            final View vp = (View) parent;
16544            vp.transformMatrixToGlobal(m);
16545            m.preTranslate(-vp.mScrollX, -vp.mScrollY);
16546        } else if (parent instanceof ViewRootImpl) {
16547            final ViewRootImpl vr = (ViewRootImpl) parent;
16548            vr.transformMatrixToGlobal(m);
16549            m.preTranslate(0, -vr.mCurScrollY);
16550        }
16551
16552        m.preTranslate(mLeft, mTop);
16553
16554        if (!hasIdentityMatrix()) {
16555            m.preConcat(getMatrix());
16556        }
16557    }
16558
16559    /**
16560     * Modifies the input matrix such that it maps on-screen coordinates to
16561     * view-local coordinates.
16562     *
16563     * @param m input matrix to modify
16564     * @hide
16565     */
16566    public void transformMatrixToLocal(Matrix m) {
16567        final ViewParent parent = mParent;
16568        if (parent instanceof View) {
16569            final View vp = (View) parent;
16570            vp.transformMatrixToLocal(m);
16571            m.postTranslate(vp.mScrollX, vp.mScrollY);
16572        } else if (parent instanceof ViewRootImpl) {
16573            final ViewRootImpl vr = (ViewRootImpl) parent;
16574            vr.transformMatrixToLocal(m);
16575            m.postTranslate(0, vr.mCurScrollY);
16576        }
16577
16578        m.postTranslate(-mLeft, -mTop);
16579
16580        if (!hasIdentityMatrix()) {
16581            m.postConcat(getInverseMatrix());
16582        }
16583    }
16584
16585    /**
16586     * @hide
16587     */
16588    @ViewDebug.ExportedProperty(category = "layout", indexMapping = {
16589            @ViewDebug.IntToString(from = 0, to = "x"),
16590            @ViewDebug.IntToString(from = 1, to = "y")
16591    })
16592    public int[] getLocationOnScreen() {
16593        int[] location = new int[2];
16594        getLocationOnScreen(location);
16595        return location;
16596    }
16597
16598    /**
16599     * <p>Computes the coordinates of this view on the screen. The argument
16600     * must be an array of two integers. After the method returns, the array
16601     * contains the x and y location in that order.</p>
16602     *
16603     * @param location an array of two integers in which to hold the coordinates
16604     */
16605    public void getLocationOnScreen(int[] location) {
16606        getLocationInWindow(location);
16607
16608        final AttachInfo info = mAttachInfo;
16609        if (info != null) {
16610            location[0] += info.mWindowLeft;
16611            location[1] += info.mWindowTop;
16612        }
16613    }
16614
16615    /**
16616     * <p>Computes the coordinates of this view in its window. The argument
16617     * must be an array of two integers. After the method returns, the array
16618     * contains the x and y location in that order.</p>
16619     *
16620     * @param location an array of two integers in which to hold the coordinates
16621     */
16622    public void getLocationInWindow(int[] location) {
16623        if (location == null || location.length < 2) {
16624            throw new IllegalArgumentException("location must be an array of two integers");
16625        }
16626
16627        if (mAttachInfo == null) {
16628            // When the view is not attached to a window, this method does not make sense
16629            location[0] = location[1] = 0;
16630            return;
16631        }
16632
16633        float[] position = mAttachInfo.mTmpTransformLocation;
16634        position[0] = position[1] = 0.0f;
16635
16636        if (!hasIdentityMatrix()) {
16637            getMatrix().mapPoints(position);
16638        }
16639
16640        position[0] += mLeft;
16641        position[1] += mTop;
16642
16643        ViewParent viewParent = mParent;
16644        while (viewParent instanceof View) {
16645            final View view = (View) viewParent;
16646
16647            position[0] -= view.mScrollX;
16648            position[1] -= view.mScrollY;
16649
16650            if (!view.hasIdentityMatrix()) {
16651                view.getMatrix().mapPoints(position);
16652            }
16653
16654            position[0] += view.mLeft;
16655            position[1] += view.mTop;
16656
16657            viewParent = view.mParent;
16658         }
16659
16660        if (viewParent instanceof ViewRootImpl) {
16661            // *cough*
16662            final ViewRootImpl vr = (ViewRootImpl) viewParent;
16663            position[1] -= vr.mCurScrollY;
16664        }
16665
16666        location[0] = (int) (position[0] + 0.5f);
16667        location[1] = (int) (position[1] + 0.5f);
16668    }
16669
16670    /**
16671     * {@hide}
16672     * @param id the id of the view to be found
16673     * @return the view of the specified id, null if cannot be found
16674     */
16675    protected View findViewTraversal(int id) {
16676        if (id == mID) {
16677            return this;
16678        }
16679        return null;
16680    }
16681
16682    /**
16683     * {@hide}
16684     * @param tag the tag of the view to be found
16685     * @return the view of specified tag, null if cannot be found
16686     */
16687    protected View findViewWithTagTraversal(Object tag) {
16688        if (tag != null && tag.equals(mTag)) {
16689            return this;
16690        }
16691        return null;
16692    }
16693
16694    /**
16695     * {@hide}
16696     * @param predicate The predicate to evaluate.
16697     * @param childToSkip If not null, ignores this child during the recursive traversal.
16698     * @return The first view that matches the predicate or null.
16699     */
16700    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
16701        if (predicate.apply(this)) {
16702            return this;
16703        }
16704        return null;
16705    }
16706
16707    /**
16708     * Look for a child view with the given id.  If this view has the given
16709     * id, return this view.
16710     *
16711     * @param id The id to search for.
16712     * @return The view that has the given id in the hierarchy or null
16713     */
16714    public final View findViewById(int id) {
16715        if (id < 0) {
16716            return null;
16717        }
16718        return findViewTraversal(id);
16719    }
16720
16721    /**
16722     * Finds a view by its unuque and stable accessibility id.
16723     *
16724     * @param accessibilityId The searched accessibility id.
16725     * @return The found view.
16726     */
16727    final View findViewByAccessibilityId(int accessibilityId) {
16728        if (accessibilityId < 0) {
16729            return null;
16730        }
16731        return findViewByAccessibilityIdTraversal(accessibilityId);
16732    }
16733
16734    /**
16735     * Performs the traversal to find a view by its unuque and stable accessibility id.
16736     *
16737     * <strong>Note:</strong>This method does not stop at the root namespace
16738     * boundary since the user can touch the screen at an arbitrary location
16739     * potentially crossing the root namespace bounday which will send an
16740     * accessibility event to accessibility services and they should be able
16741     * to obtain the event source. Also accessibility ids are guaranteed to be
16742     * unique in the window.
16743     *
16744     * @param accessibilityId The accessibility id.
16745     * @return The found view.
16746     *
16747     * @hide
16748     */
16749    public View findViewByAccessibilityIdTraversal(int accessibilityId) {
16750        if (getAccessibilityViewId() == accessibilityId) {
16751            return this;
16752        }
16753        return null;
16754    }
16755
16756    /**
16757     * Look for a child view with the given tag.  If this view has the given
16758     * tag, return this view.
16759     *
16760     * @param tag The tag to search for, using "tag.equals(getTag())".
16761     * @return The View that has the given tag in the hierarchy or null
16762     */
16763    public final View findViewWithTag(Object tag) {
16764        if (tag == null) {
16765            return null;
16766        }
16767        return findViewWithTagTraversal(tag);
16768    }
16769
16770    /**
16771     * {@hide}
16772     * Look for a child view that matches the specified predicate.
16773     * If this view matches the predicate, return this view.
16774     *
16775     * @param predicate The predicate to evaluate.
16776     * @return The first view that matches the predicate or null.
16777     */
16778    public final View findViewByPredicate(Predicate<View> predicate) {
16779        return findViewByPredicateTraversal(predicate, null);
16780    }
16781
16782    /**
16783     * {@hide}
16784     * Look for a child view that matches the specified predicate,
16785     * starting with the specified view and its descendents and then
16786     * recusively searching the ancestors and siblings of that view
16787     * until this view is reached.
16788     *
16789     * This method is useful in cases where the predicate does not match
16790     * a single unique view (perhaps multiple views use the same id)
16791     * and we are trying to find the view that is "closest" in scope to the
16792     * starting view.
16793     *
16794     * @param start The view to start from.
16795     * @param predicate The predicate to evaluate.
16796     * @return The first view that matches the predicate or null.
16797     */
16798    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
16799        View childToSkip = null;
16800        for (;;) {
16801            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
16802            if (view != null || start == this) {
16803                return view;
16804            }
16805
16806            ViewParent parent = start.getParent();
16807            if (parent == null || !(parent instanceof View)) {
16808                return null;
16809            }
16810
16811            childToSkip = start;
16812            start = (View) parent;
16813        }
16814    }
16815
16816    /**
16817     * Sets the identifier for this view. The identifier does not have to be
16818     * unique in this view's hierarchy. The identifier should be a positive
16819     * number.
16820     *
16821     * @see #NO_ID
16822     * @see #getId()
16823     * @see #findViewById(int)
16824     *
16825     * @param id a number used to identify the view
16826     *
16827     * @attr ref android.R.styleable#View_id
16828     */
16829    public void setId(int id) {
16830        mID = id;
16831        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
16832            mID = generateViewId();
16833        }
16834    }
16835
16836    /**
16837     * {@hide}
16838     *
16839     * @param isRoot true if the view belongs to the root namespace, false
16840     *        otherwise
16841     */
16842    public void setIsRootNamespace(boolean isRoot) {
16843        if (isRoot) {
16844            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
16845        } else {
16846            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
16847        }
16848    }
16849
16850    /**
16851     * {@hide}
16852     *
16853     * @return true if the view belongs to the root namespace, false otherwise
16854     */
16855    public boolean isRootNamespace() {
16856        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
16857    }
16858
16859    /**
16860     * Returns this view's identifier.
16861     *
16862     * @return a positive integer used to identify the view or {@link #NO_ID}
16863     *         if the view has no ID
16864     *
16865     * @see #setId(int)
16866     * @see #findViewById(int)
16867     * @attr ref android.R.styleable#View_id
16868     */
16869    @ViewDebug.CapturedViewProperty
16870    public int getId() {
16871        return mID;
16872    }
16873
16874    /**
16875     * Returns this view's tag.
16876     *
16877     * @return the Object stored in this view as a tag, or {@code null} if not
16878     *         set
16879     *
16880     * @see #setTag(Object)
16881     * @see #getTag(int)
16882     */
16883    @ViewDebug.ExportedProperty
16884    public Object getTag() {
16885        return mTag;
16886    }
16887
16888    /**
16889     * Sets the tag associated with this view. A tag can be used to mark
16890     * a view in its hierarchy and does not have to be unique within the
16891     * hierarchy. Tags can also be used to store data within a view without
16892     * resorting to another data structure.
16893     *
16894     * @param tag an Object to tag the view with
16895     *
16896     * @see #getTag()
16897     * @see #setTag(int, Object)
16898     */
16899    public void setTag(final Object tag) {
16900        mTag = tag;
16901    }
16902
16903    /**
16904     * Returns the tag associated with this view and the specified key.
16905     *
16906     * @param key The key identifying the tag
16907     *
16908     * @return the Object stored in this view as a tag, or {@code null} if not
16909     *         set
16910     *
16911     * @see #setTag(int, Object)
16912     * @see #getTag()
16913     */
16914    public Object getTag(int key) {
16915        if (mKeyedTags != null) return mKeyedTags.get(key);
16916        return null;
16917    }
16918
16919    /**
16920     * Sets a tag associated with this view and a key. A tag can be used
16921     * to mark a view in its hierarchy and does not have to be unique within
16922     * the hierarchy. Tags can also be used to store data within a view
16923     * without resorting to another data structure.
16924     *
16925     * The specified key should be an id declared in the resources of the
16926     * application to ensure it is unique (see the <a
16927     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
16928     * Keys identified as belonging to
16929     * the Android framework or not associated with any package will cause
16930     * an {@link IllegalArgumentException} to be thrown.
16931     *
16932     * @param key The key identifying the tag
16933     * @param tag An Object to tag the view with
16934     *
16935     * @throws IllegalArgumentException If they specified key is not valid
16936     *
16937     * @see #setTag(Object)
16938     * @see #getTag(int)
16939     */
16940    public void setTag(int key, final Object tag) {
16941        // If the package id is 0x00 or 0x01, it's either an undefined package
16942        // or a framework id
16943        if ((key >>> 24) < 2) {
16944            throw new IllegalArgumentException("The key must be an application-specific "
16945                    + "resource id.");
16946        }
16947
16948        setKeyedTag(key, tag);
16949    }
16950
16951    /**
16952     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
16953     * framework id.
16954     *
16955     * @hide
16956     */
16957    public void setTagInternal(int key, Object tag) {
16958        if ((key >>> 24) != 0x1) {
16959            throw new IllegalArgumentException("The key must be a framework-specific "
16960                    + "resource id.");
16961        }
16962
16963        setKeyedTag(key, tag);
16964    }
16965
16966    private void setKeyedTag(int key, Object tag) {
16967        if (mKeyedTags == null) {
16968            mKeyedTags = new SparseArray<Object>(2);
16969        }
16970
16971        mKeyedTags.put(key, tag);
16972    }
16973
16974    /**
16975     * Prints information about this view in the log output, with the tag
16976     * {@link #VIEW_LOG_TAG}.
16977     *
16978     * @hide
16979     */
16980    public void debug() {
16981        debug(0);
16982    }
16983
16984    /**
16985     * Prints information about this view in the log output, with the tag
16986     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
16987     * indentation defined by the <code>depth</code>.
16988     *
16989     * @param depth the indentation level
16990     *
16991     * @hide
16992     */
16993    protected void debug(int depth) {
16994        String output = debugIndent(depth - 1);
16995
16996        output += "+ " + this;
16997        int id = getId();
16998        if (id != -1) {
16999            output += " (id=" + id + ")";
17000        }
17001        Object tag = getTag();
17002        if (tag != null) {
17003            output += " (tag=" + tag + ")";
17004        }
17005        Log.d(VIEW_LOG_TAG, output);
17006
17007        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
17008            output = debugIndent(depth) + " FOCUSED";
17009            Log.d(VIEW_LOG_TAG, output);
17010        }
17011
17012        output = debugIndent(depth);
17013        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
17014                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
17015                + "} ";
17016        Log.d(VIEW_LOG_TAG, output);
17017
17018        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
17019                || mPaddingBottom != 0) {
17020            output = debugIndent(depth);
17021            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
17022                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
17023            Log.d(VIEW_LOG_TAG, output);
17024        }
17025
17026        output = debugIndent(depth);
17027        output += "mMeasureWidth=" + mMeasuredWidth +
17028                " mMeasureHeight=" + mMeasuredHeight;
17029        Log.d(VIEW_LOG_TAG, output);
17030
17031        output = debugIndent(depth);
17032        if (mLayoutParams == null) {
17033            output += "BAD! no layout params";
17034        } else {
17035            output = mLayoutParams.debug(output);
17036        }
17037        Log.d(VIEW_LOG_TAG, output);
17038
17039        output = debugIndent(depth);
17040        output += "flags={";
17041        output += View.printFlags(mViewFlags);
17042        output += "}";
17043        Log.d(VIEW_LOG_TAG, output);
17044
17045        output = debugIndent(depth);
17046        output += "privateFlags={";
17047        output += View.printPrivateFlags(mPrivateFlags);
17048        output += "}";
17049        Log.d(VIEW_LOG_TAG, output);
17050    }
17051
17052    /**
17053     * Creates a string of whitespaces used for indentation.
17054     *
17055     * @param depth the indentation level
17056     * @return a String containing (depth * 2 + 3) * 2 white spaces
17057     *
17058     * @hide
17059     */
17060    protected static String debugIndent(int depth) {
17061        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
17062        for (int i = 0; i < (depth * 2) + 3; i++) {
17063            spaces.append(' ').append(' ');
17064        }
17065        return spaces.toString();
17066    }
17067
17068    /**
17069     * <p>Return the offset of the widget's text baseline from the widget's top
17070     * boundary. If this widget does not support baseline alignment, this
17071     * method returns -1. </p>
17072     *
17073     * @return the offset of the baseline within the widget's bounds or -1
17074     *         if baseline alignment is not supported
17075     */
17076    @ViewDebug.ExportedProperty(category = "layout")
17077    public int getBaseline() {
17078        return -1;
17079    }
17080
17081    /**
17082     * Returns whether the view hierarchy is currently undergoing a layout pass. This
17083     * information is useful to avoid situations such as calling {@link #requestLayout()} during
17084     * a layout pass.
17085     *
17086     * @return whether the view hierarchy is currently undergoing a layout pass
17087     */
17088    public boolean isInLayout() {
17089        ViewRootImpl viewRoot = getViewRootImpl();
17090        return (viewRoot != null && viewRoot.isInLayout());
17091    }
17092
17093    /**
17094     * Call this when something has changed which has invalidated the
17095     * layout of this view. This will schedule a layout pass of the view
17096     * tree. This should not be called while the view hierarchy is currently in a layout
17097     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
17098     * end of the current layout pass (and then layout will run again) or after the current
17099     * frame is drawn and the next layout occurs.
17100     *
17101     * <p>Subclasses which override this method should call the superclass method to
17102     * handle possible request-during-layout errors correctly.</p>
17103     */
17104    public void requestLayout() {
17105        if (mMeasureCache != null) mMeasureCache.clear();
17106
17107        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
17108            // Only trigger request-during-layout logic if this is the view requesting it,
17109            // not the views in its parent hierarchy
17110            ViewRootImpl viewRoot = getViewRootImpl();
17111            if (viewRoot != null && viewRoot.isInLayout()) {
17112                if (!viewRoot.requestLayoutDuringLayout(this)) {
17113                    return;
17114                }
17115            }
17116            mAttachInfo.mViewRequestingLayout = this;
17117        }
17118
17119        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
17120        mPrivateFlags |= PFLAG_INVALIDATED;
17121
17122        if (mParent != null && !mParent.isLayoutRequested()) {
17123            mParent.requestLayout();
17124        }
17125        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
17126            mAttachInfo.mViewRequestingLayout = null;
17127        }
17128    }
17129
17130    /**
17131     * Forces this view to be laid out during the next layout pass.
17132     * This method does not call requestLayout() or forceLayout()
17133     * on the parent.
17134     */
17135    public void forceLayout() {
17136        if (mMeasureCache != null) mMeasureCache.clear();
17137
17138        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
17139        mPrivateFlags |= PFLAG_INVALIDATED;
17140    }
17141
17142    /**
17143     * <p>
17144     * This is called to find out how big a view should be. The parent
17145     * supplies constraint information in the width and height parameters.
17146     * </p>
17147     *
17148     * <p>
17149     * The actual measurement work of a view is performed in
17150     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
17151     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
17152     * </p>
17153     *
17154     *
17155     * @param widthMeasureSpec Horizontal space requirements as imposed by the
17156     *        parent
17157     * @param heightMeasureSpec Vertical space requirements as imposed by the
17158     *        parent
17159     *
17160     * @see #onMeasure(int, int)
17161     */
17162    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
17163        boolean optical = isLayoutModeOptical(this);
17164        if (optical != isLayoutModeOptical(mParent)) {
17165            Insets insets = getOpticalInsets();
17166            int oWidth  = insets.left + insets.right;
17167            int oHeight = insets.top  + insets.bottom;
17168            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
17169            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
17170        }
17171
17172        // Suppress sign extension for the low bytes
17173        long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
17174        if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
17175
17176        if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ||
17177                widthMeasureSpec != mOldWidthMeasureSpec ||
17178                heightMeasureSpec != mOldHeightMeasureSpec) {
17179
17180            // first clears the measured dimension flag
17181            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
17182
17183            resolveRtlPropertiesIfNeeded();
17184
17185            int cacheIndex = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ? -1 :
17186                    mMeasureCache.indexOfKey(key);
17187            if (cacheIndex < 0 || sIgnoreMeasureCache) {
17188                // measure ourselves, this should set the measured dimension flag back
17189                onMeasure(widthMeasureSpec, heightMeasureSpec);
17190                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
17191            } else {
17192                long value = mMeasureCache.valueAt(cacheIndex);
17193                // Casting a long to int drops the high 32 bits, no mask needed
17194                setMeasuredDimensionRaw((int) (value >> 32), (int) value);
17195                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
17196            }
17197
17198            // flag not set, setMeasuredDimension() was not invoked, we raise
17199            // an exception to warn the developer
17200            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
17201                throw new IllegalStateException("onMeasure() did not set the"
17202                        + " measured dimension by calling"
17203                        + " setMeasuredDimension()");
17204            }
17205
17206            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
17207        }
17208
17209        mOldWidthMeasureSpec = widthMeasureSpec;
17210        mOldHeightMeasureSpec = heightMeasureSpec;
17211
17212        mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
17213                (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
17214    }
17215
17216    /**
17217     * <p>
17218     * Measure the view and its content to determine the measured width and the
17219     * measured height. This method is invoked by {@link #measure(int, int)} and
17220     * should be overriden by subclasses to provide accurate and efficient
17221     * measurement of their contents.
17222     * </p>
17223     *
17224     * <p>
17225     * <strong>CONTRACT:</strong> When overriding this method, you
17226     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
17227     * measured width and height of this view. Failure to do so will trigger an
17228     * <code>IllegalStateException</code>, thrown by
17229     * {@link #measure(int, int)}. Calling the superclass'
17230     * {@link #onMeasure(int, int)} is a valid use.
17231     * </p>
17232     *
17233     * <p>
17234     * The base class implementation of measure defaults to the background size,
17235     * unless a larger size is allowed by the MeasureSpec. Subclasses should
17236     * override {@link #onMeasure(int, int)} to provide better measurements of
17237     * their content.
17238     * </p>
17239     *
17240     * <p>
17241     * If this method is overridden, it is the subclass's responsibility to make
17242     * sure the measured height and width are at least the view's minimum height
17243     * and width ({@link #getSuggestedMinimumHeight()} and
17244     * {@link #getSuggestedMinimumWidth()}).
17245     * </p>
17246     *
17247     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
17248     *                         The requirements are encoded with
17249     *                         {@link android.view.View.MeasureSpec}.
17250     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
17251     *                         The requirements are encoded with
17252     *                         {@link android.view.View.MeasureSpec}.
17253     *
17254     * @see #getMeasuredWidth()
17255     * @see #getMeasuredHeight()
17256     * @see #setMeasuredDimension(int, int)
17257     * @see #getSuggestedMinimumHeight()
17258     * @see #getSuggestedMinimumWidth()
17259     * @see android.view.View.MeasureSpec#getMode(int)
17260     * @see android.view.View.MeasureSpec#getSize(int)
17261     */
17262    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
17263        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
17264                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
17265    }
17266
17267    /**
17268     * <p>This method must be called by {@link #onMeasure(int, int)} to store the
17269     * measured width and measured height. Failing to do so will trigger an
17270     * exception at measurement time.</p>
17271     *
17272     * @param measuredWidth The measured width of this view.  May be a complex
17273     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17274     * {@link #MEASURED_STATE_TOO_SMALL}.
17275     * @param measuredHeight The measured height of this view.  May be a complex
17276     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17277     * {@link #MEASURED_STATE_TOO_SMALL}.
17278     */
17279    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
17280        boolean optical = isLayoutModeOptical(this);
17281        if (optical != isLayoutModeOptical(mParent)) {
17282            Insets insets = getOpticalInsets();
17283            int opticalWidth  = insets.left + insets.right;
17284            int opticalHeight = insets.top  + insets.bottom;
17285
17286            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
17287            measuredHeight += optical ? opticalHeight : -opticalHeight;
17288        }
17289        setMeasuredDimensionRaw(measuredWidth, measuredHeight);
17290    }
17291
17292    /**
17293     * Sets the measured dimension without extra processing for things like optical bounds.
17294     * Useful for reapplying consistent values that have already been cooked with adjustments
17295     * for optical bounds, etc. such as those from the measurement cache.
17296     *
17297     * @param measuredWidth The measured width of this view.  May be a complex
17298     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17299     * {@link #MEASURED_STATE_TOO_SMALL}.
17300     * @param measuredHeight The measured height of this view.  May be a complex
17301     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17302     * {@link #MEASURED_STATE_TOO_SMALL}.
17303     */
17304    private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
17305        mMeasuredWidth = measuredWidth;
17306        mMeasuredHeight = measuredHeight;
17307
17308        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
17309    }
17310
17311    /**
17312     * Merge two states as returned by {@link #getMeasuredState()}.
17313     * @param curState The current state as returned from a view or the result
17314     * of combining multiple views.
17315     * @param newState The new view state to combine.
17316     * @return Returns a new integer reflecting the combination of the two
17317     * states.
17318     */
17319    public static int combineMeasuredStates(int curState, int newState) {
17320        return curState | newState;
17321    }
17322
17323    /**
17324     * Version of {@link #resolveSizeAndState(int, int, int)}
17325     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
17326     */
17327    public static int resolveSize(int size, int measureSpec) {
17328        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
17329    }
17330
17331    /**
17332     * Utility to reconcile a desired size and state, with constraints imposed
17333     * by a MeasureSpec.  Will take the desired size, unless a different size
17334     * is imposed by the constraints.  The returned value is a compound integer,
17335     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
17336     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
17337     * size is smaller than the size the view wants to be.
17338     *
17339     * @param size How big the view wants to be
17340     * @param measureSpec Constraints imposed by the parent
17341     * @return Size information bit mask as defined by
17342     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
17343     */
17344    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
17345        int result = size;
17346        int specMode = MeasureSpec.getMode(measureSpec);
17347        int specSize =  MeasureSpec.getSize(measureSpec);
17348        switch (specMode) {
17349        case MeasureSpec.UNSPECIFIED:
17350            result = size;
17351            break;
17352        case MeasureSpec.AT_MOST:
17353            if (specSize < size) {
17354                result = specSize | MEASURED_STATE_TOO_SMALL;
17355            } else {
17356                result = size;
17357            }
17358            break;
17359        case MeasureSpec.EXACTLY:
17360            result = specSize;
17361            break;
17362        }
17363        return result | (childMeasuredState&MEASURED_STATE_MASK);
17364    }
17365
17366    /**
17367     * Utility to return a default size. Uses the supplied size if the
17368     * MeasureSpec imposed no constraints. Will get larger if allowed
17369     * by the MeasureSpec.
17370     *
17371     * @param size Default size for this view
17372     * @param measureSpec Constraints imposed by the parent
17373     * @return The size this view should be.
17374     */
17375    public static int getDefaultSize(int size, int measureSpec) {
17376        int result = size;
17377        int specMode = MeasureSpec.getMode(measureSpec);
17378        int specSize = MeasureSpec.getSize(measureSpec);
17379
17380        switch (specMode) {
17381        case MeasureSpec.UNSPECIFIED:
17382            result = size;
17383            break;
17384        case MeasureSpec.AT_MOST:
17385        case MeasureSpec.EXACTLY:
17386            result = specSize;
17387            break;
17388        }
17389        return result;
17390    }
17391
17392    /**
17393     * Returns the suggested minimum height that the view should use. This
17394     * returns the maximum of the view's minimum height
17395     * and the background's minimum height
17396     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
17397     * <p>
17398     * When being used in {@link #onMeasure(int, int)}, the caller should still
17399     * ensure the returned height is within the requirements of the parent.
17400     *
17401     * @return The suggested minimum height of the view.
17402     */
17403    protected int getSuggestedMinimumHeight() {
17404        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
17405
17406    }
17407
17408    /**
17409     * Returns the suggested minimum width that the view should use. This
17410     * returns the maximum of the view's minimum width)
17411     * and the background's minimum width
17412     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
17413     * <p>
17414     * When being used in {@link #onMeasure(int, int)}, the caller should still
17415     * ensure the returned width is within the requirements of the parent.
17416     *
17417     * @return The suggested minimum width of the view.
17418     */
17419    protected int getSuggestedMinimumWidth() {
17420        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
17421    }
17422
17423    /**
17424     * Returns the minimum height of the view.
17425     *
17426     * @return the minimum height the view will try to be.
17427     *
17428     * @see #setMinimumHeight(int)
17429     *
17430     * @attr ref android.R.styleable#View_minHeight
17431     */
17432    public int getMinimumHeight() {
17433        return mMinHeight;
17434    }
17435
17436    /**
17437     * Sets the minimum height of the view. It is not guaranteed the view will
17438     * be able to achieve this minimum height (for example, if its parent layout
17439     * constrains it with less available height).
17440     *
17441     * @param minHeight The minimum height the view will try to be.
17442     *
17443     * @see #getMinimumHeight()
17444     *
17445     * @attr ref android.R.styleable#View_minHeight
17446     */
17447    public void setMinimumHeight(int minHeight) {
17448        mMinHeight = minHeight;
17449        requestLayout();
17450    }
17451
17452    /**
17453     * Returns the minimum width of the view.
17454     *
17455     * @return the minimum width the view will try to be.
17456     *
17457     * @see #setMinimumWidth(int)
17458     *
17459     * @attr ref android.R.styleable#View_minWidth
17460     */
17461    public int getMinimumWidth() {
17462        return mMinWidth;
17463    }
17464
17465    /**
17466     * Sets the minimum width of the view. It is not guaranteed the view will
17467     * be able to achieve this minimum width (for example, if its parent layout
17468     * constrains it with less available width).
17469     *
17470     * @param minWidth The minimum width the view will try to be.
17471     *
17472     * @see #getMinimumWidth()
17473     *
17474     * @attr ref android.R.styleable#View_minWidth
17475     */
17476    public void setMinimumWidth(int minWidth) {
17477        mMinWidth = minWidth;
17478        requestLayout();
17479
17480    }
17481
17482    /**
17483     * Get the animation currently associated with this view.
17484     *
17485     * @return The animation that is currently playing or
17486     *         scheduled to play for this view.
17487     */
17488    public Animation getAnimation() {
17489        return mCurrentAnimation;
17490    }
17491
17492    /**
17493     * Start the specified animation now.
17494     *
17495     * @param animation the animation to start now
17496     */
17497    public void startAnimation(Animation animation) {
17498        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
17499        setAnimation(animation);
17500        invalidateParentCaches();
17501        invalidate(true);
17502    }
17503
17504    /**
17505     * Cancels any animations for this view.
17506     */
17507    public void clearAnimation() {
17508        if (mCurrentAnimation != null) {
17509            mCurrentAnimation.detach();
17510        }
17511        mCurrentAnimation = null;
17512        invalidateParentIfNeeded();
17513    }
17514
17515    /**
17516     * Sets the next animation to play for this view.
17517     * If you want the animation to play immediately, use
17518     * {@link #startAnimation(android.view.animation.Animation)} instead.
17519     * This method provides allows fine-grained
17520     * control over the start time and invalidation, but you
17521     * must make sure that 1) the animation has a start time set, and
17522     * 2) the view's parent (which controls animations on its children)
17523     * will be invalidated when the animation is supposed to
17524     * start.
17525     *
17526     * @param animation The next animation, or null.
17527     */
17528    public void setAnimation(Animation animation) {
17529        mCurrentAnimation = animation;
17530
17531        if (animation != null) {
17532            // If the screen is off assume the animation start time is now instead of
17533            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
17534            // would cause the animation to start when the screen turns back on
17535            if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF
17536                    && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
17537                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
17538            }
17539            animation.reset();
17540        }
17541    }
17542
17543    /**
17544     * Invoked by a parent ViewGroup to notify the start of the animation
17545     * currently associated with this view. If you override this method,
17546     * always call super.onAnimationStart();
17547     *
17548     * @see #setAnimation(android.view.animation.Animation)
17549     * @see #getAnimation()
17550     */
17551    protected void onAnimationStart() {
17552        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
17553    }
17554
17555    /**
17556     * Invoked by a parent ViewGroup to notify the end of the animation
17557     * currently associated with this view. If you override this method,
17558     * always call super.onAnimationEnd();
17559     *
17560     * @see #setAnimation(android.view.animation.Animation)
17561     * @see #getAnimation()
17562     */
17563    protected void onAnimationEnd() {
17564        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
17565    }
17566
17567    /**
17568     * Invoked if there is a Transform that involves alpha. Subclass that can
17569     * draw themselves with the specified alpha should return true, and then
17570     * respect that alpha when their onDraw() is called. If this returns false
17571     * then the view may be redirected to draw into an offscreen buffer to
17572     * fulfill the request, which will look fine, but may be slower than if the
17573     * subclass handles it internally. The default implementation returns false.
17574     *
17575     * @param alpha The alpha (0..255) to apply to the view's drawing
17576     * @return true if the view can draw with the specified alpha.
17577     */
17578    protected boolean onSetAlpha(int alpha) {
17579        return false;
17580    }
17581
17582    /**
17583     * This is used by the RootView to perform an optimization when
17584     * the view hierarchy contains one or several SurfaceView.
17585     * SurfaceView is always considered transparent, but its children are not,
17586     * therefore all View objects remove themselves from the global transparent
17587     * region (passed as a parameter to this function).
17588     *
17589     * @param region The transparent region for this ViewAncestor (window).
17590     *
17591     * @return Returns true if the effective visibility of the view at this
17592     * point is opaque, regardless of the transparent region; returns false
17593     * if it is possible for underlying windows to be seen behind the view.
17594     *
17595     * {@hide}
17596     */
17597    public boolean gatherTransparentRegion(Region region) {
17598        final AttachInfo attachInfo = mAttachInfo;
17599        if (region != null && attachInfo != null) {
17600            final int pflags = mPrivateFlags;
17601            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
17602                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
17603                // remove it from the transparent region.
17604                final int[] location = attachInfo.mTransparentLocation;
17605                getLocationInWindow(location);
17606                region.op(location[0], location[1], location[0] + mRight - mLeft,
17607                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
17608            } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null &&
17609                    mBackground.getOpacity() != PixelFormat.TRANSPARENT) {
17610                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
17611                // exists, so we remove the background drawable's non-transparent
17612                // parts from this transparent region.
17613                applyDrawableToTransparentRegion(mBackground, region);
17614            }
17615        }
17616        return true;
17617    }
17618
17619    /**
17620     * Play a sound effect for this view.
17621     *
17622     * <p>The framework will play sound effects for some built in actions, such as
17623     * clicking, but you may wish to play these effects in your widget,
17624     * for instance, for internal navigation.
17625     *
17626     * <p>The sound effect will only be played if sound effects are enabled by the user, and
17627     * {@link #isSoundEffectsEnabled()} is true.
17628     *
17629     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
17630     */
17631    public void playSoundEffect(int soundConstant) {
17632        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
17633            return;
17634        }
17635        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
17636    }
17637
17638    /**
17639     * BZZZTT!!1!
17640     *
17641     * <p>Provide haptic feedback to the user for this view.
17642     *
17643     * <p>The framework will provide haptic feedback for some built in actions,
17644     * such as long presses, but you may wish to provide feedback for your
17645     * own widget.
17646     *
17647     * <p>The feedback will only be performed if
17648     * {@link #isHapticFeedbackEnabled()} is true.
17649     *
17650     * @param feedbackConstant One of the constants defined in
17651     * {@link HapticFeedbackConstants}
17652     */
17653    public boolean performHapticFeedback(int feedbackConstant) {
17654        return performHapticFeedback(feedbackConstant, 0);
17655    }
17656
17657    /**
17658     * BZZZTT!!1!
17659     *
17660     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
17661     *
17662     * @param feedbackConstant One of the constants defined in
17663     * {@link HapticFeedbackConstants}
17664     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
17665     */
17666    public boolean performHapticFeedback(int feedbackConstant, int flags) {
17667        if (mAttachInfo == null) {
17668            return false;
17669        }
17670        //noinspection SimplifiableIfStatement
17671        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
17672                && !isHapticFeedbackEnabled()) {
17673            return false;
17674        }
17675        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
17676                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
17677    }
17678
17679    /**
17680     * Request that the visibility of the status bar or other screen/window
17681     * decorations be changed.
17682     *
17683     * <p>This method is used to put the over device UI into temporary modes
17684     * where the user's attention is focused more on the application content,
17685     * by dimming or hiding surrounding system affordances.  This is typically
17686     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
17687     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
17688     * to be placed behind the action bar (and with these flags other system
17689     * affordances) so that smooth transitions between hiding and showing them
17690     * can be done.
17691     *
17692     * <p>Two representative examples of the use of system UI visibility is
17693     * implementing a content browsing application (like a magazine reader)
17694     * and a video playing application.
17695     *
17696     * <p>The first code shows a typical implementation of a View in a content
17697     * browsing application.  In this implementation, the application goes
17698     * into a content-oriented mode by hiding the status bar and action bar,
17699     * and putting the navigation elements into lights out mode.  The user can
17700     * then interact with content while in this mode.  Such an application should
17701     * provide an easy way for the user to toggle out of the mode (such as to
17702     * check information in the status bar or access notifications).  In the
17703     * implementation here, this is done simply by tapping on the content.
17704     *
17705     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
17706     *      content}
17707     *
17708     * <p>This second code sample shows a typical implementation of a View
17709     * in a video playing application.  In this situation, while the video is
17710     * playing the application would like to go into a complete full-screen mode,
17711     * to use as much of the display as possible for the video.  When in this state
17712     * the user can not interact with the application; the system intercepts
17713     * touching on the screen to pop the UI out of full screen mode.  See
17714     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
17715     *
17716     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
17717     *      content}
17718     *
17719     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
17720     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
17721     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
17722     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
17723     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
17724     */
17725    public void setSystemUiVisibility(int visibility) {
17726        if (visibility != mSystemUiVisibility) {
17727            mSystemUiVisibility = visibility;
17728            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
17729                mParent.recomputeViewAttributes(this);
17730            }
17731        }
17732    }
17733
17734    /**
17735     * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested.
17736     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
17737     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
17738     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
17739     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
17740     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
17741     */
17742    public int getSystemUiVisibility() {
17743        return mSystemUiVisibility;
17744    }
17745
17746    /**
17747     * Returns the current system UI visibility that is currently set for
17748     * the entire window.  This is the combination of the
17749     * {@link #setSystemUiVisibility(int)} values supplied by all of the
17750     * views in the window.
17751     */
17752    public int getWindowSystemUiVisibility() {
17753        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
17754    }
17755
17756    /**
17757     * Override to find out when the window's requested system UI visibility
17758     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
17759     * This is different from the callbacks received through
17760     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
17761     * in that this is only telling you about the local request of the window,
17762     * not the actual values applied by the system.
17763     */
17764    public void onWindowSystemUiVisibilityChanged(int visible) {
17765    }
17766
17767    /**
17768     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
17769     * the view hierarchy.
17770     */
17771    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
17772        onWindowSystemUiVisibilityChanged(visible);
17773    }
17774
17775    /**
17776     * Set a listener to receive callbacks when the visibility of the system bar changes.
17777     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
17778     */
17779    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
17780        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
17781        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
17782            mParent.recomputeViewAttributes(this);
17783        }
17784    }
17785
17786    /**
17787     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
17788     * the view hierarchy.
17789     */
17790    public void dispatchSystemUiVisibilityChanged(int visibility) {
17791        ListenerInfo li = mListenerInfo;
17792        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
17793            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
17794                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
17795        }
17796    }
17797
17798    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
17799        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
17800        if (val != mSystemUiVisibility) {
17801            setSystemUiVisibility(val);
17802            return true;
17803        }
17804        return false;
17805    }
17806
17807    /** @hide */
17808    public void setDisabledSystemUiVisibility(int flags) {
17809        if (mAttachInfo != null) {
17810            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
17811                mAttachInfo.mDisabledSystemUiVisibility = flags;
17812                if (mParent != null) {
17813                    mParent.recomputeViewAttributes(this);
17814                }
17815            }
17816        }
17817    }
17818
17819    /**
17820     * Creates an image that the system displays during the drag and drop
17821     * operation. This is called a &quot;drag shadow&quot;. The default implementation
17822     * for a DragShadowBuilder based on a View returns an image that has exactly the same
17823     * appearance as the given View. The default also positions the center of the drag shadow
17824     * directly under the touch point. If no View is provided (the constructor with no parameters
17825     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
17826     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
17827     * default is an invisible drag shadow.
17828     * <p>
17829     * You are not required to use the View you provide to the constructor as the basis of the
17830     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
17831     * anything you want as the drag shadow.
17832     * </p>
17833     * <p>
17834     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
17835     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
17836     *  size and position of the drag shadow. It uses this data to construct a
17837     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
17838     *  so that your application can draw the shadow image in the Canvas.
17839     * </p>
17840     *
17841     * <div class="special reference">
17842     * <h3>Developer Guides</h3>
17843     * <p>For a guide to implementing drag and drop features, read the
17844     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
17845     * </div>
17846     */
17847    public static class DragShadowBuilder {
17848        private final WeakReference<View> mView;
17849
17850        /**
17851         * Constructs a shadow image builder based on a View. By default, the resulting drag
17852         * shadow will have the same appearance and dimensions as the View, with the touch point
17853         * over the center of the View.
17854         * @param view A View. Any View in scope can be used.
17855         */
17856        public DragShadowBuilder(View view) {
17857            mView = new WeakReference<View>(view);
17858        }
17859
17860        /**
17861         * Construct a shadow builder object with no associated View.  This
17862         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
17863         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
17864         * to supply the drag shadow's dimensions and appearance without
17865         * reference to any View object. If they are not overridden, then the result is an
17866         * invisible drag shadow.
17867         */
17868        public DragShadowBuilder() {
17869            mView = new WeakReference<View>(null);
17870        }
17871
17872        /**
17873         * Returns the View object that had been passed to the
17874         * {@link #View.DragShadowBuilder(View)}
17875         * constructor.  If that View parameter was {@code null} or if the
17876         * {@link #View.DragShadowBuilder()}
17877         * constructor was used to instantiate the builder object, this method will return
17878         * null.
17879         *
17880         * @return The View object associate with this builder object.
17881         */
17882        @SuppressWarnings({"JavadocReference"})
17883        final public View getView() {
17884            return mView.get();
17885        }
17886
17887        /**
17888         * Provides the metrics for the shadow image. These include the dimensions of
17889         * the shadow image, and the point within that shadow that should
17890         * be centered under the touch location while dragging.
17891         * <p>
17892         * The default implementation sets the dimensions of the shadow to be the
17893         * same as the dimensions of the View itself and centers the shadow under
17894         * the touch point.
17895         * </p>
17896         *
17897         * @param shadowSize A {@link android.graphics.Point} containing the width and height
17898         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
17899         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
17900         * image.
17901         *
17902         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
17903         * shadow image that should be underneath the touch point during the drag and drop
17904         * operation. Your application must set {@link android.graphics.Point#x} to the
17905         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
17906         */
17907        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
17908            final View view = mView.get();
17909            if (view != null) {
17910                shadowSize.set(view.getWidth(), view.getHeight());
17911                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
17912            } else {
17913                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
17914            }
17915        }
17916
17917        /**
17918         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
17919         * based on the dimensions it received from the
17920         * {@link #onProvideShadowMetrics(Point, Point)} callback.
17921         *
17922         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
17923         */
17924        public void onDrawShadow(Canvas canvas) {
17925            final View view = mView.get();
17926            if (view != null) {
17927                view.draw(canvas);
17928            } else {
17929                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
17930            }
17931        }
17932    }
17933
17934    /**
17935     * Starts a drag and drop operation. When your application calls this method, it passes a
17936     * {@link android.view.View.DragShadowBuilder} object to the system. The
17937     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
17938     * to get metrics for the drag shadow, and then calls the object's
17939     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
17940     * <p>
17941     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
17942     *  drag events to all the View objects in your application that are currently visible. It does
17943     *  this either by calling the View object's drag listener (an implementation of
17944     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
17945     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
17946     *  Both are passed a {@link android.view.DragEvent} object that has a
17947     *  {@link android.view.DragEvent#getAction()} value of
17948     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
17949     * </p>
17950     * <p>
17951     * Your application can invoke startDrag() on any attached View object. The View object does not
17952     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
17953     * be related to the View the user selected for dragging.
17954     * </p>
17955     * @param data A {@link android.content.ClipData} object pointing to the data to be
17956     * transferred by the drag and drop operation.
17957     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
17958     * drag shadow.
17959     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
17960     * drop operation. This Object is put into every DragEvent object sent by the system during the
17961     * current drag.
17962     * <p>
17963     * myLocalState is a lightweight mechanism for the sending information from the dragged View
17964     * to the target Views. For example, it can contain flags that differentiate between a
17965     * a copy operation and a move operation.
17966     * </p>
17967     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
17968     * so the parameter should be set to 0.
17969     * @return {@code true} if the method completes successfully, or
17970     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
17971     * do a drag, and so no drag operation is in progress.
17972     */
17973    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
17974            Object myLocalState, int flags) {
17975        if (ViewDebug.DEBUG_DRAG) {
17976            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
17977        }
17978        boolean okay = false;
17979
17980        Point shadowSize = new Point();
17981        Point shadowTouchPoint = new Point();
17982        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
17983
17984        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
17985                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
17986            throw new IllegalStateException("Drag shadow dimensions must not be negative");
17987        }
17988
17989        if (ViewDebug.DEBUG_DRAG) {
17990            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
17991                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
17992        }
17993        Surface surface = new Surface();
17994        try {
17995            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
17996                    flags, shadowSize.x, shadowSize.y, surface);
17997            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
17998                    + " surface=" + surface);
17999            if (token != null) {
18000                Canvas canvas = surface.lockCanvas(null);
18001                try {
18002                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
18003                    shadowBuilder.onDrawShadow(canvas);
18004                } finally {
18005                    surface.unlockCanvasAndPost(canvas);
18006                }
18007
18008                final ViewRootImpl root = getViewRootImpl();
18009
18010                // Cache the local state object for delivery with DragEvents
18011                root.setLocalDragState(myLocalState);
18012
18013                // repurpose 'shadowSize' for the last touch point
18014                root.getLastTouchPoint(shadowSize);
18015
18016                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
18017                        shadowSize.x, shadowSize.y,
18018                        shadowTouchPoint.x, shadowTouchPoint.y, data);
18019                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
18020
18021                // Off and running!  Release our local surface instance; the drag
18022                // shadow surface is now managed by the system process.
18023                surface.release();
18024            }
18025        } catch (Exception e) {
18026            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
18027            surface.destroy();
18028        }
18029
18030        return okay;
18031    }
18032
18033    /**
18034     * Handles drag events sent by the system following a call to
18035     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
18036     *<p>
18037     * When the system calls this method, it passes a
18038     * {@link android.view.DragEvent} object. A call to
18039     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
18040     * in DragEvent. The method uses these to determine what is happening in the drag and drop
18041     * operation.
18042     * @param event The {@link android.view.DragEvent} sent by the system.
18043     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
18044     * in DragEvent, indicating the type of drag event represented by this object.
18045     * @return {@code true} if the method was successful, otherwise {@code false}.
18046     * <p>
18047     *  The method should return {@code true} in response to an action type of
18048     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
18049     *  operation.
18050     * </p>
18051     * <p>
18052     *  The method should also return {@code true} in response to an action type of
18053     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
18054     *  {@code false} if it didn't.
18055     * </p>
18056     */
18057    public boolean onDragEvent(DragEvent event) {
18058        return false;
18059    }
18060
18061    /**
18062     * Detects if this View is enabled and has a drag event listener.
18063     * If both are true, then it calls the drag event listener with the
18064     * {@link android.view.DragEvent} it received. If the drag event listener returns
18065     * {@code true}, then dispatchDragEvent() returns {@code true}.
18066     * <p>
18067     * For all other cases, the method calls the
18068     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
18069     * method and returns its result.
18070     * </p>
18071     * <p>
18072     * This ensures that a drag event is always consumed, even if the View does not have a drag
18073     * event listener. However, if the View has a listener and the listener returns true, then
18074     * onDragEvent() is not called.
18075     * </p>
18076     */
18077    public boolean dispatchDragEvent(DragEvent event) {
18078        ListenerInfo li = mListenerInfo;
18079        //noinspection SimplifiableIfStatement
18080        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
18081                && li.mOnDragListener.onDrag(this, event)) {
18082            return true;
18083        }
18084        return onDragEvent(event);
18085    }
18086
18087    boolean canAcceptDrag() {
18088        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
18089    }
18090
18091    /**
18092     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
18093     * it is ever exposed at all.
18094     * @hide
18095     */
18096    public void onCloseSystemDialogs(String reason) {
18097    }
18098
18099    /**
18100     * Given a Drawable whose bounds have been set to draw into this view,
18101     * update a Region being computed for
18102     * {@link #gatherTransparentRegion(android.graphics.Region)} so
18103     * that any non-transparent parts of the Drawable are removed from the
18104     * given transparent region.
18105     *
18106     * @param dr The Drawable whose transparency is to be applied to the region.
18107     * @param region A Region holding the current transparency information,
18108     * where any parts of the region that are set are considered to be
18109     * transparent.  On return, this region will be modified to have the
18110     * transparency information reduced by the corresponding parts of the
18111     * Drawable that are not transparent.
18112     * {@hide}
18113     */
18114    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
18115        if (DBG) {
18116            Log.i("View", "Getting transparent region for: " + this);
18117        }
18118        final Region r = dr.getTransparentRegion();
18119        final Rect db = dr.getBounds();
18120        final AttachInfo attachInfo = mAttachInfo;
18121        if (r != null && attachInfo != null) {
18122            final int w = getRight()-getLeft();
18123            final int h = getBottom()-getTop();
18124            if (db.left > 0) {
18125                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
18126                r.op(0, 0, db.left, h, Region.Op.UNION);
18127            }
18128            if (db.right < w) {
18129                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
18130                r.op(db.right, 0, w, h, Region.Op.UNION);
18131            }
18132            if (db.top > 0) {
18133                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
18134                r.op(0, 0, w, db.top, Region.Op.UNION);
18135            }
18136            if (db.bottom < h) {
18137                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
18138                r.op(0, db.bottom, w, h, Region.Op.UNION);
18139            }
18140            final int[] location = attachInfo.mTransparentLocation;
18141            getLocationInWindow(location);
18142            r.translate(location[0], location[1]);
18143            region.op(r, Region.Op.INTERSECT);
18144        } else {
18145            region.op(db, Region.Op.DIFFERENCE);
18146        }
18147    }
18148
18149    private void checkForLongClick(int delayOffset) {
18150        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
18151            mHasPerformedLongPress = false;
18152
18153            if (mPendingCheckForLongPress == null) {
18154                mPendingCheckForLongPress = new CheckForLongPress();
18155            }
18156            mPendingCheckForLongPress.rememberWindowAttachCount();
18157            postDelayed(mPendingCheckForLongPress,
18158                    ViewConfiguration.getLongPressTimeout() - delayOffset);
18159        }
18160    }
18161
18162    /**
18163     * Inflate a view from an XML resource.  This convenience method wraps the {@link
18164     * LayoutInflater} class, which provides a full range of options for view inflation.
18165     *
18166     * @param context The Context object for your activity or application.
18167     * @param resource The resource ID to inflate
18168     * @param root A view group that will be the parent.  Used to properly inflate the
18169     * layout_* parameters.
18170     * @see LayoutInflater
18171     */
18172    public static View inflate(Context context, int resource, ViewGroup root) {
18173        LayoutInflater factory = LayoutInflater.from(context);
18174        return factory.inflate(resource, root);
18175    }
18176
18177    /**
18178     * Scroll the view with standard behavior for scrolling beyond the normal
18179     * content boundaries. Views that call this method should override
18180     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
18181     * results of an over-scroll operation.
18182     *
18183     * Views can use this method to handle any touch or fling-based scrolling.
18184     *
18185     * @param deltaX Change in X in pixels
18186     * @param deltaY Change in Y in pixels
18187     * @param scrollX Current X scroll value in pixels before applying deltaX
18188     * @param scrollY Current Y scroll value in pixels before applying deltaY
18189     * @param scrollRangeX Maximum content scroll range along the X axis
18190     * @param scrollRangeY Maximum content scroll range along the Y axis
18191     * @param maxOverScrollX Number of pixels to overscroll by in either direction
18192     *          along the X axis.
18193     * @param maxOverScrollY Number of pixels to overscroll by in either direction
18194     *          along the Y axis.
18195     * @param isTouchEvent true if this scroll operation is the result of a touch event.
18196     * @return true if scrolling was clamped to an over-scroll boundary along either
18197     *          axis, false otherwise.
18198     */
18199    @SuppressWarnings({"UnusedParameters"})
18200    protected boolean overScrollBy(int deltaX, int deltaY,
18201            int scrollX, int scrollY,
18202            int scrollRangeX, int scrollRangeY,
18203            int maxOverScrollX, int maxOverScrollY,
18204            boolean isTouchEvent) {
18205        final int overScrollMode = mOverScrollMode;
18206        final boolean canScrollHorizontal =
18207                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
18208        final boolean canScrollVertical =
18209                computeVerticalScrollRange() > computeVerticalScrollExtent();
18210        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
18211                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
18212        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
18213                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
18214
18215        int newScrollX = scrollX + deltaX;
18216        if (!overScrollHorizontal) {
18217            maxOverScrollX = 0;
18218        }
18219
18220        int newScrollY = scrollY + deltaY;
18221        if (!overScrollVertical) {
18222            maxOverScrollY = 0;
18223        }
18224
18225        // Clamp values if at the limits and record
18226        final int left = -maxOverScrollX;
18227        final int right = maxOverScrollX + scrollRangeX;
18228        final int top = -maxOverScrollY;
18229        final int bottom = maxOverScrollY + scrollRangeY;
18230
18231        boolean clampedX = false;
18232        if (newScrollX > right) {
18233            newScrollX = right;
18234            clampedX = true;
18235        } else if (newScrollX < left) {
18236            newScrollX = left;
18237            clampedX = true;
18238        }
18239
18240        boolean clampedY = false;
18241        if (newScrollY > bottom) {
18242            newScrollY = bottom;
18243            clampedY = true;
18244        } else if (newScrollY < top) {
18245            newScrollY = top;
18246            clampedY = true;
18247        }
18248
18249        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
18250
18251        return clampedX || clampedY;
18252    }
18253
18254    /**
18255     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
18256     * respond to the results of an over-scroll operation.
18257     *
18258     * @param scrollX New X scroll value in pixels
18259     * @param scrollY New Y scroll value in pixels
18260     * @param clampedX True if scrollX was clamped to an over-scroll boundary
18261     * @param clampedY True if scrollY was clamped to an over-scroll boundary
18262     */
18263    protected void onOverScrolled(int scrollX, int scrollY,
18264            boolean clampedX, boolean clampedY) {
18265        // Intentionally empty.
18266    }
18267
18268    /**
18269     * Returns the over-scroll mode for this view. The result will be
18270     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
18271     * (allow over-scrolling only if the view content is larger than the container),
18272     * or {@link #OVER_SCROLL_NEVER}.
18273     *
18274     * @return This view's over-scroll mode.
18275     */
18276    public int getOverScrollMode() {
18277        return mOverScrollMode;
18278    }
18279
18280    /**
18281     * Set the over-scroll mode for this view. Valid over-scroll modes are
18282     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
18283     * (allow over-scrolling only if the view content is larger than the container),
18284     * or {@link #OVER_SCROLL_NEVER}.
18285     *
18286     * Setting the over-scroll mode of a view will have an effect only if the
18287     * view is capable of scrolling.
18288     *
18289     * @param overScrollMode The new over-scroll mode for this view.
18290     */
18291    public void setOverScrollMode(int overScrollMode) {
18292        if (overScrollMode != OVER_SCROLL_ALWAYS &&
18293                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
18294                overScrollMode != OVER_SCROLL_NEVER) {
18295            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
18296        }
18297        mOverScrollMode = overScrollMode;
18298    }
18299
18300    /**
18301     * Enable or disable nested scrolling for this view.
18302     *
18303     * <p>If this property is set to true the view will be permitted to initiate nested
18304     * scrolling operations with a compatible parent view in the current hierarchy. If this
18305     * view does not implement nested scrolling this will have no effect. Disabling nested scrolling
18306     * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping}
18307     * the nested scroll.</p>
18308     *
18309     * @param enabled true to enable nested scrolling, false to disable
18310     *
18311     * @see #isNestedScrollingEnabled()
18312     */
18313    public void setNestedScrollingEnabled(boolean enabled) {
18314        if (enabled) {
18315            mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED;
18316        } else {
18317            stopNestedScroll();
18318            mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED;
18319        }
18320    }
18321
18322    /**
18323     * Returns true if nested scrolling is enabled for this view.
18324     *
18325     * <p>If nested scrolling is enabled and this View class implementation supports it,
18326     * this view will act as a nested scrolling child view when applicable, forwarding data
18327     * about the scroll operation in progress to a compatible and cooperating nested scrolling
18328     * parent.</p>
18329     *
18330     * @return true if nested scrolling is enabled
18331     *
18332     * @see #setNestedScrollingEnabled(boolean)
18333     */
18334    public boolean isNestedScrollingEnabled() {
18335        return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) ==
18336                PFLAG3_NESTED_SCROLLING_ENABLED;
18337    }
18338
18339    /**
18340     * Begin a nestable scroll operation along the given axes.
18341     *
18342     * <p>A view starting a nested scroll promises to abide by the following contract:</p>
18343     *
18344     * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case
18345     * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}.
18346     * In the case of touch scrolling the nested scroll will be terminated automatically in
18347     * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}.
18348     * In the event of programmatic scrolling the caller must explicitly call
18349     * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p>
18350     *
18351     * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found.
18352     * If it returns false the caller may ignore the rest of this contract until the next scroll.
18353     * Calling startNestedScroll while a nested scroll is already in progress will return true.</p>
18354     *
18355     * <p>At each incremental step of the scroll the caller should invoke
18356     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll}
18357     * once it has calculated the requested scrolling delta. If it returns true the nested scrolling
18358     * parent at least partially consumed the scroll and the caller should adjust the amount it
18359     * scrolls by.</p>
18360     *
18361     * <p>After applying the remainder of the scroll delta the caller should invoke
18362     * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing
18363     * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat
18364     * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}.
18365     * </p>
18366     *
18367     * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or
18368     *             {@link #SCROLL_AXIS_VERTICAL}.
18369     * @return true if a cooperative parent was found and nested scrolling has been enabled for
18370     *         the current gesture.
18371     *
18372     * @see #stopNestedScroll()
18373     * @see #dispatchNestedPreScroll(int, int, int[], int[])
18374     * @see #dispatchNestedScroll(int, int, int, int, int[])
18375     */
18376    public boolean startNestedScroll(int axes) {
18377        if (hasNestedScrollingParent()) {
18378            // Already in progress
18379            return true;
18380        }
18381        if (isNestedScrollingEnabled()) {
18382            ViewParent p = getParent();
18383            View child = this;
18384            while (p != null) {
18385                try {
18386                    if (p.onStartNestedScroll(child, this, axes)) {
18387                        mNestedScrollingParent = p;
18388                        p.onNestedScrollAccepted(child, this, axes);
18389                        return true;
18390                    }
18391                } catch (AbstractMethodError e) {
18392                    Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " +
18393                            "method onStartNestedScroll", e);
18394                    // Allow the search upward to continue
18395                }
18396                if (p instanceof View) {
18397                    child = (View) p;
18398                }
18399                p = p.getParent();
18400            }
18401        }
18402        return false;
18403    }
18404
18405    /**
18406     * Stop a nested scroll in progress.
18407     *
18408     * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p>
18409     *
18410     * @see #startNestedScroll(int)
18411     */
18412    public void stopNestedScroll() {
18413        if (mNestedScrollingParent != null) {
18414            mNestedScrollingParent.onStopNestedScroll(this);
18415            mNestedScrollingParent = null;
18416        }
18417    }
18418
18419    /**
18420     * Returns true if this view has a nested scrolling parent.
18421     *
18422     * <p>The presence of a nested scrolling parent indicates that this view has initiated
18423     * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p>
18424     *
18425     * @return whether this view has a nested scrolling parent
18426     */
18427    public boolean hasNestedScrollingParent() {
18428        return mNestedScrollingParent != null;
18429    }
18430
18431    /**
18432     * Dispatch one step of a nested scroll in progress.
18433     *
18434     * <p>Implementations of views that support nested scrolling should call this to report
18435     * info about a scroll in progress to the current nested scrolling parent. If a nested scroll
18436     * is not currently in progress or nested scrolling is not
18437     * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p>
18438     *
18439     * <p>Compatible View implementations should also call
18440     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before
18441     * consuming a component of the scroll event themselves.</p>
18442     *
18443     * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step
18444     * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step
18445     * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view
18446     * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view
18447     * @param offsetInWindow Optional. If not null, on return this will contain the offset
18448     *                       in local view coordinates of this view from before this operation
18449     *                       to after it completes. View implementations may use this to adjust
18450     *                       expected input coordinate tracking.
18451     * @return true if the event was dispatched, false if it could not be dispatched.
18452     * @see #dispatchNestedPreScroll(int, int, int[], int[])
18453     */
18454    public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed,
18455            int dxUnconsumed, int dyUnconsumed, int[] offsetInWindow) {
18456        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
18457            if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) {
18458                int startX = 0;
18459                int startY = 0;
18460                if (offsetInWindow != null) {
18461                    getLocationInWindow(offsetInWindow);
18462                    startX = offsetInWindow[0];
18463                    startY = offsetInWindow[1];
18464                }
18465
18466                mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed,
18467                        dxUnconsumed, dyUnconsumed);
18468
18469                if (offsetInWindow != null) {
18470                    getLocationInWindow(offsetInWindow);
18471                    offsetInWindow[0] -= startX;
18472                    offsetInWindow[1] -= startY;
18473                }
18474                return true;
18475            } else if (offsetInWindow != null) {
18476                // No motion, no dispatch. Keep offsetInWindow up to date.
18477                offsetInWindow[0] = 0;
18478                offsetInWindow[1] = 0;
18479            }
18480        }
18481        return false;
18482    }
18483
18484    /**
18485     * Dispatch one step of a nested scroll in progress before this view consumes any portion of it.
18486     *
18487     * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch.
18488     * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested
18489     * scrolling operation to consume some or all of the scroll operation before the child view
18490     * consumes it.</p>
18491     *
18492     * @param dx Horizontal scroll distance in pixels
18493     * @param dy Vertical scroll distance in pixels
18494     * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx
18495     *                 and consumed[1] the consumed dy.
18496     * @param offsetInWindow Optional. If not null, on return this will contain the offset
18497     *                       in local view coordinates of this view from before this operation
18498     *                       to after it completes. View implementations may use this to adjust
18499     *                       expected input coordinate tracking.
18500     * @return true if the parent consumed some or all of the scroll delta
18501     * @see #dispatchNestedScroll(int, int, int, int, int[])
18502     */
18503    public boolean dispatchNestedPreScroll(int dx, int dy, int[] consumed, int[] offsetInWindow) {
18504        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
18505            if (dx != 0 || dy != 0) {
18506                int startX = 0;
18507                int startY = 0;
18508                if (offsetInWindow != null) {
18509                    getLocationInWindow(offsetInWindow);
18510                    startX = offsetInWindow[0];
18511                    startY = offsetInWindow[1];
18512                }
18513
18514                if (consumed == null) {
18515                    if (mTempNestedScrollConsumed == null) {
18516                        mTempNestedScrollConsumed = new int[2];
18517                    }
18518                    consumed = mTempNestedScrollConsumed;
18519                }
18520                consumed[0] = 0;
18521                consumed[1] = 0;
18522                mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed);
18523
18524                if (offsetInWindow != null) {
18525                    getLocationInWindow(offsetInWindow);
18526                    offsetInWindow[0] -= startX;
18527                    offsetInWindow[1] -= startY;
18528                }
18529                return consumed[0] != 0 || consumed[1] != 0;
18530            } else if (offsetInWindow != null) {
18531                offsetInWindow[0] = 0;
18532                offsetInWindow[1] = 0;
18533            }
18534        }
18535        return false;
18536    }
18537
18538    /**
18539     * Dispatch a fling to a nested scrolling parent.
18540     *
18541     * <p>This method should be used to indicate that a nested scrolling child has detected
18542     * suitable conditions for a fling. Generally this means that a touch scroll has ended with a
18543     * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds
18544     * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity}
18545     * along a scrollable axis.</p>
18546     *
18547     * <p>If a nested scrolling child view would normally fling but it is at the edge of
18548     * its own content, it can use this method to delegate the fling to its nested scrolling
18549     * parent instead. The parent may optionally consume the fling or observe a child fling.</p>
18550     *
18551     * @param velocityX Horizontal fling velocity in pixels per second
18552     * @param velocityY Vertical fling velocity in pixels per second
18553     * @param consumed true if the child consumed the fling, false otherwise
18554     * @return true if the nested scrolling parent consumed or otherwise reacted to the fling
18555     */
18556    public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) {
18557        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
18558            return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed);
18559        }
18560        return false;
18561    }
18562
18563    /**
18564     * Dispatch a fling to a nested scrolling parent before it is processed by this view.
18565     *
18566     * <p>Nested pre-fling events are to nested fling events what touch intercept is to touch
18567     * and what nested pre-scroll is to nested scroll. <code>dispatchNestedPreFling</code>
18568     * offsets an opportunity for the parent view in a nested fling to fully consume the fling
18569     * before the child view consumes it. If this method returns <code>true</code>, a nested
18570     * parent view consumed the fling and this view should not scroll as a result.</p>
18571     *
18572     * <p>For a better user experience, only one view in a nested scrolling chain should consume
18573     * the fling at a time. If a parent view consumed the fling this method will return false.
18574     * Custom view implementations should account for this in two ways:</p>
18575     *
18576     * <ul>
18577     *     <li>If a custom view is paged and needs to settle to a fixed page-point, do not
18578     *     call <code>dispatchNestedPreFling</code>; consume the fling and settle to a valid
18579     *     position regardless.</li>
18580     *     <li>If a nested parent does consume the fling, this view should not scroll at all,
18581     *     even to settle back to a valid idle position.</li>
18582     * </ul>
18583     *
18584     * <p>Views should also not offer fling velocities to nested parent views along an axis
18585     * where scrolling is not currently supported; a {@link android.widget.ScrollView ScrollView}
18586     * should not offer a horizontal fling velocity to its parents since scrolling along that
18587     * axis is not permitted and carrying velocity along that motion does not make sense.</p>
18588     *
18589     * @param velocityX Horizontal fling velocity in pixels per second
18590     * @param velocityY Vertical fling velocity in pixels per second
18591     * @return true if a nested scrolling parent consumed the fling
18592     */
18593    public boolean dispatchNestedPreFling(float velocityX, float velocityY) {
18594        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
18595            return mNestedScrollingParent.onNestedPreFling(this, velocityX, velocityY);
18596        }
18597        return false;
18598    }
18599
18600    /**
18601     * Gets a scale factor that determines the distance the view should scroll
18602     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
18603     * @return The vertical scroll scale factor.
18604     * @hide
18605     */
18606    protected float getVerticalScrollFactor() {
18607        if (mVerticalScrollFactor == 0) {
18608            TypedValue outValue = new TypedValue();
18609            if (!mContext.getTheme().resolveAttribute(
18610                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
18611                throw new IllegalStateException(
18612                        "Expected theme to define listPreferredItemHeight.");
18613            }
18614            mVerticalScrollFactor = outValue.getDimension(
18615                    mContext.getResources().getDisplayMetrics());
18616        }
18617        return mVerticalScrollFactor;
18618    }
18619
18620    /**
18621     * Gets a scale factor that determines the distance the view should scroll
18622     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
18623     * @return The horizontal scroll scale factor.
18624     * @hide
18625     */
18626    protected float getHorizontalScrollFactor() {
18627        // TODO: Should use something else.
18628        return getVerticalScrollFactor();
18629    }
18630
18631    /**
18632     * Return the value specifying the text direction or policy that was set with
18633     * {@link #setTextDirection(int)}.
18634     *
18635     * @return the defined text direction. It can be one of:
18636     *
18637     * {@link #TEXT_DIRECTION_INHERIT},
18638     * {@link #TEXT_DIRECTION_FIRST_STRONG}
18639     * {@link #TEXT_DIRECTION_ANY_RTL},
18640     * {@link #TEXT_DIRECTION_LTR},
18641     * {@link #TEXT_DIRECTION_RTL},
18642     * {@link #TEXT_DIRECTION_LOCALE}
18643     *
18644     * @attr ref android.R.styleable#View_textDirection
18645     *
18646     * @hide
18647     */
18648    @ViewDebug.ExportedProperty(category = "text", mapping = {
18649            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
18650            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
18651            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
18652            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
18653            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
18654            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
18655    })
18656    public int getRawTextDirection() {
18657        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
18658    }
18659
18660    /**
18661     * Set the text direction.
18662     *
18663     * @param textDirection the direction to set. Should be one of:
18664     *
18665     * {@link #TEXT_DIRECTION_INHERIT},
18666     * {@link #TEXT_DIRECTION_FIRST_STRONG}
18667     * {@link #TEXT_DIRECTION_ANY_RTL},
18668     * {@link #TEXT_DIRECTION_LTR},
18669     * {@link #TEXT_DIRECTION_RTL},
18670     * {@link #TEXT_DIRECTION_LOCALE}
18671     *
18672     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
18673     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
18674     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
18675     *
18676     * @attr ref android.R.styleable#View_textDirection
18677     */
18678    public void setTextDirection(int textDirection) {
18679        if (getRawTextDirection() != textDirection) {
18680            // Reset the current text direction and the resolved one
18681            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
18682            resetResolvedTextDirection();
18683            // Set the new text direction
18684            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
18685            // Do resolution
18686            resolveTextDirection();
18687            // Notify change
18688            onRtlPropertiesChanged(getLayoutDirection());
18689            // Refresh
18690            requestLayout();
18691            invalidate(true);
18692        }
18693    }
18694
18695    /**
18696     * Return the resolved text direction.
18697     *
18698     * @return the resolved text direction. Returns one of:
18699     *
18700     * {@link #TEXT_DIRECTION_FIRST_STRONG}
18701     * {@link #TEXT_DIRECTION_ANY_RTL},
18702     * {@link #TEXT_DIRECTION_LTR},
18703     * {@link #TEXT_DIRECTION_RTL},
18704     * {@link #TEXT_DIRECTION_LOCALE}
18705     *
18706     * @attr ref android.R.styleable#View_textDirection
18707     */
18708    @ViewDebug.ExportedProperty(category = "text", mapping = {
18709            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
18710            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
18711            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
18712            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
18713            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
18714            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
18715    })
18716    public int getTextDirection() {
18717        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
18718    }
18719
18720    /**
18721     * Resolve the text direction.
18722     *
18723     * @return true if resolution has been done, false otherwise.
18724     *
18725     * @hide
18726     */
18727    public boolean resolveTextDirection() {
18728        // Reset any previous text direction resolution
18729        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
18730
18731        if (hasRtlSupport()) {
18732            // Set resolved text direction flag depending on text direction flag
18733            final int textDirection = getRawTextDirection();
18734            switch(textDirection) {
18735                case TEXT_DIRECTION_INHERIT:
18736                    if (!canResolveTextDirection()) {
18737                        // We cannot do the resolution if there is no parent, so use the default one
18738                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18739                        // Resolution will need to happen again later
18740                        return false;
18741                    }
18742
18743                    // Parent has not yet resolved, so we still return the default
18744                    try {
18745                        if (!mParent.isTextDirectionResolved()) {
18746                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18747                            // Resolution will need to happen again later
18748                            return false;
18749                        }
18750                    } catch (AbstractMethodError e) {
18751                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18752                                " does not fully implement ViewParent", e);
18753                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED |
18754                                PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18755                        return true;
18756                    }
18757
18758                    // Set current resolved direction to the same value as the parent's one
18759                    int parentResolvedDirection;
18760                    try {
18761                        parentResolvedDirection = mParent.getTextDirection();
18762                    } catch (AbstractMethodError e) {
18763                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18764                                " does not fully implement ViewParent", e);
18765                        parentResolvedDirection = TEXT_DIRECTION_LTR;
18766                    }
18767                    switch (parentResolvedDirection) {
18768                        case TEXT_DIRECTION_FIRST_STRONG:
18769                        case TEXT_DIRECTION_ANY_RTL:
18770                        case TEXT_DIRECTION_LTR:
18771                        case TEXT_DIRECTION_RTL:
18772                        case TEXT_DIRECTION_LOCALE:
18773                            mPrivateFlags2 |=
18774                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
18775                            break;
18776                        default:
18777                            // Default resolved direction is "first strong" heuristic
18778                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18779                    }
18780                    break;
18781                case TEXT_DIRECTION_FIRST_STRONG:
18782                case TEXT_DIRECTION_ANY_RTL:
18783                case TEXT_DIRECTION_LTR:
18784                case TEXT_DIRECTION_RTL:
18785                case TEXT_DIRECTION_LOCALE:
18786                    // Resolved direction is the same as text direction
18787                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
18788                    break;
18789                default:
18790                    // Default resolved direction is "first strong" heuristic
18791                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18792            }
18793        } else {
18794            // Default resolved direction is "first strong" heuristic
18795            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18796        }
18797
18798        // Set to resolved
18799        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
18800        return true;
18801    }
18802
18803    /**
18804     * Check if text direction resolution can be done.
18805     *
18806     * @return true if text direction resolution can be done otherwise return false.
18807     */
18808    public boolean canResolveTextDirection() {
18809        switch (getRawTextDirection()) {
18810            case TEXT_DIRECTION_INHERIT:
18811                if (mParent != null) {
18812                    try {
18813                        return mParent.canResolveTextDirection();
18814                    } catch (AbstractMethodError e) {
18815                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18816                                " does not fully implement ViewParent", e);
18817                    }
18818                }
18819                return false;
18820
18821            default:
18822                return true;
18823        }
18824    }
18825
18826    /**
18827     * Reset resolved text direction. Text direction will be resolved during a call to
18828     * {@link #onMeasure(int, int)}.
18829     *
18830     * @hide
18831     */
18832    public void resetResolvedTextDirection() {
18833        // Reset any previous text direction resolution
18834        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
18835        // Set to default value
18836        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18837    }
18838
18839    /**
18840     * @return true if text direction is inherited.
18841     *
18842     * @hide
18843     */
18844    public boolean isTextDirectionInherited() {
18845        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
18846    }
18847
18848    /**
18849     * @return true if text direction is resolved.
18850     */
18851    public boolean isTextDirectionResolved() {
18852        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
18853    }
18854
18855    /**
18856     * Return the value specifying the text alignment or policy that was set with
18857     * {@link #setTextAlignment(int)}.
18858     *
18859     * @return the defined text alignment. It can be one of:
18860     *
18861     * {@link #TEXT_ALIGNMENT_INHERIT},
18862     * {@link #TEXT_ALIGNMENT_GRAVITY},
18863     * {@link #TEXT_ALIGNMENT_CENTER},
18864     * {@link #TEXT_ALIGNMENT_TEXT_START},
18865     * {@link #TEXT_ALIGNMENT_TEXT_END},
18866     * {@link #TEXT_ALIGNMENT_VIEW_START},
18867     * {@link #TEXT_ALIGNMENT_VIEW_END}
18868     *
18869     * @attr ref android.R.styleable#View_textAlignment
18870     *
18871     * @hide
18872     */
18873    @ViewDebug.ExportedProperty(category = "text", mapping = {
18874            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
18875            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
18876            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
18877            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
18878            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
18879            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
18880            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
18881    })
18882    @TextAlignment
18883    public int getRawTextAlignment() {
18884        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
18885    }
18886
18887    /**
18888     * Set the text alignment.
18889     *
18890     * @param textAlignment The text alignment to set. Should be one of
18891     *
18892     * {@link #TEXT_ALIGNMENT_INHERIT},
18893     * {@link #TEXT_ALIGNMENT_GRAVITY},
18894     * {@link #TEXT_ALIGNMENT_CENTER},
18895     * {@link #TEXT_ALIGNMENT_TEXT_START},
18896     * {@link #TEXT_ALIGNMENT_TEXT_END},
18897     * {@link #TEXT_ALIGNMENT_VIEW_START},
18898     * {@link #TEXT_ALIGNMENT_VIEW_END}
18899     *
18900     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
18901     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
18902     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
18903     *
18904     * @attr ref android.R.styleable#View_textAlignment
18905     */
18906    public void setTextAlignment(@TextAlignment int textAlignment) {
18907        if (textAlignment != getRawTextAlignment()) {
18908            // Reset the current and resolved text alignment
18909            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
18910            resetResolvedTextAlignment();
18911            // Set the new text alignment
18912            mPrivateFlags2 |=
18913                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
18914            // Do resolution
18915            resolveTextAlignment();
18916            // Notify change
18917            onRtlPropertiesChanged(getLayoutDirection());
18918            // Refresh
18919            requestLayout();
18920            invalidate(true);
18921        }
18922    }
18923
18924    /**
18925     * Return the resolved text alignment.
18926     *
18927     * @return the resolved text alignment. Returns one of:
18928     *
18929     * {@link #TEXT_ALIGNMENT_GRAVITY},
18930     * {@link #TEXT_ALIGNMENT_CENTER},
18931     * {@link #TEXT_ALIGNMENT_TEXT_START},
18932     * {@link #TEXT_ALIGNMENT_TEXT_END},
18933     * {@link #TEXT_ALIGNMENT_VIEW_START},
18934     * {@link #TEXT_ALIGNMENT_VIEW_END}
18935     *
18936     * @attr ref android.R.styleable#View_textAlignment
18937     */
18938    @ViewDebug.ExportedProperty(category = "text", mapping = {
18939            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
18940            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
18941            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
18942            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
18943            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
18944            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
18945            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
18946    })
18947    @TextAlignment
18948    public int getTextAlignment() {
18949        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
18950                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
18951    }
18952
18953    /**
18954     * Resolve the text alignment.
18955     *
18956     * @return true if resolution has been done, false otherwise.
18957     *
18958     * @hide
18959     */
18960    public boolean resolveTextAlignment() {
18961        // Reset any previous text alignment resolution
18962        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
18963
18964        if (hasRtlSupport()) {
18965            // Set resolved text alignment flag depending on text alignment flag
18966            final int textAlignment = getRawTextAlignment();
18967            switch (textAlignment) {
18968                case TEXT_ALIGNMENT_INHERIT:
18969                    // Check if we can resolve the text alignment
18970                    if (!canResolveTextAlignment()) {
18971                        // We cannot do the resolution if there is no parent so use the default
18972                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18973                        // Resolution will need to happen again later
18974                        return false;
18975                    }
18976
18977                    // Parent has not yet resolved, so we still return the default
18978                    try {
18979                        if (!mParent.isTextAlignmentResolved()) {
18980                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18981                            // Resolution will need to happen again later
18982                            return false;
18983                        }
18984                    } catch (AbstractMethodError e) {
18985                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18986                                " does not fully implement ViewParent", e);
18987                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED |
18988                                PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18989                        return true;
18990                    }
18991
18992                    int parentResolvedTextAlignment;
18993                    try {
18994                        parentResolvedTextAlignment = mParent.getTextAlignment();
18995                    } catch (AbstractMethodError e) {
18996                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18997                                " does not fully implement ViewParent", e);
18998                        parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY;
18999                    }
19000                    switch (parentResolvedTextAlignment) {
19001                        case TEXT_ALIGNMENT_GRAVITY:
19002                        case TEXT_ALIGNMENT_TEXT_START:
19003                        case TEXT_ALIGNMENT_TEXT_END:
19004                        case TEXT_ALIGNMENT_CENTER:
19005                        case TEXT_ALIGNMENT_VIEW_START:
19006                        case TEXT_ALIGNMENT_VIEW_END:
19007                            // Resolved text alignment is the same as the parent resolved
19008                            // text alignment
19009                            mPrivateFlags2 |=
19010                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
19011                            break;
19012                        default:
19013                            // Use default resolved text alignment
19014                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
19015                    }
19016                    break;
19017                case TEXT_ALIGNMENT_GRAVITY:
19018                case TEXT_ALIGNMENT_TEXT_START:
19019                case TEXT_ALIGNMENT_TEXT_END:
19020                case TEXT_ALIGNMENT_CENTER:
19021                case TEXT_ALIGNMENT_VIEW_START:
19022                case TEXT_ALIGNMENT_VIEW_END:
19023                    // Resolved text alignment is the same as text alignment
19024                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
19025                    break;
19026                default:
19027                    // Use default resolved text alignment
19028                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
19029            }
19030        } else {
19031            // Use default resolved text alignment
19032            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
19033        }
19034
19035        // Set the resolved
19036        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
19037        return true;
19038    }
19039
19040    /**
19041     * Check if text alignment resolution can be done.
19042     *
19043     * @return true if text alignment resolution can be done otherwise return false.
19044     */
19045    public boolean canResolveTextAlignment() {
19046        switch (getRawTextAlignment()) {
19047            case TEXT_DIRECTION_INHERIT:
19048                if (mParent != null) {
19049                    try {
19050                        return mParent.canResolveTextAlignment();
19051                    } catch (AbstractMethodError e) {
19052                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
19053                                " does not fully implement ViewParent", e);
19054                    }
19055                }
19056                return false;
19057
19058            default:
19059                return true;
19060        }
19061    }
19062
19063    /**
19064     * Reset resolved text alignment. Text alignment will be resolved during a call to
19065     * {@link #onMeasure(int, int)}.
19066     *
19067     * @hide
19068     */
19069    public void resetResolvedTextAlignment() {
19070        // Reset any previous text alignment resolution
19071        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
19072        // Set to default
19073        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
19074    }
19075
19076    /**
19077     * @return true if text alignment is inherited.
19078     *
19079     * @hide
19080     */
19081    public boolean isTextAlignmentInherited() {
19082        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
19083    }
19084
19085    /**
19086     * @return true if text alignment is resolved.
19087     */
19088    public boolean isTextAlignmentResolved() {
19089        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
19090    }
19091
19092    /**
19093     * Generate a value suitable for use in {@link #setId(int)}.
19094     * This value will not collide with ID values generated at build time by aapt for R.id.
19095     *
19096     * @return a generated ID value
19097     */
19098    public static int generateViewId() {
19099        for (;;) {
19100            final int result = sNextGeneratedId.get();
19101            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
19102            int newValue = result + 1;
19103            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
19104            if (sNextGeneratedId.compareAndSet(result, newValue)) {
19105                return result;
19106            }
19107        }
19108    }
19109
19110    /**
19111     * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions.
19112     * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and
19113     *                           a normal View or a ViewGroup with
19114     *                           {@link android.view.ViewGroup#isTransitionGroup()} true.
19115     * @hide
19116     */
19117    public void captureTransitioningViews(List<View> transitioningViews) {
19118        if (getVisibility() == View.VISIBLE) {
19119            transitioningViews.add(this);
19120        }
19121    }
19122
19123    /**
19124     * Adds all Views that have {@link #getTransitionName()} non-null to namedElements.
19125     * @param namedElements Will contain all Views in the hierarchy having a transitionName.
19126     * @hide
19127     */
19128    public void findNamedViews(Map<String, View> namedElements) {
19129        if (getVisibility() == VISIBLE || mGhostView != null) {
19130            String transitionName = getTransitionName();
19131            if (transitionName != null) {
19132                namedElements.put(transitionName, this);
19133            }
19134        }
19135    }
19136
19137    //
19138    // Properties
19139    //
19140    /**
19141     * A Property wrapper around the <code>alpha</code> functionality handled by the
19142     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
19143     */
19144    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
19145        @Override
19146        public void setValue(View object, float value) {
19147            object.setAlpha(value);
19148        }
19149
19150        @Override
19151        public Float get(View object) {
19152            return object.getAlpha();
19153        }
19154    };
19155
19156    /**
19157     * A Property wrapper around the <code>translationX</code> functionality handled by the
19158     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
19159     */
19160    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
19161        @Override
19162        public void setValue(View object, float value) {
19163            object.setTranslationX(value);
19164        }
19165
19166                @Override
19167        public Float get(View object) {
19168            return object.getTranslationX();
19169        }
19170    };
19171
19172    /**
19173     * A Property wrapper around the <code>translationY</code> functionality handled by the
19174     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
19175     */
19176    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
19177        @Override
19178        public void setValue(View object, float value) {
19179            object.setTranslationY(value);
19180        }
19181
19182        @Override
19183        public Float get(View object) {
19184            return object.getTranslationY();
19185        }
19186    };
19187
19188    /**
19189     * A Property wrapper around the <code>translationZ</code> functionality handled by the
19190     * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods.
19191     */
19192    public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") {
19193        @Override
19194        public void setValue(View object, float value) {
19195            object.setTranslationZ(value);
19196        }
19197
19198        @Override
19199        public Float get(View object) {
19200            return object.getTranslationZ();
19201        }
19202    };
19203
19204    /**
19205     * A Property wrapper around the <code>x</code> functionality handled by the
19206     * {@link View#setX(float)} and {@link View#getX()} methods.
19207     */
19208    public static final Property<View, Float> X = new FloatProperty<View>("x") {
19209        @Override
19210        public void setValue(View object, float value) {
19211            object.setX(value);
19212        }
19213
19214        @Override
19215        public Float get(View object) {
19216            return object.getX();
19217        }
19218    };
19219
19220    /**
19221     * A Property wrapper around the <code>y</code> functionality handled by the
19222     * {@link View#setY(float)} and {@link View#getY()} methods.
19223     */
19224    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
19225        @Override
19226        public void setValue(View object, float value) {
19227            object.setY(value);
19228        }
19229
19230        @Override
19231        public Float get(View object) {
19232            return object.getY();
19233        }
19234    };
19235
19236    /**
19237     * A Property wrapper around the <code>z</code> functionality handled by the
19238     * {@link View#setZ(float)} and {@link View#getZ()} methods.
19239     */
19240    public static final Property<View, Float> Z = new FloatProperty<View>("z") {
19241        @Override
19242        public void setValue(View object, float value) {
19243            object.setZ(value);
19244        }
19245
19246        @Override
19247        public Float get(View object) {
19248            return object.getZ();
19249        }
19250    };
19251
19252    /**
19253     * A Property wrapper around the <code>rotation</code> functionality handled by the
19254     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
19255     */
19256    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
19257        @Override
19258        public void setValue(View object, float value) {
19259            object.setRotation(value);
19260        }
19261
19262        @Override
19263        public Float get(View object) {
19264            return object.getRotation();
19265        }
19266    };
19267
19268    /**
19269     * A Property wrapper around the <code>rotationX</code> functionality handled by the
19270     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
19271     */
19272    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
19273        @Override
19274        public void setValue(View object, float value) {
19275            object.setRotationX(value);
19276        }
19277
19278        @Override
19279        public Float get(View object) {
19280            return object.getRotationX();
19281        }
19282    };
19283
19284    /**
19285     * A Property wrapper around the <code>rotationY</code> functionality handled by the
19286     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
19287     */
19288    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
19289        @Override
19290        public void setValue(View object, float value) {
19291            object.setRotationY(value);
19292        }
19293
19294        @Override
19295        public Float get(View object) {
19296            return object.getRotationY();
19297        }
19298    };
19299
19300    /**
19301     * A Property wrapper around the <code>scaleX</code> functionality handled by the
19302     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
19303     */
19304    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
19305        @Override
19306        public void setValue(View object, float value) {
19307            object.setScaleX(value);
19308        }
19309
19310        @Override
19311        public Float get(View object) {
19312            return object.getScaleX();
19313        }
19314    };
19315
19316    /**
19317     * A Property wrapper around the <code>scaleY</code> functionality handled by the
19318     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
19319     */
19320    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
19321        @Override
19322        public void setValue(View object, float value) {
19323            object.setScaleY(value);
19324        }
19325
19326        @Override
19327        public Float get(View object) {
19328            return object.getScaleY();
19329        }
19330    };
19331
19332    /**
19333     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
19334     * Each MeasureSpec represents a requirement for either the width or the height.
19335     * A MeasureSpec is comprised of a size and a mode. There are three possible
19336     * modes:
19337     * <dl>
19338     * <dt>UNSPECIFIED</dt>
19339     * <dd>
19340     * The parent has not imposed any constraint on the child. It can be whatever size
19341     * it wants.
19342     * </dd>
19343     *
19344     * <dt>EXACTLY</dt>
19345     * <dd>
19346     * The parent has determined an exact size for the child. The child is going to be
19347     * given those bounds regardless of how big it wants to be.
19348     * </dd>
19349     *
19350     * <dt>AT_MOST</dt>
19351     * <dd>
19352     * The child can be as large as it wants up to the specified size.
19353     * </dd>
19354     * </dl>
19355     *
19356     * MeasureSpecs are implemented as ints to reduce object allocation. This class
19357     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
19358     */
19359    public static class MeasureSpec {
19360        private static final int MODE_SHIFT = 30;
19361        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
19362
19363        /**
19364         * Measure specification mode: The parent has not imposed any constraint
19365         * on the child. It can be whatever size it wants.
19366         */
19367        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
19368
19369        /**
19370         * Measure specification mode: The parent has determined an exact size
19371         * for the child. The child is going to be given those bounds regardless
19372         * of how big it wants to be.
19373         */
19374        public static final int EXACTLY     = 1 << MODE_SHIFT;
19375
19376        /**
19377         * Measure specification mode: The child can be as large as it wants up
19378         * to the specified size.
19379         */
19380        public static final int AT_MOST     = 2 << MODE_SHIFT;
19381
19382        /**
19383         * Creates a measure specification based on the supplied size and mode.
19384         *
19385         * The mode must always be one of the following:
19386         * <ul>
19387         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
19388         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
19389         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
19390         * </ul>
19391         *
19392         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
19393         * implementation was such that the order of arguments did not matter
19394         * and overflow in either value could impact the resulting MeasureSpec.
19395         * {@link android.widget.RelativeLayout} was affected by this bug.
19396         * Apps targeting API levels greater than 17 will get the fixed, more strict
19397         * behavior.</p>
19398         *
19399         * @param size the size of the measure specification
19400         * @param mode the mode of the measure specification
19401         * @return the measure specification based on size and mode
19402         */
19403        public static int makeMeasureSpec(int size, int mode) {
19404            if (sUseBrokenMakeMeasureSpec) {
19405                return size + mode;
19406            } else {
19407                return (size & ~MODE_MASK) | (mode & MODE_MASK);
19408            }
19409        }
19410
19411        /**
19412         * Extracts the mode from the supplied measure specification.
19413         *
19414         * @param measureSpec the measure specification to extract the mode from
19415         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
19416         *         {@link android.view.View.MeasureSpec#AT_MOST} or
19417         *         {@link android.view.View.MeasureSpec#EXACTLY}
19418         */
19419        public static int getMode(int measureSpec) {
19420            return (measureSpec & MODE_MASK);
19421        }
19422
19423        /**
19424         * Extracts the size from the supplied measure specification.
19425         *
19426         * @param measureSpec the measure specification to extract the size from
19427         * @return the size in pixels defined in the supplied measure specification
19428         */
19429        public static int getSize(int measureSpec) {
19430            return (measureSpec & ~MODE_MASK);
19431        }
19432
19433        static int adjust(int measureSpec, int delta) {
19434            final int mode = getMode(measureSpec);
19435            if (mode == UNSPECIFIED) {
19436                // No need to adjust size for UNSPECIFIED mode.
19437                return makeMeasureSpec(0, UNSPECIFIED);
19438            }
19439            int size = getSize(measureSpec) + delta;
19440            if (size < 0) {
19441                Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size +
19442                        ") spec: " + toString(measureSpec) + " delta: " + delta);
19443                size = 0;
19444            }
19445            return makeMeasureSpec(size, mode);
19446        }
19447
19448        /**
19449         * Returns a String representation of the specified measure
19450         * specification.
19451         *
19452         * @param measureSpec the measure specification to convert to a String
19453         * @return a String with the following format: "MeasureSpec: MODE SIZE"
19454         */
19455        public static String toString(int measureSpec) {
19456            int mode = getMode(measureSpec);
19457            int size = getSize(measureSpec);
19458
19459            StringBuilder sb = new StringBuilder("MeasureSpec: ");
19460
19461            if (mode == UNSPECIFIED)
19462                sb.append("UNSPECIFIED ");
19463            else if (mode == EXACTLY)
19464                sb.append("EXACTLY ");
19465            else if (mode == AT_MOST)
19466                sb.append("AT_MOST ");
19467            else
19468                sb.append(mode).append(" ");
19469
19470            sb.append(size);
19471            return sb.toString();
19472        }
19473    }
19474
19475    private final class CheckForLongPress implements Runnable {
19476        private int mOriginalWindowAttachCount;
19477
19478        @Override
19479        public void run() {
19480            if (isPressed() && (mParent != null)
19481                    && mOriginalWindowAttachCount == mWindowAttachCount) {
19482                if (performLongClick()) {
19483                    mHasPerformedLongPress = true;
19484                }
19485            }
19486        }
19487
19488        public void rememberWindowAttachCount() {
19489            mOriginalWindowAttachCount = mWindowAttachCount;
19490        }
19491    }
19492
19493    private final class CheckForTap implements Runnable {
19494        public float x;
19495        public float y;
19496
19497        @Override
19498        public void run() {
19499            mPrivateFlags &= ~PFLAG_PREPRESSED;
19500            setPressed(true, x, y);
19501            checkForLongClick(ViewConfiguration.getTapTimeout());
19502        }
19503    }
19504
19505    private final class PerformClick implements Runnable {
19506        @Override
19507        public void run() {
19508            performClick();
19509        }
19510    }
19511
19512    /** @hide */
19513    public void hackTurnOffWindowResizeAnim(boolean off) {
19514        mAttachInfo.mTurnOffWindowResizeAnim = off;
19515    }
19516
19517    /**
19518     * This method returns a ViewPropertyAnimator object, which can be used to animate
19519     * specific properties on this View.
19520     *
19521     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
19522     */
19523    public ViewPropertyAnimator animate() {
19524        if (mAnimator == null) {
19525            mAnimator = new ViewPropertyAnimator(this);
19526        }
19527        return mAnimator;
19528    }
19529
19530    /**
19531     * Sets the name of the View to be used to identify Views in Transitions.
19532     * Names should be unique in the View hierarchy.
19533     *
19534     * @param transitionName The name of the View to uniquely identify it for Transitions.
19535     */
19536    public final void setTransitionName(String transitionName) {
19537        mTransitionName = transitionName;
19538    }
19539
19540    /**
19541     * Returns the name of the View to be used to identify Views in Transitions.
19542     * Names should be unique in the View hierarchy.
19543     *
19544     * <p>This returns null if the View has not been given a name.</p>
19545     *
19546     * @return The name used of the View to be used to identify Views in Transitions or null
19547     * if no name has been given.
19548     */
19549    @ViewDebug.ExportedProperty
19550    public String getTransitionName() {
19551        return mTransitionName;
19552    }
19553
19554    /**
19555     * Interface definition for a callback to be invoked when a hardware key event is
19556     * dispatched to this view. The callback will be invoked before the key event is
19557     * given to the view. This is only useful for hardware keyboards; a software input
19558     * method has no obligation to trigger this listener.
19559     */
19560    public interface OnKeyListener {
19561        /**
19562         * Called when a hardware key is dispatched to a view. This allows listeners to
19563         * get a chance to respond before the target view.
19564         * <p>Key presses in software keyboards will generally NOT trigger this method,
19565         * although some may elect to do so in some situations. Do not assume a
19566         * software input method has to be key-based; even if it is, it may use key presses
19567         * in a different way than you expect, so there is no way to reliably catch soft
19568         * input key presses.
19569         *
19570         * @param v The view the key has been dispatched to.
19571         * @param keyCode The code for the physical key that was pressed
19572         * @param event The KeyEvent object containing full information about
19573         *        the event.
19574         * @return True if the listener has consumed the event, false otherwise.
19575         */
19576        boolean onKey(View v, int keyCode, KeyEvent event);
19577    }
19578
19579    /**
19580     * Interface definition for a callback to be invoked when a touch event is
19581     * dispatched to this view. The callback will be invoked before the touch
19582     * event is given to the view.
19583     */
19584    public interface OnTouchListener {
19585        /**
19586         * Called when a touch event is dispatched to a view. This allows listeners to
19587         * get a chance to respond before the target view.
19588         *
19589         * @param v The view the touch event has been dispatched to.
19590         * @param event The MotionEvent object containing full information about
19591         *        the event.
19592         * @return True if the listener has consumed the event, false otherwise.
19593         */
19594        boolean onTouch(View v, MotionEvent event);
19595    }
19596
19597    /**
19598     * Interface definition for a callback to be invoked when a hover event is
19599     * dispatched to this view. The callback will be invoked before the hover
19600     * event is given to the view.
19601     */
19602    public interface OnHoverListener {
19603        /**
19604         * Called when a hover event is dispatched to a view. This allows listeners to
19605         * get a chance to respond before the target view.
19606         *
19607         * @param v The view the hover event has been dispatched to.
19608         * @param event The MotionEvent object containing full information about
19609         *        the event.
19610         * @return True if the listener has consumed the event, false otherwise.
19611         */
19612        boolean onHover(View v, MotionEvent event);
19613    }
19614
19615    /**
19616     * Interface definition for a callback to be invoked when a generic motion event is
19617     * dispatched to this view. The callback will be invoked before the generic motion
19618     * event is given to the view.
19619     */
19620    public interface OnGenericMotionListener {
19621        /**
19622         * Called when a generic motion event is dispatched to a view. This allows listeners to
19623         * get a chance to respond before the target view.
19624         *
19625         * @param v The view the generic motion event has been dispatched to.
19626         * @param event The MotionEvent object containing full information about
19627         *        the event.
19628         * @return True if the listener has consumed the event, false otherwise.
19629         */
19630        boolean onGenericMotion(View v, MotionEvent event);
19631    }
19632
19633    /**
19634     * Interface definition for a callback to be invoked when a view has been clicked and held.
19635     */
19636    public interface OnLongClickListener {
19637        /**
19638         * Called when a view has been clicked and held.
19639         *
19640         * @param v The view that was clicked and held.
19641         *
19642         * @return true if the callback consumed the long click, false otherwise.
19643         */
19644        boolean onLongClick(View v);
19645    }
19646
19647    /**
19648     * Interface definition for a callback to be invoked when a drag is being dispatched
19649     * to this view.  The callback will be invoked before the hosting view's own
19650     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
19651     * onDrag(event) behavior, it should return 'false' from this callback.
19652     *
19653     * <div class="special reference">
19654     * <h3>Developer Guides</h3>
19655     * <p>For a guide to implementing drag and drop features, read the
19656     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
19657     * </div>
19658     */
19659    public interface OnDragListener {
19660        /**
19661         * Called when a drag event is dispatched to a view. This allows listeners
19662         * to get a chance to override base View behavior.
19663         *
19664         * @param v The View that received the drag event.
19665         * @param event The {@link android.view.DragEvent} object for the drag event.
19666         * @return {@code true} if the drag event was handled successfully, or {@code false}
19667         * if the drag event was not handled. Note that {@code false} will trigger the View
19668         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
19669         */
19670        boolean onDrag(View v, DragEvent event);
19671    }
19672
19673    /**
19674     * Interface definition for a callback to be invoked when the focus state of
19675     * a view changed.
19676     */
19677    public interface OnFocusChangeListener {
19678        /**
19679         * Called when the focus state of a view has changed.
19680         *
19681         * @param v The view whose state has changed.
19682         * @param hasFocus The new focus state of v.
19683         */
19684        void onFocusChange(View v, boolean hasFocus);
19685    }
19686
19687    /**
19688     * Interface definition for a callback to be invoked when a view is clicked.
19689     */
19690    public interface OnClickListener {
19691        /**
19692         * Called when a view has been clicked.
19693         *
19694         * @param v The view that was clicked.
19695         */
19696        void onClick(View v);
19697    }
19698
19699    /**
19700     * Interface definition for a callback to be invoked when the context menu
19701     * for this view is being built.
19702     */
19703    public interface OnCreateContextMenuListener {
19704        /**
19705         * Called when the context menu for this view is being built. It is not
19706         * safe to hold onto the menu after this method returns.
19707         *
19708         * @param menu The context menu that is being built
19709         * @param v The view for which the context menu is being built
19710         * @param menuInfo Extra information about the item for which the
19711         *            context menu should be shown. This information will vary
19712         *            depending on the class of v.
19713         */
19714        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
19715    }
19716
19717    /**
19718     * Interface definition for a callback to be invoked when the status bar changes
19719     * visibility.  This reports <strong>global</strong> changes to the system UI
19720     * state, not what the application is requesting.
19721     *
19722     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
19723     */
19724    public interface OnSystemUiVisibilityChangeListener {
19725        /**
19726         * Called when the status bar changes visibility because of a call to
19727         * {@link View#setSystemUiVisibility(int)}.
19728         *
19729         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
19730         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
19731         * This tells you the <strong>global</strong> state of these UI visibility
19732         * flags, not what your app is currently applying.
19733         */
19734        public void onSystemUiVisibilityChange(int visibility);
19735    }
19736
19737    /**
19738     * Interface definition for a callback to be invoked when this view is attached
19739     * or detached from its window.
19740     */
19741    public interface OnAttachStateChangeListener {
19742        /**
19743         * Called when the view is attached to a window.
19744         * @param v The view that was attached
19745         */
19746        public void onViewAttachedToWindow(View v);
19747        /**
19748         * Called when the view is detached from a window.
19749         * @param v The view that was detached
19750         */
19751        public void onViewDetachedFromWindow(View v);
19752    }
19753
19754    /**
19755     * Listener for applying window insets on a view in a custom way.
19756     *
19757     * <p>Apps may choose to implement this interface if they want to apply custom policy
19758     * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener
19759     * is set, its
19760     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
19761     * method will be called instead of the View's own
19762     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener
19763     * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply
19764     * the View's normal behavior as part of its own.</p>
19765     */
19766    public interface OnApplyWindowInsetsListener {
19767        /**
19768         * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set}
19769         * on a View, this listener method will be called instead of the view's own
19770         * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
19771         *
19772         * @param v The view applying window insets
19773         * @param insets The insets to apply
19774         * @return The insets supplied, minus any insets that were consumed
19775         */
19776        public WindowInsets onApplyWindowInsets(View v, WindowInsets insets);
19777    }
19778
19779    private final class UnsetPressedState implements Runnable {
19780        @Override
19781        public void run() {
19782            setPressed(false);
19783        }
19784    }
19785
19786    /**
19787     * Base class for derived classes that want to save and restore their own
19788     * state in {@link android.view.View#onSaveInstanceState()}.
19789     */
19790    public static class BaseSavedState extends AbsSavedState {
19791        /**
19792         * Constructor used when reading from a parcel. Reads the state of the superclass.
19793         *
19794         * @param source
19795         */
19796        public BaseSavedState(Parcel source) {
19797            super(source);
19798        }
19799
19800        /**
19801         * Constructor called by derived classes when creating their SavedState objects
19802         *
19803         * @param superState The state of the superclass of this view
19804         */
19805        public BaseSavedState(Parcelable superState) {
19806            super(superState);
19807        }
19808
19809        public static final Parcelable.Creator<BaseSavedState> CREATOR =
19810                new Parcelable.Creator<BaseSavedState>() {
19811            public BaseSavedState createFromParcel(Parcel in) {
19812                return new BaseSavedState(in);
19813            }
19814
19815            public BaseSavedState[] newArray(int size) {
19816                return new BaseSavedState[size];
19817            }
19818        };
19819    }
19820
19821    /**
19822     * A set of information given to a view when it is attached to its parent
19823     * window.
19824     */
19825    final static class AttachInfo {
19826        interface Callbacks {
19827            void playSoundEffect(int effectId);
19828            boolean performHapticFeedback(int effectId, boolean always);
19829        }
19830
19831        /**
19832         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
19833         * to a Handler. This class contains the target (View) to invalidate and
19834         * the coordinates of the dirty rectangle.
19835         *
19836         * For performance purposes, this class also implements a pool of up to
19837         * POOL_LIMIT objects that get reused. This reduces memory allocations
19838         * whenever possible.
19839         */
19840        static class InvalidateInfo {
19841            private static final int POOL_LIMIT = 10;
19842
19843            private static final SynchronizedPool<InvalidateInfo> sPool =
19844                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
19845
19846            View target;
19847
19848            int left;
19849            int top;
19850            int right;
19851            int bottom;
19852
19853            public static InvalidateInfo obtain() {
19854                InvalidateInfo instance = sPool.acquire();
19855                return (instance != null) ? instance : new InvalidateInfo();
19856            }
19857
19858            public void recycle() {
19859                target = null;
19860                sPool.release(this);
19861            }
19862        }
19863
19864        final IWindowSession mSession;
19865
19866        final IWindow mWindow;
19867
19868        final IBinder mWindowToken;
19869
19870        final Display mDisplay;
19871
19872        final Callbacks mRootCallbacks;
19873
19874        IWindowId mIWindowId;
19875        WindowId mWindowId;
19876
19877        /**
19878         * The top view of the hierarchy.
19879         */
19880        View mRootView;
19881
19882        IBinder mPanelParentWindowToken;
19883
19884        boolean mHardwareAccelerated;
19885        boolean mHardwareAccelerationRequested;
19886        HardwareRenderer mHardwareRenderer;
19887        List<RenderNode> mPendingAnimatingRenderNodes;
19888
19889        /**
19890         * The state of the display to which the window is attached, as reported
19891         * by {@link Display#getState()}.  Note that the display state constants
19892         * declared by {@link Display} do not exactly line up with the screen state
19893         * constants declared by {@link View} (there are more display states than
19894         * screen states).
19895         */
19896        int mDisplayState = Display.STATE_UNKNOWN;
19897
19898        /**
19899         * Scale factor used by the compatibility mode
19900         */
19901        float mApplicationScale;
19902
19903        /**
19904         * Indicates whether the application is in compatibility mode
19905         */
19906        boolean mScalingRequired;
19907
19908        /**
19909         * If set, ViewRootImpl doesn't use its lame animation for when the window resizes.
19910         */
19911        boolean mTurnOffWindowResizeAnim;
19912
19913        /**
19914         * Left position of this view's window
19915         */
19916        int mWindowLeft;
19917
19918        /**
19919         * Top position of this view's window
19920         */
19921        int mWindowTop;
19922
19923        /**
19924         * Indicates whether views need to use 32-bit drawing caches
19925         */
19926        boolean mUse32BitDrawingCache;
19927
19928        /**
19929         * For windows that are full-screen but using insets to layout inside
19930         * of the screen areas, these are the current insets to appear inside
19931         * the overscan area of the display.
19932         */
19933        final Rect mOverscanInsets = new Rect();
19934
19935        /**
19936         * For windows that are full-screen but using insets to layout inside
19937         * of the screen decorations, these are the current insets for the
19938         * content of the window.
19939         */
19940        final Rect mContentInsets = new Rect();
19941
19942        /**
19943         * For windows that are full-screen but using insets to layout inside
19944         * of the screen decorations, these are the current insets for the
19945         * actual visible parts of the window.
19946         */
19947        final Rect mVisibleInsets = new Rect();
19948
19949        /**
19950         * For windows that are full-screen but using insets to layout inside
19951         * of the screen decorations, these are the current insets for the
19952         * stable system windows.
19953         */
19954        final Rect mStableInsets = new Rect();
19955
19956        /**
19957         * The internal insets given by this window.  This value is
19958         * supplied by the client (through
19959         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
19960         * be given to the window manager when changed to be used in laying
19961         * out windows behind it.
19962         */
19963        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
19964                = new ViewTreeObserver.InternalInsetsInfo();
19965
19966        /**
19967         * Set to true when mGivenInternalInsets is non-empty.
19968         */
19969        boolean mHasNonEmptyGivenInternalInsets;
19970
19971        /**
19972         * All views in the window's hierarchy that serve as scroll containers,
19973         * used to determine if the window can be resized or must be panned
19974         * to adjust for a soft input area.
19975         */
19976        final ArrayList<View> mScrollContainers = new ArrayList<View>();
19977
19978        final KeyEvent.DispatcherState mKeyDispatchState
19979                = new KeyEvent.DispatcherState();
19980
19981        /**
19982         * Indicates whether the view's window currently has the focus.
19983         */
19984        boolean mHasWindowFocus;
19985
19986        /**
19987         * The current visibility of the window.
19988         */
19989        int mWindowVisibility;
19990
19991        /**
19992         * Indicates the time at which drawing started to occur.
19993         */
19994        long mDrawingTime;
19995
19996        /**
19997         * Indicates whether or not ignoring the DIRTY_MASK flags.
19998         */
19999        boolean mIgnoreDirtyState;
20000
20001        /**
20002         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
20003         * to avoid clearing that flag prematurely.
20004         */
20005        boolean mSetIgnoreDirtyState = false;
20006
20007        /**
20008         * Indicates whether the view's window is currently in touch mode.
20009         */
20010        boolean mInTouchMode;
20011
20012        /**
20013         * Indicates whether the view has requested unbuffered input dispatching for the current
20014         * event stream.
20015         */
20016        boolean mUnbufferedDispatchRequested;
20017
20018        /**
20019         * Indicates that ViewAncestor should trigger a global layout change
20020         * the next time it performs a traversal
20021         */
20022        boolean mRecomputeGlobalAttributes;
20023
20024        /**
20025         * Always report new attributes at next traversal.
20026         */
20027        boolean mForceReportNewAttributes;
20028
20029        /**
20030         * Set during a traveral if any views want to keep the screen on.
20031         */
20032        boolean mKeepScreenOn;
20033
20034        /**
20035         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
20036         */
20037        int mSystemUiVisibility;
20038
20039        /**
20040         * Hack to force certain system UI visibility flags to be cleared.
20041         */
20042        int mDisabledSystemUiVisibility;
20043
20044        /**
20045         * Last global system UI visibility reported by the window manager.
20046         */
20047        int mGlobalSystemUiVisibility;
20048
20049        /**
20050         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
20051         * attached.
20052         */
20053        boolean mHasSystemUiListeners;
20054
20055        /**
20056         * Set if the window has requested to extend into the overscan region
20057         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
20058         */
20059        boolean mOverscanRequested;
20060
20061        /**
20062         * Set if the visibility of any views has changed.
20063         */
20064        boolean mViewVisibilityChanged;
20065
20066        /**
20067         * Set to true if a view has been scrolled.
20068         */
20069        boolean mViewScrollChanged;
20070
20071        /**
20072         * Set to true if high contrast mode enabled
20073         */
20074        boolean mHighContrastText;
20075
20076        /**
20077         * Global to the view hierarchy used as a temporary for dealing with
20078         * x/y points in the transparent region computations.
20079         */
20080        final int[] mTransparentLocation = new int[2];
20081
20082        /**
20083         * Global to the view hierarchy used as a temporary for dealing with
20084         * x/y points in the ViewGroup.invalidateChild implementation.
20085         */
20086        final int[] mInvalidateChildLocation = new int[2];
20087
20088        /**
20089         * Global to the view hierarchy used as a temporary for dealng with
20090         * computing absolute on-screen location.
20091         */
20092        final int[] mTmpLocation = new int[2];
20093
20094        /**
20095         * Global to the view hierarchy used as a temporary for dealing with
20096         * x/y location when view is transformed.
20097         */
20098        final float[] mTmpTransformLocation = new float[2];
20099
20100        /**
20101         * The view tree observer used to dispatch global events like
20102         * layout, pre-draw, touch mode change, etc.
20103         */
20104        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
20105
20106        /**
20107         * A Canvas used by the view hierarchy to perform bitmap caching.
20108         */
20109        Canvas mCanvas;
20110
20111        /**
20112         * The view root impl.
20113         */
20114        final ViewRootImpl mViewRootImpl;
20115
20116        /**
20117         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
20118         * handler can be used to pump events in the UI events queue.
20119         */
20120        final Handler mHandler;
20121
20122        /**
20123         * Temporary for use in computing invalidate rectangles while
20124         * calling up the hierarchy.
20125         */
20126        final Rect mTmpInvalRect = new Rect();
20127
20128        /**
20129         * Temporary for use in computing hit areas with transformed views
20130         */
20131        final RectF mTmpTransformRect = new RectF();
20132
20133        /**
20134         * Temporary for use in transforming invalidation rect
20135         */
20136        final Matrix mTmpMatrix = new Matrix();
20137
20138        /**
20139         * Temporary for use in transforming invalidation rect
20140         */
20141        final Transformation mTmpTransformation = new Transformation();
20142
20143        /**
20144         * Temporary for use in querying outlines from OutlineProviders
20145         */
20146        final Outline mTmpOutline = new Outline();
20147
20148        /**
20149         * Temporary list for use in collecting focusable descendents of a view.
20150         */
20151        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
20152
20153        /**
20154         * The id of the window for accessibility purposes.
20155         */
20156        int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
20157
20158        /**
20159         * Flags related to accessibility processing.
20160         *
20161         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
20162         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
20163         */
20164        int mAccessibilityFetchFlags;
20165
20166        /**
20167         * The drawable for highlighting accessibility focus.
20168         */
20169        Drawable mAccessibilityFocusDrawable;
20170
20171        /**
20172         * Show where the margins, bounds and layout bounds are for each view.
20173         */
20174        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
20175
20176        /**
20177         * Point used to compute visible regions.
20178         */
20179        final Point mPoint = new Point();
20180
20181        /**
20182         * Used to track which View originated a requestLayout() call, used when
20183         * requestLayout() is called during layout.
20184         */
20185        View mViewRequestingLayout;
20186
20187        /**
20188         * Creates a new set of attachment information with the specified
20189         * events handler and thread.
20190         *
20191         * @param handler the events handler the view must use
20192         */
20193        AttachInfo(IWindowSession session, IWindow window, Display display,
20194                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
20195            mSession = session;
20196            mWindow = window;
20197            mWindowToken = window.asBinder();
20198            mDisplay = display;
20199            mViewRootImpl = viewRootImpl;
20200            mHandler = handler;
20201            mRootCallbacks = effectPlayer;
20202        }
20203    }
20204
20205    /**
20206     * <p>ScrollabilityCache holds various fields used by a View when scrolling
20207     * is supported. This avoids keeping too many unused fields in most
20208     * instances of View.</p>
20209     */
20210    private static class ScrollabilityCache implements Runnable {
20211
20212        /**
20213         * Scrollbars are not visible
20214         */
20215        public static final int OFF = 0;
20216
20217        /**
20218         * Scrollbars are visible
20219         */
20220        public static final int ON = 1;
20221
20222        /**
20223         * Scrollbars are fading away
20224         */
20225        public static final int FADING = 2;
20226
20227        public boolean fadeScrollBars;
20228
20229        public int fadingEdgeLength;
20230        public int scrollBarDefaultDelayBeforeFade;
20231        public int scrollBarFadeDuration;
20232
20233        public int scrollBarSize;
20234        public ScrollBarDrawable scrollBar;
20235        public float[] interpolatorValues;
20236        public View host;
20237
20238        public final Paint paint;
20239        public final Matrix matrix;
20240        public Shader shader;
20241
20242        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
20243
20244        private static final float[] OPAQUE = { 255 };
20245        private static final float[] TRANSPARENT = { 0.0f };
20246
20247        /**
20248         * When fading should start. This time moves into the future every time
20249         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
20250         */
20251        public long fadeStartTime;
20252
20253
20254        /**
20255         * The current state of the scrollbars: ON, OFF, or FADING
20256         */
20257        public int state = OFF;
20258
20259        private int mLastColor;
20260
20261        public ScrollabilityCache(ViewConfiguration configuration, View host) {
20262            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
20263            scrollBarSize = configuration.getScaledScrollBarSize();
20264            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
20265            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
20266
20267            paint = new Paint();
20268            matrix = new Matrix();
20269            // use use a height of 1, and then wack the matrix each time we
20270            // actually use it.
20271            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
20272            paint.setShader(shader);
20273            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
20274
20275            this.host = host;
20276        }
20277
20278        public void setFadeColor(int color) {
20279            if (color != mLastColor) {
20280                mLastColor = color;
20281
20282                if (color != 0) {
20283                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
20284                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
20285                    paint.setShader(shader);
20286                    // Restore the default transfer mode (src_over)
20287                    paint.setXfermode(null);
20288                } else {
20289                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
20290                    paint.setShader(shader);
20291                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
20292                }
20293            }
20294        }
20295
20296        public void run() {
20297            long now = AnimationUtils.currentAnimationTimeMillis();
20298            if (now >= fadeStartTime) {
20299
20300                // the animation fades the scrollbars out by changing
20301                // the opacity (alpha) from fully opaque to fully
20302                // transparent
20303                int nextFrame = (int) now;
20304                int framesCount = 0;
20305
20306                Interpolator interpolator = scrollBarInterpolator;
20307
20308                // Start opaque
20309                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
20310
20311                // End transparent
20312                nextFrame += scrollBarFadeDuration;
20313                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
20314
20315                state = FADING;
20316
20317                // Kick off the fade animation
20318                host.invalidate(true);
20319            }
20320        }
20321    }
20322
20323    /**
20324     * Resuable callback for sending
20325     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
20326     */
20327    private class SendViewScrolledAccessibilityEvent implements Runnable {
20328        public volatile boolean mIsPending;
20329
20330        public void run() {
20331            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
20332            mIsPending = false;
20333        }
20334    }
20335
20336    /**
20337     * <p>
20338     * This class represents a delegate that can be registered in a {@link View}
20339     * to enhance accessibility support via composition rather via inheritance.
20340     * It is specifically targeted to widget developers that extend basic View
20341     * classes i.e. classes in package android.view, that would like their
20342     * applications to be backwards compatible.
20343     * </p>
20344     * <div class="special reference">
20345     * <h3>Developer Guides</h3>
20346     * <p>For more information about making applications accessible, read the
20347     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
20348     * developer guide.</p>
20349     * </div>
20350     * <p>
20351     * A scenario in which a developer would like to use an accessibility delegate
20352     * is overriding a method introduced in a later API version then the minimal API
20353     * version supported by the application. For example, the method
20354     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
20355     * in API version 4 when the accessibility APIs were first introduced. If a
20356     * developer would like his application to run on API version 4 devices (assuming
20357     * all other APIs used by the application are version 4 or lower) and take advantage
20358     * of this method, instead of overriding the method which would break the application's
20359     * backwards compatibility, he can override the corresponding method in this
20360     * delegate and register the delegate in the target View if the API version of
20361     * the system is high enough i.e. the API version is same or higher to the API
20362     * version that introduced
20363     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
20364     * </p>
20365     * <p>
20366     * Here is an example implementation:
20367     * </p>
20368     * <code><pre><p>
20369     * if (Build.VERSION.SDK_INT >= 14) {
20370     *     // If the API version is equal of higher than the version in
20371     *     // which onInitializeAccessibilityNodeInfo was introduced we
20372     *     // register a delegate with a customized implementation.
20373     *     View view = findViewById(R.id.view_id);
20374     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
20375     *         public void onInitializeAccessibilityNodeInfo(View host,
20376     *                 AccessibilityNodeInfo info) {
20377     *             // Let the default implementation populate the info.
20378     *             super.onInitializeAccessibilityNodeInfo(host, info);
20379     *             // Set some other information.
20380     *             info.setEnabled(host.isEnabled());
20381     *         }
20382     *     });
20383     * }
20384     * </code></pre></p>
20385     * <p>
20386     * This delegate contains methods that correspond to the accessibility methods
20387     * in View. If a delegate has been specified the implementation in View hands
20388     * off handling to the corresponding method in this delegate. The default
20389     * implementation the delegate methods behaves exactly as the corresponding
20390     * method in View for the case of no accessibility delegate been set. Hence,
20391     * to customize the behavior of a View method, clients can override only the
20392     * corresponding delegate method without altering the behavior of the rest
20393     * accessibility related methods of the host view.
20394     * </p>
20395     */
20396    public static class AccessibilityDelegate {
20397
20398        /**
20399         * Sends an accessibility event of the given type. If accessibility is not
20400         * enabled this method has no effect.
20401         * <p>
20402         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
20403         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
20404         * been set.
20405         * </p>
20406         *
20407         * @param host The View hosting the delegate.
20408         * @param eventType The type of the event to send.
20409         *
20410         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
20411         */
20412        public void sendAccessibilityEvent(View host, int eventType) {
20413            host.sendAccessibilityEventInternal(eventType);
20414        }
20415
20416        /**
20417         * Performs the specified accessibility action on the view. For
20418         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
20419         * <p>
20420         * The default implementation behaves as
20421         * {@link View#performAccessibilityAction(int, Bundle)
20422         *  View#performAccessibilityAction(int, Bundle)} for the case of
20423         *  no accessibility delegate been set.
20424         * </p>
20425         *
20426         * @param action The action to perform.
20427         * @return Whether the action was performed.
20428         *
20429         * @see View#performAccessibilityAction(int, Bundle)
20430         *      View#performAccessibilityAction(int, Bundle)
20431         */
20432        public boolean performAccessibilityAction(View host, int action, Bundle args) {
20433            return host.performAccessibilityActionInternal(action, args);
20434        }
20435
20436        /**
20437         * Sends an accessibility event. This method behaves exactly as
20438         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
20439         * empty {@link AccessibilityEvent} and does not perform a check whether
20440         * accessibility is enabled.
20441         * <p>
20442         * The default implementation behaves as
20443         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
20444         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
20445         * the case of no accessibility delegate been set.
20446         * </p>
20447         *
20448         * @param host The View hosting the delegate.
20449         * @param event The event to send.
20450         *
20451         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
20452         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
20453         */
20454        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
20455            host.sendAccessibilityEventUncheckedInternal(event);
20456        }
20457
20458        /**
20459         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
20460         * to its children for adding their text content to the event.
20461         * <p>
20462         * The default implementation behaves as
20463         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
20464         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
20465         * the case of no accessibility delegate been set.
20466         * </p>
20467         *
20468         * @param host The View hosting the delegate.
20469         * @param event The event.
20470         * @return True if the event population was completed.
20471         *
20472         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
20473         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
20474         */
20475        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
20476            return host.dispatchPopulateAccessibilityEventInternal(event);
20477        }
20478
20479        /**
20480         * Gives a chance to the host View to populate the accessibility event with its
20481         * text content.
20482         * <p>
20483         * The default implementation behaves as
20484         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
20485         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
20486         * the case of no accessibility delegate been set.
20487         * </p>
20488         *
20489         * @param host The View hosting the delegate.
20490         * @param event The accessibility event which to populate.
20491         *
20492         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
20493         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
20494         */
20495        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
20496            host.onPopulateAccessibilityEventInternal(event);
20497        }
20498
20499        /**
20500         * Initializes an {@link AccessibilityEvent} with information about the
20501         * the host View which is the event source.
20502         * <p>
20503         * The default implementation behaves as
20504         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
20505         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
20506         * the case of no accessibility delegate been set.
20507         * </p>
20508         *
20509         * @param host The View hosting the delegate.
20510         * @param event The event to initialize.
20511         *
20512         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
20513         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
20514         */
20515        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
20516            host.onInitializeAccessibilityEventInternal(event);
20517        }
20518
20519        /**
20520         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
20521         * <p>
20522         * The default implementation behaves as
20523         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
20524         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
20525         * the case of no accessibility delegate been set.
20526         * </p>
20527         *
20528         * @param host The View hosting the delegate.
20529         * @param info The instance to initialize.
20530         *
20531         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
20532         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
20533         */
20534        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
20535            host.onInitializeAccessibilityNodeInfoInternal(info);
20536        }
20537
20538        /**
20539         * Called when a child of the host View has requested sending an
20540         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
20541         * to augment the event.
20542         * <p>
20543         * The default implementation behaves as
20544         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
20545         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
20546         * the case of no accessibility delegate been set.
20547         * </p>
20548         *
20549         * @param host The View hosting the delegate.
20550         * @param child The child which requests sending the event.
20551         * @param event The event to be sent.
20552         * @return True if the event should be sent
20553         *
20554         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
20555         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
20556         */
20557        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
20558                AccessibilityEvent event) {
20559            return host.onRequestSendAccessibilityEventInternal(child, event);
20560        }
20561
20562        /**
20563         * Gets the provider for managing a virtual view hierarchy rooted at this View
20564         * and reported to {@link android.accessibilityservice.AccessibilityService}s
20565         * that explore the window content.
20566         * <p>
20567         * The default implementation behaves as
20568         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
20569         * the case of no accessibility delegate been set.
20570         * </p>
20571         *
20572         * @return The provider.
20573         *
20574         * @see AccessibilityNodeProvider
20575         */
20576        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
20577            return null;
20578        }
20579
20580        /**
20581         * Returns an {@link AccessibilityNodeInfo} representing the host view from the
20582         * point of view of an {@link android.accessibilityservice.AccessibilityService}.
20583         * This method is responsible for obtaining an accessibility node info from a
20584         * pool of reusable instances and calling
20585         * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host
20586         * view to initialize the former.
20587         * <p>
20588         * <strong>Note:</strong> The client is responsible for recycling the obtained
20589         * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object
20590         * creation.
20591         * </p>
20592         * <p>
20593         * The default implementation behaves as
20594         * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for
20595         * the case of no accessibility delegate been set.
20596         * </p>
20597         * @return A populated {@link AccessibilityNodeInfo}.
20598         *
20599         * @see AccessibilityNodeInfo
20600         *
20601         * @hide
20602         */
20603        public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) {
20604            return host.createAccessibilityNodeInfoInternal();
20605        }
20606    }
20607
20608    private class MatchIdPredicate implements Predicate<View> {
20609        public int mId;
20610
20611        @Override
20612        public boolean apply(View view) {
20613            return (view.mID == mId);
20614        }
20615    }
20616
20617    private class MatchLabelForPredicate implements Predicate<View> {
20618        private int mLabeledId;
20619
20620        @Override
20621        public boolean apply(View view) {
20622            return (view.mLabelForId == mLabeledId);
20623        }
20624    }
20625
20626    private class SendViewStateChangedAccessibilityEvent implements Runnable {
20627        private int mChangeTypes = 0;
20628        private boolean mPosted;
20629        private boolean mPostedWithDelay;
20630        private long mLastEventTimeMillis;
20631
20632        @Override
20633        public void run() {
20634            mPosted = false;
20635            mPostedWithDelay = false;
20636            mLastEventTimeMillis = SystemClock.uptimeMillis();
20637            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
20638                final AccessibilityEvent event = AccessibilityEvent.obtain();
20639                event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
20640                event.setContentChangeTypes(mChangeTypes);
20641                sendAccessibilityEventUnchecked(event);
20642            }
20643            mChangeTypes = 0;
20644        }
20645
20646        public void runOrPost(int changeType) {
20647            mChangeTypes |= changeType;
20648
20649            // If this is a live region or the child of a live region, collect
20650            // all events from this frame and send them on the next frame.
20651            if (inLiveRegion()) {
20652                // If we're already posted with a delay, remove that.
20653                if (mPostedWithDelay) {
20654                    removeCallbacks(this);
20655                    mPostedWithDelay = false;
20656                }
20657                // Only post if we're not already posted.
20658                if (!mPosted) {
20659                    post(this);
20660                    mPosted = true;
20661                }
20662                return;
20663            }
20664
20665            if (mPosted) {
20666                return;
20667            }
20668
20669            final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
20670            final long minEventIntevalMillis =
20671                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
20672            if (timeSinceLastMillis >= minEventIntevalMillis) {
20673                removeCallbacks(this);
20674                run();
20675            } else {
20676                postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
20677                mPostedWithDelay = true;
20678            }
20679        }
20680    }
20681
20682    private boolean inLiveRegion() {
20683        if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) {
20684            return true;
20685        }
20686
20687        ViewParent parent = getParent();
20688        while (parent instanceof View) {
20689            if (((View) parent).getAccessibilityLiveRegion()
20690                    != View.ACCESSIBILITY_LIVE_REGION_NONE) {
20691                return true;
20692            }
20693            parent = parent.getParent();
20694        }
20695
20696        return false;
20697    }
20698
20699    /**
20700     * Dump all private flags in readable format, useful for documentation and
20701     * sanity checking.
20702     */
20703    private static void dumpFlags() {
20704        final HashMap<String, String> found = Maps.newHashMap();
20705        try {
20706            for (Field field : View.class.getDeclaredFields()) {
20707                final int modifiers = field.getModifiers();
20708                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
20709                    if (field.getType().equals(int.class)) {
20710                        final int value = field.getInt(null);
20711                        dumpFlag(found, field.getName(), value);
20712                    } else if (field.getType().equals(int[].class)) {
20713                        final int[] values = (int[]) field.get(null);
20714                        for (int i = 0; i < values.length; i++) {
20715                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
20716                        }
20717                    }
20718                }
20719            }
20720        } catch (IllegalAccessException e) {
20721            throw new RuntimeException(e);
20722        }
20723
20724        final ArrayList<String> keys = Lists.newArrayList();
20725        keys.addAll(found.keySet());
20726        Collections.sort(keys);
20727        for (String key : keys) {
20728            Log.d(VIEW_LOG_TAG, found.get(key));
20729        }
20730    }
20731
20732    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
20733        // Sort flags by prefix, then by bits, always keeping unique keys
20734        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
20735        final int prefix = name.indexOf('_');
20736        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
20737        final String output = bits + " " + name;
20738        found.put(key, output);
20739    }
20740}
20741