View.java revision 30794097acd0911ca481a2636bfa62d8514edbcf
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.RevealAnimator;
21import android.animation.StateListAnimator;
22import android.animation.ValueAnimator;
23import android.annotation.IntDef;
24import android.annotation.NonNull;
25import android.annotation.Nullable;
26import android.content.ClipData;
27import android.content.Context;
28import android.content.res.Configuration;
29import android.content.res.Resources;
30import android.content.res.TypedArray;
31import android.graphics.Bitmap;
32import android.graphics.Canvas;
33import android.graphics.Insets;
34import android.graphics.Interpolator;
35import android.graphics.LinearGradient;
36import android.graphics.Matrix;
37import android.graphics.Outline;
38import android.graphics.Paint;
39import android.graphics.PixelFormat;
40import android.graphics.Point;
41import android.graphics.PorterDuff;
42import android.graphics.PorterDuffXfermode;
43import android.graphics.Rect;
44import android.graphics.RectF;
45import android.graphics.Region;
46import android.graphics.Shader;
47import android.graphics.drawable.ColorDrawable;
48import android.graphics.drawable.Drawable;
49import android.hardware.display.DisplayManagerGlobal;
50import android.os.Bundle;
51import android.os.Handler;
52import android.os.IBinder;
53import android.os.Parcel;
54import android.os.Parcelable;
55import android.os.RemoteException;
56import android.os.SystemClock;
57import android.os.SystemProperties;
58import android.text.TextUtils;
59import android.util.AttributeSet;
60import android.util.FloatProperty;
61import android.util.LayoutDirection;
62import android.util.Log;
63import android.util.LongSparseLongArray;
64import android.util.Pools.SynchronizedPool;
65import android.util.Property;
66import android.util.SparseArray;
67import android.util.SuperNotCalledException;
68import android.util.TypedValue;
69import android.view.ContextMenu.ContextMenuInfo;
70import android.view.AccessibilityIterators.TextSegmentIterator;
71import android.view.AccessibilityIterators.CharacterTextSegmentIterator;
72import android.view.AccessibilityIterators.WordTextSegmentIterator;
73import android.view.AccessibilityIterators.ParagraphTextSegmentIterator;
74import android.view.accessibility.AccessibilityEvent;
75import android.view.accessibility.AccessibilityEventSource;
76import android.view.accessibility.AccessibilityManager;
77import android.view.accessibility.AccessibilityNodeInfo;
78import android.view.accessibility.AccessibilityNodeProvider;
79import android.view.animation.Animation;
80import android.view.animation.AnimationUtils;
81import android.view.animation.Transformation;
82import android.view.inputmethod.EditorInfo;
83import android.view.inputmethod.InputConnection;
84import android.view.inputmethod.InputMethodManager;
85import android.widget.ScrollBarDrawable;
86
87import static android.os.Build.VERSION_CODES.*;
88import static java.lang.Math.max;
89
90import com.android.internal.R;
91import com.android.internal.util.Predicate;
92import com.android.internal.view.menu.MenuBuilder;
93
94import com.google.android.collect.Lists;
95import com.google.android.collect.Maps;
96
97import java.lang.annotation.Retention;
98import java.lang.annotation.RetentionPolicy;
99import java.lang.ref.WeakReference;
100import java.lang.reflect.Field;
101import java.lang.reflect.InvocationTargetException;
102import java.lang.reflect.Method;
103import java.lang.reflect.Modifier;
104import java.util.ArrayList;
105import java.util.Arrays;
106import java.util.Collections;
107import java.util.HashMap;
108import java.util.List;
109import java.util.Locale;
110import java.util.Map;
111import java.util.concurrent.CopyOnWriteArrayList;
112import java.util.concurrent.atomic.AtomicInteger;
113
114/**
115 * <p>
116 * This class represents the basic building block for user interface components. A View
117 * occupies a rectangular area on the screen and is responsible for drawing and
118 * event handling. View is the base class for <em>widgets</em>, which are
119 * used to create interactive UI components (buttons, text fields, etc.). The
120 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
121 * are invisible containers that hold other Views (or other ViewGroups) and define
122 * their layout properties.
123 * </p>
124 *
125 * <div class="special reference">
126 * <h3>Developer Guides</h3>
127 * <p>For information about using this class to develop your application's user interface,
128 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
129 * </div>
130 *
131 * <a name="Using"></a>
132 * <h3>Using Views</h3>
133 * <p>
134 * All of the views in a window are arranged in a single tree. You can add views
135 * either from code or by specifying a tree of views in one or more XML layout
136 * files. There are many specialized subclasses of views that act as controls or
137 * are capable of displaying text, images, or other content.
138 * </p>
139 * <p>
140 * Once you have created a tree of views, there are typically a few types of
141 * common operations you may wish to perform:
142 * <ul>
143 * <li><strong>Set properties:</strong> for example setting the text of a
144 * {@link android.widget.TextView}. The available properties and the methods
145 * that set them will vary among the different subclasses of views. Note that
146 * properties that are known at build time can be set in the XML layout
147 * files.</li>
148 * <li><strong>Set focus:</strong> The framework will handled moving focus in
149 * response to user input. To force focus to a specific view, call
150 * {@link #requestFocus}.</li>
151 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
152 * that will be notified when something interesting happens to the view. For
153 * example, all views will let you set a listener to be notified when the view
154 * gains or loses focus. You can register such a listener using
155 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
156 * Other view subclasses offer more specialized listeners. For example, a Button
157 * exposes a listener to notify clients when the button is clicked.</li>
158 * <li><strong>Set visibility:</strong> You can hide or show views using
159 * {@link #setVisibility(int)}.</li>
160 * </ul>
161 * </p>
162 * <p><em>
163 * Note: The Android framework is responsible for measuring, laying out and
164 * drawing views. You should not call methods that perform these actions on
165 * views yourself unless you are actually implementing a
166 * {@link android.view.ViewGroup}.
167 * </em></p>
168 *
169 * <a name="Lifecycle"></a>
170 * <h3>Implementing a Custom View</h3>
171 *
172 * <p>
173 * To implement a custom view, you will usually begin by providing overrides for
174 * some of the standard methods that the framework calls on all views. You do
175 * not need to override all of these methods. In fact, you can start by just
176 * overriding {@link #onDraw(android.graphics.Canvas)}.
177 * <table border="2" width="85%" align="center" cellpadding="5">
178 *     <thead>
179 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
180 *     </thead>
181 *
182 *     <tbody>
183 *     <tr>
184 *         <td rowspan="2">Creation</td>
185 *         <td>Constructors</td>
186 *         <td>There is a form of the constructor that are called when the view
187 *         is created from code and a form that is called when the view is
188 *         inflated from a layout file. The second form should parse and apply
189 *         any attributes defined in the layout file.
190 *         </td>
191 *     </tr>
192 *     <tr>
193 *         <td><code>{@link #onFinishInflate()}</code></td>
194 *         <td>Called after a view and all of its children has been inflated
195 *         from XML.</td>
196 *     </tr>
197 *
198 *     <tr>
199 *         <td rowspan="3">Layout</td>
200 *         <td><code>{@link #onMeasure(int, int)}</code></td>
201 *         <td>Called to determine the size requirements for this view and all
202 *         of its children.
203 *         </td>
204 *     </tr>
205 *     <tr>
206 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
207 *         <td>Called when this view should assign a size and position to all
208 *         of its children.
209 *         </td>
210 *     </tr>
211 *     <tr>
212 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
213 *         <td>Called when the size of this view has changed.
214 *         </td>
215 *     </tr>
216 *
217 *     <tr>
218 *         <td>Drawing</td>
219 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
220 *         <td>Called when the view should render its content.
221 *         </td>
222 *     </tr>
223 *
224 *     <tr>
225 *         <td rowspan="4">Event processing</td>
226 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
227 *         <td>Called when a new hardware key event occurs.
228 *         </td>
229 *     </tr>
230 *     <tr>
231 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
232 *         <td>Called when a hardware key up event occurs.
233 *         </td>
234 *     </tr>
235 *     <tr>
236 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
237 *         <td>Called when a trackball motion event occurs.
238 *         </td>
239 *     </tr>
240 *     <tr>
241 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
242 *         <td>Called when a touch screen motion event occurs.
243 *         </td>
244 *     </tr>
245 *
246 *     <tr>
247 *         <td rowspan="2">Focus</td>
248 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
249 *         <td>Called when the view gains or loses focus.
250 *         </td>
251 *     </tr>
252 *
253 *     <tr>
254 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
255 *         <td>Called when the window containing the view gains or loses focus.
256 *         </td>
257 *     </tr>
258 *
259 *     <tr>
260 *         <td rowspan="3">Attaching</td>
261 *         <td><code>{@link #onAttachedToWindow()}</code></td>
262 *         <td>Called when the view is attached to a window.
263 *         </td>
264 *     </tr>
265 *
266 *     <tr>
267 *         <td><code>{@link #onDetachedFromWindow}</code></td>
268 *         <td>Called when the view is detached from its window.
269 *         </td>
270 *     </tr>
271 *
272 *     <tr>
273 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
274 *         <td>Called when the visibility of the window containing the view
275 *         has changed.
276 *         </td>
277 *     </tr>
278 *     </tbody>
279 *
280 * </table>
281 * </p>
282 *
283 * <a name="IDs"></a>
284 * <h3>IDs</h3>
285 * Views may have an integer id associated with them. These ids are typically
286 * assigned in the layout XML files, and are used to find specific views within
287 * the view tree. A common pattern is to:
288 * <ul>
289 * <li>Define a Button in the layout file and assign it a unique ID.
290 * <pre>
291 * &lt;Button
292 *     android:id="@+id/my_button"
293 *     android:layout_width="wrap_content"
294 *     android:layout_height="wrap_content"
295 *     android:text="@string/my_button_text"/&gt;
296 * </pre></li>
297 * <li>From the onCreate method of an Activity, find the Button
298 * <pre class="prettyprint">
299 *      Button myButton = (Button) findViewById(R.id.my_button);
300 * </pre></li>
301 * </ul>
302 * <p>
303 * View IDs need not be unique throughout the tree, but it is good practice to
304 * ensure that they are at least unique within the part of the tree you are
305 * searching.
306 * </p>
307 *
308 * <a name="Position"></a>
309 * <h3>Position</h3>
310 * <p>
311 * The geometry of a view is that of a rectangle. A view has a location,
312 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
313 * two dimensions, expressed as a width and a height. The unit for location
314 * and dimensions is the pixel.
315 * </p>
316 *
317 * <p>
318 * It is possible to retrieve the location of a view by invoking the methods
319 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
320 * coordinate of the rectangle representing the view. The latter returns the
321 * top, or Y, coordinate of the rectangle representing the view. These methods
322 * both return the location of the view relative to its parent. For instance,
323 * when getLeft() returns 20, that means the view is located 20 pixels to the
324 * right of the left edge of its direct parent.
325 * </p>
326 *
327 * <p>
328 * In addition, several convenience methods are offered to avoid unnecessary
329 * computations, namely {@link #getRight()} and {@link #getBottom()}.
330 * These methods return the coordinates of the right and bottom edges of the
331 * rectangle representing the view. For instance, calling {@link #getRight()}
332 * is similar to the following computation: <code>getLeft() + getWidth()</code>
333 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
334 * </p>
335 *
336 * <a name="SizePaddingMargins"></a>
337 * <h3>Size, padding and margins</h3>
338 * <p>
339 * The size of a view is expressed with a width and a height. A view actually
340 * possess two pairs of width and height values.
341 * </p>
342 *
343 * <p>
344 * The first pair is known as <em>measured width</em> and
345 * <em>measured height</em>. These dimensions define how big a view wants to be
346 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
347 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
348 * and {@link #getMeasuredHeight()}.
349 * </p>
350 *
351 * <p>
352 * The second pair is simply known as <em>width</em> and <em>height</em>, or
353 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
354 * dimensions define the actual size of the view on screen, at drawing time and
355 * after layout. These values may, but do not have to, be different from the
356 * measured width and height. The width and height can be obtained by calling
357 * {@link #getWidth()} and {@link #getHeight()}.
358 * </p>
359 *
360 * <p>
361 * To measure its dimensions, a view takes into account its padding. The padding
362 * is expressed in pixels for the left, top, right and bottom parts of the view.
363 * Padding can be used to offset the content of the view by a specific amount of
364 * pixels. For instance, a left padding of 2 will push the view's content by
365 * 2 pixels to the right of the left edge. Padding can be set using the
366 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)}
367 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()},
368 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()},
369 * {@link #getPaddingEnd()}.
370 * </p>
371 *
372 * <p>
373 * Even though a view can define a padding, it does not provide any support for
374 * margins. However, view groups provide such a support. Refer to
375 * {@link android.view.ViewGroup} and
376 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
377 * </p>
378 *
379 * <a name="Layout"></a>
380 * <h3>Layout</h3>
381 * <p>
382 * Layout is a two pass process: a measure pass and a layout pass. The measuring
383 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
384 * of the view tree. Each view pushes dimension specifications down the tree
385 * during the recursion. At the end of the measure pass, every view has stored
386 * its measurements. The second pass happens in
387 * {@link #layout(int,int,int,int)} and is also top-down. During
388 * this pass each parent is responsible for positioning all of its children
389 * using the sizes computed in the measure pass.
390 * </p>
391 *
392 * <p>
393 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
394 * {@link #getMeasuredHeight()} values must be set, along with those for all of
395 * that view's descendants. A view's measured width and measured height values
396 * must respect the constraints imposed by the view's parents. This guarantees
397 * that at the end of the measure pass, all parents accept all of their
398 * children's measurements. A parent view may call measure() more than once on
399 * its children. For example, the parent may measure each child once with
400 * unspecified dimensions to find out how big they want to be, then call
401 * measure() on them again with actual numbers if the sum of all the children's
402 * unconstrained sizes is too big or too small.
403 * </p>
404 *
405 * <p>
406 * The measure pass uses two classes to communicate dimensions. The
407 * {@link MeasureSpec} class is used by views to tell their parents how they
408 * want to be measured and positioned. The base LayoutParams class just
409 * describes how big the view wants to be for both width and height. For each
410 * dimension, it can specify one of:
411 * <ul>
412 * <li> an exact number
413 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
414 * (minus padding)
415 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
416 * enclose its content (plus padding).
417 * </ul>
418 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
419 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
420 * an X and Y value.
421 * </p>
422 *
423 * <p>
424 * MeasureSpecs are used to push requirements down the tree from parent to
425 * child. A MeasureSpec can be in one of three modes:
426 * <ul>
427 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
428 * of a child view. For example, a LinearLayout may call measure() on its child
429 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
430 * tall the child view wants to be given a width of 240 pixels.
431 * <li>EXACTLY: This is used by the parent to impose an exact size on the
432 * child. The child must use this size, and guarantee that all of its
433 * descendants will fit within this size.
434 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
435 * child. The child must guarantee that it and all of its descendants will fit
436 * within this size.
437 * </ul>
438 * </p>
439 *
440 * <p>
441 * To intiate a layout, call {@link #requestLayout}. This method is typically
442 * called by a view on itself when it believes that is can no longer fit within
443 * its current bounds.
444 * </p>
445 *
446 * <a name="Drawing"></a>
447 * <h3>Drawing</h3>
448 * <p>
449 * Drawing is handled by walking the tree and rendering each view that
450 * intersects the invalid region. Because the tree is traversed in-order,
451 * this means that parents will draw before (i.e., behind) their children, with
452 * siblings drawn in the order they appear in the tree.
453 * If you set a background drawable for a View, then the View will draw it for you
454 * before calling back to its <code>onDraw()</code> method.
455 * </p>
456 *
457 * <p>
458 * Note that the framework will not draw views that are not in the invalid region.
459 * </p>
460 *
461 * <p>
462 * To force a view to draw, call {@link #invalidate()}.
463 * </p>
464 *
465 * <a name="EventHandlingThreading"></a>
466 * <h3>Event Handling and Threading</h3>
467 * <p>
468 * The basic cycle of a view is as follows:
469 * <ol>
470 * <li>An event comes in and is dispatched to the appropriate view. The view
471 * handles the event and notifies any listeners.</li>
472 * <li>If in the course of processing the event, the view's bounds may need
473 * to be changed, the view will call {@link #requestLayout()}.</li>
474 * <li>Similarly, if in the course of processing the event the view's appearance
475 * may need to be changed, the view will call {@link #invalidate()}.</li>
476 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
477 * the framework will take care of measuring, laying out, and drawing the tree
478 * as appropriate.</li>
479 * </ol>
480 * </p>
481 *
482 * <p><em>Note: The entire view tree is single threaded. You must always be on
483 * the UI thread when calling any method on any view.</em>
484 * If you are doing work on other threads and want to update the state of a view
485 * from that thread, you should use a {@link Handler}.
486 * </p>
487 *
488 * <a name="FocusHandling"></a>
489 * <h3>Focus Handling</h3>
490 * <p>
491 * The framework will handle routine focus movement in response to user input.
492 * This includes changing the focus as views are removed or hidden, or as new
493 * views become available. Views indicate their willingness to take focus
494 * through the {@link #isFocusable} method. To change whether a view can take
495 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
496 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
497 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
498 * </p>
499 * <p>
500 * Focus movement is based on an algorithm which finds the nearest neighbor in a
501 * given direction. In rare cases, the default algorithm may not match the
502 * intended behavior of the developer. In these situations, you can provide
503 * explicit overrides by using these XML attributes in the layout file:
504 * <pre>
505 * nextFocusDown
506 * nextFocusLeft
507 * nextFocusRight
508 * nextFocusUp
509 * </pre>
510 * </p>
511 *
512 *
513 * <p>
514 * To get a particular view to take focus, call {@link #requestFocus()}.
515 * </p>
516 *
517 * <a name="TouchMode"></a>
518 * <h3>Touch Mode</h3>
519 * <p>
520 * When a user is navigating a user interface via directional keys such as a D-pad, it is
521 * necessary to give focus to actionable items such as buttons so the user can see
522 * what will take input.  If the device has touch capabilities, however, and the user
523 * begins interacting with the interface by touching it, it is no longer necessary to
524 * always highlight, or give focus to, a particular view.  This motivates a mode
525 * for interaction named 'touch mode'.
526 * </p>
527 * <p>
528 * For a touch capable device, once the user touches the screen, the device
529 * will enter touch mode.  From this point onward, only views for which
530 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
531 * Other views that are touchable, like buttons, will not take focus when touched; they will
532 * only fire the on click listeners.
533 * </p>
534 * <p>
535 * Any time a user hits a directional key, such as a D-pad direction, the view device will
536 * exit touch mode, and find a view to take focus, so that the user may resume interacting
537 * with the user interface without touching the screen again.
538 * </p>
539 * <p>
540 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
541 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
542 * </p>
543 *
544 * <a name="Scrolling"></a>
545 * <h3>Scrolling</h3>
546 * <p>
547 * The framework provides basic support for views that wish to internally
548 * scroll their content. This includes keeping track of the X and Y scroll
549 * offset as well as mechanisms for drawing scrollbars. See
550 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
551 * {@link #awakenScrollBars()} for more details.
552 * </p>
553 *
554 * <a name="Tags"></a>
555 * <h3>Tags</h3>
556 * <p>
557 * Unlike IDs, tags are not used to identify views. Tags are essentially an
558 * extra piece of information that can be associated with a view. They are most
559 * often used as a convenience to store data related to views in the views
560 * themselves rather than by putting them in a separate structure.
561 * </p>
562 *
563 * <a name="Properties"></a>
564 * <h3>Properties</h3>
565 * <p>
566 * The View class exposes an {@link #ALPHA} property, as well as several transform-related
567 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are
568 * available both in the {@link Property} form as well as in similarly-named setter/getter
569 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can
570 * be used to set persistent state associated with these rendering-related properties on the view.
571 * The properties and methods can also be used in conjunction with
572 * {@link android.animation.Animator Animator}-based animations, described more in the
573 * <a href="#Animation">Animation</a> section.
574 * </p>
575 *
576 * <a name="Animation"></a>
577 * <h3>Animation</h3>
578 * <p>
579 * Starting with Android 3.0, the preferred way of animating views is to use the
580 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based
581 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and
582 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0
583 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only
584 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class
585 * makes animating these View properties particularly easy and efficient.
586 * </p>
587 * <p>
588 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered.
589 * You can attach an {@link Animation} object to a view using
590 * {@link #setAnimation(Animation)} or
591 * {@link #startAnimation(Animation)}. The animation can alter the scale,
592 * rotation, translation and alpha of a view over time. If the animation is
593 * attached to a view that has children, the animation will affect the entire
594 * subtree rooted by that node. When an animation is started, the framework will
595 * take care of redrawing the appropriate views until the animation completes.
596 * </p>
597 *
598 * <a name="Security"></a>
599 * <h3>Security</h3>
600 * <p>
601 * Sometimes it is essential that an application be able to verify that an action
602 * is being performed with the full knowledge and consent of the user, such as
603 * granting a permission request, making a purchase or clicking on an advertisement.
604 * Unfortunately, a malicious application could try to spoof the user into
605 * performing these actions, unaware, by concealing the intended purpose of the view.
606 * As a remedy, the framework offers a touch filtering mechanism that can be used to
607 * improve the security of views that provide access to sensitive functionality.
608 * </p><p>
609 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
610 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
611 * will discard touches that are received whenever the view's window is obscured by
612 * another visible window.  As a result, the view will not receive touches whenever a
613 * toast, dialog or other window appears above the view's window.
614 * </p><p>
615 * For more fine-grained control over security, consider overriding the
616 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
617 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
618 * </p>
619 *
620 * @attr ref android.R.styleable#View_alpha
621 * @attr ref android.R.styleable#View_background
622 * @attr ref android.R.styleable#View_clickable
623 * @attr ref android.R.styleable#View_contentDescription
624 * @attr ref android.R.styleable#View_drawingCacheQuality
625 * @attr ref android.R.styleable#View_duplicateParentState
626 * @attr ref android.R.styleable#View_id
627 * @attr ref android.R.styleable#View_requiresFadingEdge
628 * @attr ref android.R.styleable#View_fadeScrollbars
629 * @attr ref android.R.styleable#View_fadingEdgeLength
630 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
631 * @attr ref android.R.styleable#View_fitsSystemWindows
632 * @attr ref android.R.styleable#View_isScrollContainer
633 * @attr ref android.R.styleable#View_focusable
634 * @attr ref android.R.styleable#View_focusableInTouchMode
635 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
636 * @attr ref android.R.styleable#View_keepScreenOn
637 * @attr ref android.R.styleable#View_layerType
638 * @attr ref android.R.styleable#View_layoutDirection
639 * @attr ref android.R.styleable#View_longClickable
640 * @attr ref android.R.styleable#View_minHeight
641 * @attr ref android.R.styleable#View_minWidth
642 * @attr ref android.R.styleable#View_nextFocusDown
643 * @attr ref android.R.styleable#View_nextFocusLeft
644 * @attr ref android.R.styleable#View_nextFocusRight
645 * @attr ref android.R.styleable#View_nextFocusUp
646 * @attr ref android.R.styleable#View_onClick
647 * @attr ref android.R.styleable#View_padding
648 * @attr ref android.R.styleable#View_paddingBottom
649 * @attr ref android.R.styleable#View_paddingLeft
650 * @attr ref android.R.styleable#View_paddingRight
651 * @attr ref android.R.styleable#View_paddingTop
652 * @attr ref android.R.styleable#View_paddingStart
653 * @attr ref android.R.styleable#View_paddingEnd
654 * @attr ref android.R.styleable#View_saveEnabled
655 * @attr ref android.R.styleable#View_rotation
656 * @attr ref android.R.styleable#View_rotationX
657 * @attr ref android.R.styleable#View_rotationY
658 * @attr ref android.R.styleable#View_scaleX
659 * @attr ref android.R.styleable#View_scaleY
660 * @attr ref android.R.styleable#View_scrollX
661 * @attr ref android.R.styleable#View_scrollY
662 * @attr ref android.R.styleable#View_scrollbarSize
663 * @attr ref android.R.styleable#View_scrollbarStyle
664 * @attr ref android.R.styleable#View_scrollbars
665 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
666 * @attr ref android.R.styleable#View_scrollbarFadeDuration
667 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
668 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
669 * @attr ref android.R.styleable#View_scrollbarThumbVertical
670 * @attr ref android.R.styleable#View_scrollbarTrackVertical
671 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
672 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
673 * @attr ref android.R.styleable#View_stateListAnimator
674 * @attr ref android.R.styleable#View_viewName
675 * @attr ref android.R.styleable#View_soundEffectsEnabled
676 * @attr ref android.R.styleable#View_tag
677 * @attr ref android.R.styleable#View_textAlignment
678 * @attr ref android.R.styleable#View_textDirection
679 * @attr ref android.R.styleable#View_transformPivotX
680 * @attr ref android.R.styleable#View_transformPivotY
681 * @attr ref android.R.styleable#View_translationX
682 * @attr ref android.R.styleable#View_translationY
683 * @attr ref android.R.styleable#View_translationZ
684 * @attr ref android.R.styleable#View_visibility
685 *
686 * @see android.view.ViewGroup
687 */
688public class View implements Drawable.Callback, KeyEvent.Callback,
689        AccessibilityEventSource {
690    private static final boolean DBG = false;
691
692    /**
693     * The logging tag used by this class with android.util.Log.
694     */
695    protected static final String VIEW_LOG_TAG = "View";
696
697    /**
698     * When set to true, apps will draw debugging information about their layouts.
699     *
700     * @hide
701     */
702    public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout";
703
704    /**
705     * Used to mark a View that has no ID.
706     */
707    public static final int NO_ID = -1;
708
709    /**
710     * Signals that compatibility booleans have been initialized according to
711     * target SDK versions.
712     */
713    private static boolean sCompatibilityDone = false;
714
715    /**
716     * Use the old (broken) way of building MeasureSpecs.
717     */
718    private static boolean sUseBrokenMakeMeasureSpec = false;
719
720    /**
721     * Ignore any optimizations using the measure cache.
722     */
723    private static boolean sIgnoreMeasureCache = false;
724
725    /**
726     * Ignore the clipBounds of this view for the children.
727     */
728    static boolean sIgnoreClipBoundsForChildren = 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 a view's outline has been specifically defined.
2383     */
2384    static final int PFLAG3_OUTLINE_DEFINED = 0x20;
2385
2386    /**
2387     * Flag indicating that we're in the process of applying window insets.
2388     */
2389    static final int PFLAG3_APPLYING_INSETS = 0x40;
2390
2391    /**
2392     * Flag indicating that we're in the process of fitting system windows using the old method.
2393     */
2394    static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x80;
2395
2396    /**
2397     * Flag indicating that nested scrolling is enabled for this view.
2398     * The view will optionally cooperate with views up its parent chain to allow for
2399     * integrated nested scrolling along the same axis.
2400     */
2401    static final int PFLAG3_NESTED_SCROLLING_ENABLED = 0x200;
2402
2403    /* End of masks for mPrivateFlags3 */
2404
2405    static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED;
2406
2407    /**
2408     * Always allow a user to over-scroll this view, provided it is a
2409     * view that can scroll.
2410     *
2411     * @see #getOverScrollMode()
2412     * @see #setOverScrollMode(int)
2413     */
2414    public static final int OVER_SCROLL_ALWAYS = 0;
2415
2416    /**
2417     * Allow a user to over-scroll this view only if the content is large
2418     * enough to meaningfully scroll, provided it is a view that can scroll.
2419     *
2420     * @see #getOverScrollMode()
2421     * @see #setOverScrollMode(int)
2422     */
2423    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2424
2425    /**
2426     * Never allow a user to over-scroll this view.
2427     *
2428     * @see #getOverScrollMode()
2429     * @see #setOverScrollMode(int)
2430     */
2431    public static final int OVER_SCROLL_NEVER = 2;
2432
2433    /**
2434     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2435     * requested the system UI (status bar) to be visible (the default).
2436     *
2437     * @see #setSystemUiVisibility(int)
2438     */
2439    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2440
2441    /**
2442     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2443     * system UI to enter an unobtrusive "low profile" mode.
2444     *
2445     * <p>This is for use in games, book readers, video players, or any other
2446     * "immersive" application where the usual system chrome is deemed too distracting.
2447     *
2448     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2449     *
2450     * @see #setSystemUiVisibility(int)
2451     */
2452    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2453
2454    /**
2455     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2456     * system navigation be temporarily hidden.
2457     *
2458     * <p>This is an even less obtrusive state than that called for by
2459     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2460     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2461     * those to disappear. This is useful (in conjunction with the
2462     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2463     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2464     * window flags) for displaying content using every last pixel on the display.
2465     *
2466     * <p>There is a limitation: because navigation controls are so important, the least user
2467     * interaction will cause them to reappear immediately.  When this happens, both
2468     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2469     * so that both elements reappear at the same time.
2470     *
2471     * @see #setSystemUiVisibility(int)
2472     */
2473    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2474
2475    /**
2476     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2477     * into the normal fullscreen mode so that its content can take over the screen
2478     * while still allowing the user to interact with the application.
2479     *
2480     * <p>This has the same visual effect as
2481     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2482     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2483     * meaning that non-critical screen decorations (such as the status bar) will be
2484     * hidden while the user is in the View's window, focusing the experience on
2485     * that content.  Unlike the window flag, if you are using ActionBar in
2486     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2487     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2488     * hide the action bar.
2489     *
2490     * <p>This approach to going fullscreen is best used over the window flag when
2491     * it is a transient state -- that is, the application does this at certain
2492     * points in its user interaction where it wants to allow the user to focus
2493     * on content, but not as a continuous state.  For situations where the application
2494     * would like to simply stay full screen the entire time (such as a game that
2495     * wants to take over the screen), the
2496     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2497     * is usually a better approach.  The state set here will be removed by the system
2498     * in various situations (such as the user moving to another application) like
2499     * the other system UI states.
2500     *
2501     * <p>When using this flag, the application should provide some easy facility
2502     * for the user to go out of it.  A common example would be in an e-book
2503     * reader, where tapping on the screen brings back whatever screen and UI
2504     * decorations that had been hidden while the user was immersed in reading
2505     * the book.
2506     *
2507     * @see #setSystemUiVisibility(int)
2508     */
2509    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2510
2511    /**
2512     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2513     * flags, we would like a stable view of the content insets given to
2514     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2515     * will always represent the worst case that the application can expect
2516     * as a continuous state.  In the stock Android UI this is the space for
2517     * the system bar, nav bar, and status bar, but not more transient elements
2518     * such as an input method.
2519     *
2520     * The stable layout your UI sees is based on the system UI modes you can
2521     * switch to.  That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
2522     * then you will get a stable layout for changes of the
2523     * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
2524     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
2525     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
2526     * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
2527     * with a stable layout.  (Note that you should avoid using
2528     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
2529     *
2530     * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN}
2531     * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
2532     * then a hidden status bar will be considered a "stable" state for purposes
2533     * here.  This allows your UI to continually hide the status bar, while still
2534     * using the system UI flags to hide the action bar while still retaining
2535     * a stable layout.  Note that changing the window fullscreen flag will never
2536     * provide a stable layout for a clean transition.
2537     *
2538     * <p>If you are using ActionBar in
2539     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2540     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2541     * insets it adds to those given to the application.
2542     */
2543    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2544
2545    /**
2546     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2547     * to be layed out as if it has requested
2548     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2549     * allows it to avoid artifacts when switching in and out of that mode, at
2550     * the expense that some of its user interface may be covered by screen
2551     * decorations when they are shown.  You can perform layout of your inner
2552     * UI elements to account for the navigation system UI through the
2553     * {@link #fitSystemWindows(Rect)} method.
2554     */
2555    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2556
2557    /**
2558     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2559     * to be layed out as if it has requested
2560     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2561     * allows it to avoid artifacts when switching in and out of that mode, at
2562     * the expense that some of its user interface may be covered by screen
2563     * decorations when they are shown.  You can perform layout of your inner
2564     * UI elements to account for non-fullscreen system UI through the
2565     * {@link #fitSystemWindows(Rect)} method.
2566     */
2567    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2568
2569    /**
2570     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2571     * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  If this flag is
2572     * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any
2573     * user interaction.
2574     * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only
2575     * has an effect when used in combination with that flag.</p>
2576     */
2577    public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800;
2578
2579    /**
2580     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2581     * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation
2582     * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  Use this flag to create an immersive
2583     * experience while also hiding the system bars.  If this flag is not set,
2584     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user
2585     * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system
2586     * if the user swipes from the top of the screen.
2587     * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with
2588     * system gestures, such as swiping from the top of the screen.  These transient system bars
2589     * will overlay app’s content, may have some degree of transparency, and will automatically
2590     * hide after a short timeout.
2591     * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and
2592     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination
2593     * with one or both of those flags.</p>
2594     */
2595    public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000;
2596
2597    /**
2598     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2599     */
2600    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2601
2602    /**
2603     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2604     */
2605    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2606
2607    /**
2608     * @hide
2609     *
2610     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2611     * out of the public fields to keep the undefined bits out of the developer's way.
2612     *
2613     * Flag to make the status bar not expandable.  Unless you also
2614     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
2615     */
2616    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
2617
2618    /**
2619     * @hide
2620     *
2621     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2622     * out of the public fields to keep the undefined bits out of the developer's way.
2623     *
2624     * Flag to hide notification icons and scrolling ticker text.
2625     */
2626    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
2627
2628    /**
2629     * @hide
2630     *
2631     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2632     * out of the public fields to keep the undefined bits out of the developer's way.
2633     *
2634     * Flag to disable incoming notification alerts.  This will not block
2635     * icons, but it will block sound, vibrating and other visual or aural notifications.
2636     */
2637    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
2638
2639    /**
2640     * @hide
2641     *
2642     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2643     * out of the public fields to keep the undefined bits out of the developer's way.
2644     *
2645     * Flag to hide only the scrolling ticker.  Note that
2646     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
2647     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
2648     */
2649    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
2650
2651    /**
2652     * @hide
2653     *
2654     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2655     * out of the public fields to keep the undefined bits out of the developer's way.
2656     *
2657     * Flag to hide the center system info area.
2658     */
2659    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
2660
2661    /**
2662     * @hide
2663     *
2664     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2665     * out of the public fields to keep the undefined bits out of the developer's way.
2666     *
2667     * Flag to hide only the home button.  Don't use this
2668     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2669     */
2670    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
2671
2672    /**
2673     * @hide
2674     *
2675     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2676     * out of the public fields to keep the undefined bits out of the developer's way.
2677     *
2678     * Flag to hide only the back button. Don't use this
2679     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2680     */
2681    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
2682
2683    /**
2684     * @hide
2685     *
2686     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2687     * out of the public fields to keep the undefined bits out of the developer's way.
2688     *
2689     * Flag to hide only the clock.  You might use this if your activity has
2690     * its own clock making the status bar's clock redundant.
2691     */
2692    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
2693
2694    /**
2695     * @hide
2696     *
2697     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2698     * out of the public fields to keep the undefined bits out of the developer's way.
2699     *
2700     * Flag to hide only the recent apps button. Don't use this
2701     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2702     */
2703    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
2704
2705    /**
2706     * @hide
2707     *
2708     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2709     * out of the public fields to keep the undefined bits out of the developer's way.
2710     *
2711     * Flag to disable the global search gesture. Don't use this
2712     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2713     */
2714    public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000;
2715
2716    /**
2717     * @hide
2718     *
2719     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2720     * out of the public fields to keep the undefined bits out of the developer's way.
2721     *
2722     * Flag to specify that the status bar is displayed in transient mode.
2723     */
2724    public static final int STATUS_BAR_TRANSIENT = 0x04000000;
2725
2726    /**
2727     * @hide
2728     *
2729     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2730     * out of the public fields to keep the undefined bits out of the developer's way.
2731     *
2732     * Flag to specify that the navigation bar is displayed in transient mode.
2733     */
2734    public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000;
2735
2736    /**
2737     * @hide
2738     *
2739     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2740     * out of the public fields to keep the undefined bits out of the developer's way.
2741     *
2742     * Flag to specify that the hidden status bar would like to be shown.
2743     */
2744    public static final int STATUS_BAR_UNHIDE = 0x10000000;
2745
2746    /**
2747     * @hide
2748     *
2749     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2750     * out of the public fields to keep the undefined bits out of the developer's way.
2751     *
2752     * Flag to specify that the hidden navigation bar would like to be shown.
2753     */
2754    public static final int NAVIGATION_BAR_UNHIDE = 0x20000000;
2755
2756    /**
2757     * @hide
2758     *
2759     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2760     * out of the public fields to keep the undefined bits out of the developer's way.
2761     *
2762     * Flag to specify that the status bar is displayed in translucent mode.
2763     */
2764    public static final int STATUS_BAR_TRANSLUCENT = 0x40000000;
2765
2766    /**
2767     * @hide
2768     *
2769     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2770     * out of the public fields to keep the undefined bits out of the developer's way.
2771     *
2772     * Flag to specify that the navigation bar is displayed in translucent mode.
2773     */
2774    public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000;
2775
2776    /**
2777     * @hide
2778     *
2779     * Whether Recents is visible or not.
2780     */
2781    public static final int RECENT_APPS_VISIBLE = 0x00004000;
2782
2783    /**
2784     * @hide
2785     *
2786     * Makes system ui transparent.
2787     */
2788    public static final int SYSTEM_UI_TRANSPARENT = 0x00008000;
2789
2790    /**
2791     * @hide
2792     */
2793    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x00003FFF;
2794
2795    /**
2796     * These are the system UI flags that can be cleared by events outside
2797     * of an application.  Currently this is just the ability to tap on the
2798     * screen while hiding the navigation bar to have it return.
2799     * @hide
2800     */
2801    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
2802            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
2803            | SYSTEM_UI_FLAG_FULLSCREEN;
2804
2805    /**
2806     * Flags that can impact the layout in relation to system UI.
2807     */
2808    public static final int SYSTEM_UI_LAYOUT_FLAGS =
2809            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
2810            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
2811
2812    /** @hide */
2813    @IntDef(flag = true,
2814            value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION })
2815    @Retention(RetentionPolicy.SOURCE)
2816    public @interface FindViewFlags {}
2817
2818    /**
2819     * Find views that render the specified text.
2820     *
2821     * @see #findViewsWithText(ArrayList, CharSequence, int)
2822     */
2823    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
2824
2825    /**
2826     * Find find views that contain the specified content description.
2827     *
2828     * @see #findViewsWithText(ArrayList, CharSequence, int)
2829     */
2830    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
2831
2832    /**
2833     * Find views that contain {@link AccessibilityNodeProvider}. Such
2834     * a View is a root of virtual view hierarchy and may contain the searched
2835     * text. If this flag is set Views with providers are automatically
2836     * added and it is a responsibility of the client to call the APIs of
2837     * the provider to determine whether the virtual tree rooted at this View
2838     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
2839     * representing the virtual views with this text.
2840     *
2841     * @see #findViewsWithText(ArrayList, CharSequence, int)
2842     *
2843     * @hide
2844     */
2845    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
2846
2847    /**
2848     * The undefined cursor position.
2849     *
2850     * @hide
2851     */
2852    public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1;
2853
2854    /**
2855     * Indicates that the screen has changed state and is now off.
2856     *
2857     * @see #onScreenStateChanged(int)
2858     */
2859    public static final int SCREEN_STATE_OFF = 0x0;
2860
2861    /**
2862     * Indicates that the screen has changed state and is now on.
2863     *
2864     * @see #onScreenStateChanged(int)
2865     */
2866    public static final int SCREEN_STATE_ON = 0x1;
2867
2868    /**
2869     * Indicates no axis of view scrolling.
2870     */
2871    public static final int SCROLL_AXIS_NONE = 0;
2872
2873    /**
2874     * Indicates scrolling along the horizontal axis.
2875     */
2876    public static final int SCROLL_AXIS_HORIZONTAL = 1 << 0;
2877
2878    /**
2879     * Indicates scrolling along the vertical axis.
2880     */
2881    public static final int SCROLL_AXIS_VERTICAL = 1 << 1;
2882
2883    /**
2884     * Controls the over-scroll mode for this view.
2885     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
2886     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
2887     * and {@link #OVER_SCROLL_NEVER}.
2888     */
2889    private int mOverScrollMode;
2890
2891    /**
2892     * The parent this view is attached to.
2893     * {@hide}
2894     *
2895     * @see #getParent()
2896     */
2897    protected ViewParent mParent;
2898
2899    /**
2900     * {@hide}
2901     */
2902    AttachInfo mAttachInfo;
2903
2904    /**
2905     * {@hide}
2906     */
2907    @ViewDebug.ExportedProperty(flagMapping = {
2908        @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT,
2909                name = "FORCE_LAYOUT"),
2910        @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED,
2911                name = "LAYOUT_REQUIRED"),
2912        @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID,
2913            name = "DRAWING_CACHE_INVALID", outputIf = false),
2914        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true),
2915        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false),
2916        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
2917        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY")
2918    })
2919    int mPrivateFlags;
2920    int mPrivateFlags2;
2921    int mPrivateFlags3;
2922
2923    /**
2924     * This view's request for the visibility of the status bar.
2925     * @hide
2926     */
2927    @ViewDebug.ExportedProperty(flagMapping = {
2928        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
2929                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
2930                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
2931        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2932                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2933                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
2934        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
2935                                equals = SYSTEM_UI_FLAG_VISIBLE,
2936                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
2937    })
2938    int mSystemUiVisibility;
2939
2940    /**
2941     * Reference count for transient state.
2942     * @see #setHasTransientState(boolean)
2943     */
2944    int mTransientStateCount = 0;
2945
2946    /**
2947     * Count of how many windows this view has been attached to.
2948     */
2949    int mWindowAttachCount;
2950
2951    /**
2952     * The layout parameters associated with this view and used by the parent
2953     * {@link android.view.ViewGroup} to determine how this view should be
2954     * laid out.
2955     * {@hide}
2956     */
2957    protected ViewGroup.LayoutParams mLayoutParams;
2958
2959    /**
2960     * The view flags hold various views states.
2961     * {@hide}
2962     */
2963    @ViewDebug.ExportedProperty
2964    int mViewFlags;
2965
2966    static class TransformationInfo {
2967        /**
2968         * The transform matrix for the View. This transform is calculated internally
2969         * based on the translation, rotation, and scale properties.
2970         *
2971         * Do *not* use this variable directly; instead call getMatrix(), which will
2972         * load the value from the View's RenderNode.
2973         */
2974        private final Matrix mMatrix = new Matrix();
2975
2976        /**
2977         * The inverse transform matrix for the View. This transform is calculated
2978         * internally based on the translation, rotation, and scale properties.
2979         *
2980         * Do *not* use this variable directly; instead call getInverseMatrix(),
2981         * which will load the value from the View's RenderNode.
2982         */
2983        private Matrix mInverseMatrix;
2984
2985        /**
2986         * The opacity of the View. This is a value from 0 to 1, where 0 means
2987         * completely transparent and 1 means completely opaque.
2988         */
2989        @ViewDebug.ExportedProperty
2990        float mAlpha = 1f;
2991
2992        /**
2993         * The opacity of the view as manipulated by the Fade transition. This is a hidden
2994         * property only used by transitions, which is composited with the other alpha
2995         * values to calculate the final visual alpha value.
2996         */
2997        float mTransitionAlpha = 1f;
2998    }
2999
3000    TransformationInfo mTransformationInfo;
3001
3002    /**
3003     * Current clip bounds. to which all drawing of this view are constrained.
3004     */
3005    Rect mClipBounds = null;
3006
3007    private boolean mLastIsOpaque;
3008
3009    /**
3010     * The distance in pixels from the left edge of this view's parent
3011     * to the left edge of this view.
3012     * {@hide}
3013     */
3014    @ViewDebug.ExportedProperty(category = "layout")
3015    protected int mLeft;
3016    /**
3017     * The distance in pixels from the left edge of this view's parent
3018     * to the right edge of this view.
3019     * {@hide}
3020     */
3021    @ViewDebug.ExportedProperty(category = "layout")
3022    protected int mRight;
3023    /**
3024     * The distance in pixels from the top edge of this view's parent
3025     * to the top edge of this view.
3026     * {@hide}
3027     */
3028    @ViewDebug.ExportedProperty(category = "layout")
3029    protected int mTop;
3030    /**
3031     * The distance in pixels from the top edge of this view's parent
3032     * to the bottom edge of this view.
3033     * {@hide}
3034     */
3035    @ViewDebug.ExportedProperty(category = "layout")
3036    protected int mBottom;
3037
3038    /**
3039     * The offset, in pixels, by which the content of this view is scrolled
3040     * horizontally.
3041     * {@hide}
3042     */
3043    @ViewDebug.ExportedProperty(category = "scrolling")
3044    protected int mScrollX;
3045    /**
3046     * The offset, in pixels, by which the content of this view is scrolled
3047     * vertically.
3048     * {@hide}
3049     */
3050    @ViewDebug.ExportedProperty(category = "scrolling")
3051    protected int mScrollY;
3052
3053    /**
3054     * The left padding in pixels, that is the distance in pixels between the
3055     * left edge of this view and the left edge of its content.
3056     * {@hide}
3057     */
3058    @ViewDebug.ExportedProperty(category = "padding")
3059    protected int mPaddingLeft = 0;
3060    /**
3061     * The right padding in pixels, that is the distance in pixels between the
3062     * right edge of this view and the right edge of its content.
3063     * {@hide}
3064     */
3065    @ViewDebug.ExportedProperty(category = "padding")
3066    protected int mPaddingRight = 0;
3067    /**
3068     * The top padding in pixels, that is the distance in pixels between the
3069     * top edge of this view and the top edge of its content.
3070     * {@hide}
3071     */
3072    @ViewDebug.ExportedProperty(category = "padding")
3073    protected int mPaddingTop;
3074    /**
3075     * The bottom padding in pixels, that is the distance in pixels between the
3076     * bottom edge of this view and the bottom edge of its content.
3077     * {@hide}
3078     */
3079    @ViewDebug.ExportedProperty(category = "padding")
3080    protected int mPaddingBottom;
3081
3082    /**
3083     * The layout insets in pixels, that is the distance in pixels between the
3084     * visible edges of this view its bounds.
3085     */
3086    private Insets mLayoutInsets;
3087
3088    /**
3089     * Briefly describes the view and is primarily used for accessibility support.
3090     */
3091    private CharSequence mContentDescription;
3092
3093    /**
3094     * Specifies the id of a view for which this view serves as a label for
3095     * accessibility purposes.
3096     */
3097    private int mLabelForId = View.NO_ID;
3098
3099    /**
3100     * Predicate for matching labeled view id with its label for
3101     * accessibility purposes.
3102     */
3103    private MatchLabelForPredicate mMatchLabelForPredicate;
3104
3105    /**
3106     * Predicate for matching a view by its id.
3107     */
3108    private MatchIdPredicate mMatchIdPredicate;
3109
3110    /**
3111     * Cache the paddingRight set by the user to append to the scrollbar's size.
3112     *
3113     * @hide
3114     */
3115    @ViewDebug.ExportedProperty(category = "padding")
3116    protected int mUserPaddingRight;
3117
3118    /**
3119     * Cache the paddingBottom set by the user to append to the scrollbar's size.
3120     *
3121     * @hide
3122     */
3123    @ViewDebug.ExportedProperty(category = "padding")
3124    protected int mUserPaddingBottom;
3125
3126    /**
3127     * Cache the paddingLeft set by the user to append to the scrollbar's size.
3128     *
3129     * @hide
3130     */
3131    @ViewDebug.ExportedProperty(category = "padding")
3132    protected int mUserPaddingLeft;
3133
3134    /**
3135     * Cache the paddingStart set by the user to append to the scrollbar's size.
3136     *
3137     */
3138    @ViewDebug.ExportedProperty(category = "padding")
3139    int mUserPaddingStart;
3140
3141    /**
3142     * Cache the paddingEnd set by the user to append to the scrollbar's size.
3143     *
3144     */
3145    @ViewDebug.ExportedProperty(category = "padding")
3146    int mUserPaddingEnd;
3147
3148    /**
3149     * Cache initial left padding.
3150     *
3151     * @hide
3152     */
3153    int mUserPaddingLeftInitial;
3154
3155    /**
3156     * Cache initial right padding.
3157     *
3158     * @hide
3159     */
3160    int mUserPaddingRightInitial;
3161
3162    /**
3163     * Default undefined padding
3164     */
3165    private static final int UNDEFINED_PADDING = Integer.MIN_VALUE;
3166
3167    /**
3168     * Cache if a left padding has been defined
3169     */
3170    private boolean mLeftPaddingDefined = false;
3171
3172    /**
3173     * Cache if a right padding has been defined
3174     */
3175    private boolean mRightPaddingDefined = false;
3176
3177    /**
3178     * @hide
3179     */
3180    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
3181    /**
3182     * @hide
3183     */
3184    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
3185
3186    private LongSparseLongArray mMeasureCache;
3187
3188    @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_")
3189    private Drawable mBackground;
3190
3191    /**
3192     * Display list used for backgrounds.
3193     * <p>
3194     * When non-null and valid, this is expected to contain an up-to-date copy
3195     * of the background drawable. It is cleared on temporary detach and reset
3196     * on cleanup.
3197     */
3198    private RenderNode mBackgroundDisplayList;
3199
3200    private int mBackgroundResource;
3201    private boolean mBackgroundSizeChanged;
3202
3203    private String mViewName;
3204
3205    static class ListenerInfo {
3206        /**
3207         * Listener used to dispatch focus change events.
3208         * This field should be made private, so it is hidden from the SDK.
3209         * {@hide}
3210         */
3211        protected OnFocusChangeListener mOnFocusChangeListener;
3212
3213        /**
3214         * Listeners for layout change events.
3215         */
3216        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
3217
3218        /**
3219         * Listeners for attach events.
3220         */
3221        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
3222
3223        /**
3224         * Listener used to dispatch click events.
3225         * This field should be made private, so it is hidden from the SDK.
3226         * {@hide}
3227         */
3228        public OnClickListener mOnClickListener;
3229
3230        /**
3231         * Listener used to dispatch long click events.
3232         * This field should be made private, so it is hidden from the SDK.
3233         * {@hide}
3234         */
3235        protected OnLongClickListener mOnLongClickListener;
3236
3237        /**
3238         * Listener used to build the context menu.
3239         * This field should be made private, so it is hidden from the SDK.
3240         * {@hide}
3241         */
3242        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
3243
3244        private OnKeyListener mOnKeyListener;
3245
3246        private OnTouchListener mOnTouchListener;
3247
3248        private OnHoverListener mOnHoverListener;
3249
3250        private OnGenericMotionListener mOnGenericMotionListener;
3251
3252        private OnDragListener mOnDragListener;
3253
3254        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
3255
3256        OnApplyWindowInsetsListener mOnApplyWindowInsetsListener;
3257    }
3258
3259    ListenerInfo mListenerInfo;
3260
3261    /**
3262     * The application environment this view lives in.
3263     * This field should be made private, so it is hidden from the SDK.
3264     * {@hide}
3265     */
3266    protected Context mContext;
3267
3268    private final Resources mResources;
3269
3270    private ScrollabilityCache mScrollCache;
3271
3272    private int[] mDrawableState = null;
3273
3274    /**
3275     * Stores the outline of the view, passed down to the DisplayList level for
3276     * defining shadow shape.
3277     */
3278    private Outline mOutline;
3279
3280    /**
3281     * Animator that automatically runs based on state changes.
3282     */
3283    private StateListAnimator mStateListAnimator;
3284
3285    /**
3286     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
3287     * the user may specify which view to go to next.
3288     */
3289    private int mNextFocusLeftId = View.NO_ID;
3290
3291    /**
3292     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
3293     * the user may specify which view to go to next.
3294     */
3295    private int mNextFocusRightId = View.NO_ID;
3296
3297    /**
3298     * When this view has focus and the next focus is {@link #FOCUS_UP},
3299     * the user may specify which view to go to next.
3300     */
3301    private int mNextFocusUpId = View.NO_ID;
3302
3303    /**
3304     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
3305     * the user may specify which view to go to next.
3306     */
3307    private int mNextFocusDownId = View.NO_ID;
3308
3309    /**
3310     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
3311     * the user may specify which view to go to next.
3312     */
3313    int mNextFocusForwardId = View.NO_ID;
3314
3315    private CheckForLongPress mPendingCheckForLongPress;
3316    private CheckForTap mPendingCheckForTap = null;
3317    private PerformClick mPerformClick;
3318    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
3319
3320    private UnsetPressedState mUnsetPressedState;
3321
3322    /**
3323     * Whether the long press's action has been invoked.  The tap's action is invoked on the
3324     * up event while a long press is invoked as soon as the long press duration is reached, so
3325     * a long press could be performed before the tap is checked, in which case the tap's action
3326     * should not be invoked.
3327     */
3328    private boolean mHasPerformedLongPress;
3329
3330    /**
3331     * The minimum height of the view. We'll try our best to have the height
3332     * of this view to at least this amount.
3333     */
3334    @ViewDebug.ExportedProperty(category = "measurement")
3335    private int mMinHeight;
3336
3337    /**
3338     * The minimum width of the view. We'll try our best to have the width
3339     * of this view to at least this amount.
3340     */
3341    @ViewDebug.ExportedProperty(category = "measurement")
3342    private int mMinWidth;
3343
3344    /**
3345     * The delegate to handle touch events that are physically in this view
3346     * but should be handled by another view.
3347     */
3348    private TouchDelegate mTouchDelegate = null;
3349
3350    /**
3351     * Solid color to use as a background when creating the drawing cache. Enables
3352     * the cache to use 16 bit bitmaps instead of 32 bit.
3353     */
3354    private int mDrawingCacheBackgroundColor = 0;
3355
3356    /**
3357     * Special tree observer used when mAttachInfo is null.
3358     */
3359    private ViewTreeObserver mFloatingTreeObserver;
3360
3361    /**
3362     * Cache the touch slop from the context that created the view.
3363     */
3364    private int mTouchSlop;
3365
3366    /**
3367     * Object that handles automatic animation of view properties.
3368     */
3369    private ViewPropertyAnimator mAnimator = null;
3370
3371    /**
3372     * Flag indicating that a drag can cross window boundaries.  When
3373     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
3374     * with this flag set, all visible applications will be able to participate
3375     * in the drag operation and receive the dragged content.
3376     *
3377     * @hide
3378     */
3379    public static final int DRAG_FLAG_GLOBAL = 1;
3380
3381    /**
3382     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
3383     */
3384    private float mVerticalScrollFactor;
3385
3386    /**
3387     * Position of the vertical scroll bar.
3388     */
3389    private int mVerticalScrollbarPosition;
3390
3391    /**
3392     * Position the scroll bar at the default position as determined by the system.
3393     */
3394    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
3395
3396    /**
3397     * Position the scroll bar along the left edge.
3398     */
3399    public static final int SCROLLBAR_POSITION_LEFT = 1;
3400
3401    /**
3402     * Position the scroll bar along the right edge.
3403     */
3404    public static final int SCROLLBAR_POSITION_RIGHT = 2;
3405
3406    /**
3407     * Indicates that the view does not have a layer.
3408     *
3409     * @see #getLayerType()
3410     * @see #setLayerType(int, android.graphics.Paint)
3411     * @see #LAYER_TYPE_SOFTWARE
3412     * @see #LAYER_TYPE_HARDWARE
3413     */
3414    public static final int LAYER_TYPE_NONE = 0;
3415
3416    /**
3417     * <p>Indicates that the view has a software layer. A software layer is backed
3418     * by a bitmap and causes the view to be rendered using Android's software
3419     * rendering pipeline, even if hardware acceleration is enabled.</p>
3420     *
3421     * <p>Software layers have various usages:</p>
3422     * <p>When the application is not using hardware acceleration, a software layer
3423     * is useful to apply a specific color filter and/or blending mode and/or
3424     * translucency to a view and all its children.</p>
3425     * <p>When the application is using hardware acceleration, a software layer
3426     * is useful to render drawing primitives not supported by the hardware
3427     * accelerated pipeline. It can also be used to cache a complex view tree
3428     * into a texture and reduce the complexity of drawing operations. For instance,
3429     * when animating a complex view tree with a translation, a software layer can
3430     * be used to render the view tree only once.</p>
3431     * <p>Software layers should be avoided when the affected view tree updates
3432     * often. Every update will require to re-render the software layer, which can
3433     * potentially be slow (particularly when hardware acceleration is turned on
3434     * since the layer will have to be uploaded into a hardware texture after every
3435     * update.)</p>
3436     *
3437     * @see #getLayerType()
3438     * @see #setLayerType(int, android.graphics.Paint)
3439     * @see #LAYER_TYPE_NONE
3440     * @see #LAYER_TYPE_HARDWARE
3441     */
3442    public static final int LAYER_TYPE_SOFTWARE = 1;
3443
3444    /**
3445     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3446     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3447     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3448     * rendering pipeline, but only if hardware acceleration is turned on for the
3449     * view hierarchy. When hardware acceleration is turned off, hardware layers
3450     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3451     *
3452     * <p>A hardware layer is useful to apply a specific color filter and/or
3453     * blending mode and/or translucency to a view and all its children.</p>
3454     * <p>A hardware layer can be used to cache a complex view tree into a
3455     * texture and reduce the complexity of drawing operations. For instance,
3456     * when animating a complex view tree with a translation, a hardware layer can
3457     * be used to render the view tree only once.</p>
3458     * <p>A hardware layer can also be used to increase the rendering quality when
3459     * rotation transformations are applied on a view. It can also be used to
3460     * prevent potential clipping issues when applying 3D transforms on a view.</p>
3461     *
3462     * @see #getLayerType()
3463     * @see #setLayerType(int, android.graphics.Paint)
3464     * @see #LAYER_TYPE_NONE
3465     * @see #LAYER_TYPE_SOFTWARE
3466     */
3467    public static final int LAYER_TYPE_HARDWARE = 2;
3468
3469    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3470            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
3471            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
3472            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
3473    })
3474    int mLayerType = LAYER_TYPE_NONE;
3475    Paint mLayerPaint;
3476
3477    /**
3478     * Set to true when drawing cache is enabled and cannot be created.
3479     *
3480     * @hide
3481     */
3482    public boolean mCachingFailed;
3483    private Bitmap mDrawingCache;
3484    private Bitmap mUnscaledDrawingCache;
3485
3486    /**
3487     * RenderNode holding View properties, potentially holding a DisplayList of View content.
3488     * <p>
3489     * When non-null and valid, this is expected to contain an up-to-date copy
3490     * of the View content. Its DisplayList content is cleared on temporary detach and reset on
3491     * cleanup.
3492     */
3493    final RenderNode mRenderNode;
3494
3495    /**
3496     * Set to true when the view is sending hover accessibility events because it
3497     * is the innermost hovered view.
3498     */
3499    private boolean mSendingHoverAccessibilityEvents;
3500
3501    /**
3502     * Delegate for injecting accessibility functionality.
3503     */
3504    AccessibilityDelegate mAccessibilityDelegate;
3505
3506    /**
3507     * The view's overlay layer. Developers get a reference to the overlay via getOverlay()
3508     * and add/remove objects to/from the overlay directly through the Overlay methods.
3509     */
3510    ViewOverlay mOverlay;
3511
3512    /**
3513     * The currently active parent view for receiving delegated nested scrolling events.
3514     * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared
3515     * by {@link #stopNestedScroll()} at the same point where we clear
3516     * requestDisallowInterceptTouchEvent.
3517     */
3518    private ViewParent mNestedScrollingParent;
3519
3520    /**
3521     * Consistency verifier for debugging purposes.
3522     * @hide
3523     */
3524    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
3525            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
3526                    new InputEventConsistencyVerifier(this, 0) : null;
3527
3528    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
3529
3530    private int[] mTempNestedScrollConsumed;
3531
3532    /**
3533     * Simple constructor to use when creating a view from code.
3534     *
3535     * @param context The Context the view is running in, through which it can
3536     *        access the current theme, resources, etc.
3537     */
3538    public View(Context context) {
3539        mContext = context;
3540        mResources = context != null ? context.getResources() : null;
3541        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
3542        // Set some flags defaults
3543        mPrivateFlags2 =
3544                (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) |
3545                (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) |
3546                (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) |
3547                (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) |
3548                (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) |
3549                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
3550        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
3551        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
3552        mUserPaddingStart = UNDEFINED_PADDING;
3553        mUserPaddingEnd = UNDEFINED_PADDING;
3554        mRenderNode = RenderNode.create(getClass().getName());
3555
3556        if (!sCompatibilityDone && context != null) {
3557            final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3558
3559            // Older apps may need this compatibility hack for measurement.
3560            sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1;
3561
3562            // Older apps expect onMeasure() to always be called on a layout pass, regardless
3563            // of whether a layout was requested on that View.
3564            sIgnoreMeasureCache = targetSdkVersion < KITKAT;
3565
3566            // Older apps may need this to ignore the clip bounds
3567            sIgnoreClipBoundsForChildren = targetSdkVersion < L;
3568
3569            sCompatibilityDone = true;
3570        }
3571    }
3572
3573    /**
3574     * Constructor that is called when inflating a view from XML. This is called
3575     * when a view is being constructed from an XML file, supplying attributes
3576     * that were specified in the XML file. This version uses a default style of
3577     * 0, so the only attribute values applied are those in the Context's Theme
3578     * and the given AttributeSet.
3579     *
3580     * <p>
3581     * The method onFinishInflate() will be called after all children have been
3582     * added.
3583     *
3584     * @param context The Context the view is running in, through which it can
3585     *        access the current theme, resources, etc.
3586     * @param attrs The attributes of the XML tag that is inflating the view.
3587     * @see #View(Context, AttributeSet, int)
3588     */
3589    public View(Context context, AttributeSet attrs) {
3590        this(context, attrs, 0);
3591    }
3592
3593    /**
3594     * Perform inflation from XML and apply a class-specific base style from a
3595     * theme attribute. This constructor of View allows subclasses to use their
3596     * own base style when they are inflating. For example, a Button class's
3597     * constructor would call this version of the super class constructor and
3598     * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this
3599     * allows the theme's button style to modify all of the base view attributes
3600     * (in particular its background) as well as the Button class's attributes.
3601     *
3602     * @param context The Context the view is running in, through which it can
3603     *        access the current theme, resources, etc.
3604     * @param attrs The attributes of the XML tag that is inflating the view.
3605     * @param defStyleAttr An attribute in the current theme that contains a
3606     *        reference to a style resource that supplies default values for
3607     *        the view. Can be 0 to not look for defaults.
3608     * @see #View(Context, AttributeSet)
3609     */
3610    public View(Context context, AttributeSet attrs, int defStyleAttr) {
3611        this(context, attrs, defStyleAttr, 0);
3612    }
3613
3614    /**
3615     * Perform inflation from XML and apply a class-specific base style from a
3616     * theme attribute or style resource. This constructor of View allows
3617     * subclasses to use their own base style when they are inflating.
3618     * <p>
3619     * When determining the final value of a particular attribute, there are
3620     * four inputs that come into play:
3621     * <ol>
3622     * <li>Any attribute values in the given AttributeSet.
3623     * <li>The style resource specified in the AttributeSet (named "style").
3624     * <li>The default style specified by <var>defStyleAttr</var>.
3625     * <li>The default style specified by <var>defStyleRes</var>.
3626     * <li>The base values in this theme.
3627     * </ol>
3628     * <p>
3629     * Each of these inputs is considered in-order, with the first listed taking
3630     * precedence over the following ones. In other words, if in the
3631     * AttributeSet you have supplied <code>&lt;Button * textColor="#ff000000"&gt;</code>
3632     * , then the button's text will <em>always</em> be black, regardless of
3633     * what is specified in any of the styles.
3634     *
3635     * @param context The Context the view is running in, through which it can
3636     *        access the current theme, resources, etc.
3637     * @param attrs The attributes of the XML tag that is inflating the view.
3638     * @param defStyleAttr An attribute in the current theme that contains a
3639     *        reference to a style resource that supplies default values for
3640     *        the view. Can be 0 to not look for defaults.
3641     * @param defStyleRes A resource identifier of a style resource that
3642     *        supplies default values for the view, used only if
3643     *        defStyleAttr is 0 or can not be found in the theme. Can be 0
3644     *        to not look for defaults.
3645     * @see #View(Context, AttributeSet, int)
3646     */
3647    public View(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
3648        this(context);
3649
3650        final TypedArray a = context.obtainStyledAttributes(
3651                attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes);
3652
3653        Drawable background = null;
3654
3655        int leftPadding = -1;
3656        int topPadding = -1;
3657        int rightPadding = -1;
3658        int bottomPadding = -1;
3659        int startPadding = UNDEFINED_PADDING;
3660        int endPadding = UNDEFINED_PADDING;
3661
3662        int padding = -1;
3663
3664        int viewFlagValues = 0;
3665        int viewFlagMasks = 0;
3666
3667        boolean setScrollContainer = false;
3668
3669        int x = 0;
3670        int y = 0;
3671
3672        float tx = 0;
3673        float ty = 0;
3674        float tz = 0;
3675        float elevation = 0;
3676        float rotation = 0;
3677        float rotationX = 0;
3678        float rotationY = 0;
3679        float sx = 1f;
3680        float sy = 1f;
3681        boolean transformSet = false;
3682
3683        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
3684        int overScrollMode = mOverScrollMode;
3685        boolean initializeScrollbars = false;
3686
3687        boolean startPaddingDefined = false;
3688        boolean endPaddingDefined = false;
3689        boolean leftPaddingDefined = false;
3690        boolean rightPaddingDefined = false;
3691
3692        final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3693
3694        final int N = a.getIndexCount();
3695        for (int i = 0; i < N; i++) {
3696            int attr = a.getIndex(i);
3697            switch (attr) {
3698                case com.android.internal.R.styleable.View_background:
3699                    background = a.getDrawable(attr);
3700                    break;
3701                case com.android.internal.R.styleable.View_padding:
3702                    padding = a.getDimensionPixelSize(attr, -1);
3703                    mUserPaddingLeftInitial = padding;
3704                    mUserPaddingRightInitial = padding;
3705                    leftPaddingDefined = true;
3706                    rightPaddingDefined = true;
3707                    break;
3708                 case com.android.internal.R.styleable.View_paddingLeft:
3709                    leftPadding = a.getDimensionPixelSize(attr, -1);
3710                    mUserPaddingLeftInitial = leftPadding;
3711                    leftPaddingDefined = true;
3712                    break;
3713                case com.android.internal.R.styleable.View_paddingTop:
3714                    topPadding = a.getDimensionPixelSize(attr, -1);
3715                    break;
3716                case com.android.internal.R.styleable.View_paddingRight:
3717                    rightPadding = a.getDimensionPixelSize(attr, -1);
3718                    mUserPaddingRightInitial = rightPadding;
3719                    rightPaddingDefined = true;
3720                    break;
3721                case com.android.internal.R.styleable.View_paddingBottom:
3722                    bottomPadding = a.getDimensionPixelSize(attr, -1);
3723                    break;
3724                case com.android.internal.R.styleable.View_paddingStart:
3725                    startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3726                    startPaddingDefined = (startPadding != UNDEFINED_PADDING);
3727                    break;
3728                case com.android.internal.R.styleable.View_paddingEnd:
3729                    endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3730                    endPaddingDefined = (endPadding != UNDEFINED_PADDING);
3731                    break;
3732                case com.android.internal.R.styleable.View_scrollX:
3733                    x = a.getDimensionPixelOffset(attr, 0);
3734                    break;
3735                case com.android.internal.R.styleable.View_scrollY:
3736                    y = a.getDimensionPixelOffset(attr, 0);
3737                    break;
3738                case com.android.internal.R.styleable.View_alpha:
3739                    setAlpha(a.getFloat(attr, 1f));
3740                    break;
3741                case com.android.internal.R.styleable.View_transformPivotX:
3742                    setPivotX(a.getDimensionPixelOffset(attr, 0));
3743                    break;
3744                case com.android.internal.R.styleable.View_transformPivotY:
3745                    setPivotY(a.getDimensionPixelOffset(attr, 0));
3746                    break;
3747                case com.android.internal.R.styleable.View_translationX:
3748                    tx = a.getDimensionPixelOffset(attr, 0);
3749                    transformSet = true;
3750                    break;
3751                case com.android.internal.R.styleable.View_translationY:
3752                    ty = a.getDimensionPixelOffset(attr, 0);
3753                    transformSet = true;
3754                    break;
3755                case com.android.internal.R.styleable.View_translationZ:
3756                    tz = a.getDimensionPixelOffset(attr, 0);
3757                    transformSet = true;
3758                    break;
3759                case com.android.internal.R.styleable.View_elevation:
3760                    elevation = a.getDimensionPixelOffset(attr, 0);
3761                    transformSet = true;
3762                    break;
3763                case com.android.internal.R.styleable.View_rotation:
3764                    rotation = a.getFloat(attr, 0);
3765                    transformSet = true;
3766                    break;
3767                case com.android.internal.R.styleable.View_rotationX:
3768                    rotationX = a.getFloat(attr, 0);
3769                    transformSet = true;
3770                    break;
3771                case com.android.internal.R.styleable.View_rotationY:
3772                    rotationY = a.getFloat(attr, 0);
3773                    transformSet = true;
3774                    break;
3775                case com.android.internal.R.styleable.View_scaleX:
3776                    sx = a.getFloat(attr, 1f);
3777                    transformSet = true;
3778                    break;
3779                case com.android.internal.R.styleable.View_scaleY:
3780                    sy = a.getFloat(attr, 1f);
3781                    transformSet = true;
3782                    break;
3783                case com.android.internal.R.styleable.View_id:
3784                    mID = a.getResourceId(attr, NO_ID);
3785                    break;
3786                case com.android.internal.R.styleable.View_tag:
3787                    mTag = a.getText(attr);
3788                    break;
3789                case com.android.internal.R.styleable.View_fitsSystemWindows:
3790                    if (a.getBoolean(attr, false)) {
3791                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
3792                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
3793                    }
3794                    break;
3795                case com.android.internal.R.styleable.View_focusable:
3796                    if (a.getBoolean(attr, false)) {
3797                        viewFlagValues |= FOCUSABLE;
3798                        viewFlagMasks |= FOCUSABLE_MASK;
3799                    }
3800                    break;
3801                case com.android.internal.R.styleable.View_focusableInTouchMode:
3802                    if (a.getBoolean(attr, false)) {
3803                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
3804                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
3805                    }
3806                    break;
3807                case com.android.internal.R.styleable.View_clickable:
3808                    if (a.getBoolean(attr, false)) {
3809                        viewFlagValues |= CLICKABLE;
3810                        viewFlagMasks |= CLICKABLE;
3811                    }
3812                    break;
3813                case com.android.internal.R.styleable.View_longClickable:
3814                    if (a.getBoolean(attr, false)) {
3815                        viewFlagValues |= LONG_CLICKABLE;
3816                        viewFlagMasks |= LONG_CLICKABLE;
3817                    }
3818                    break;
3819                case com.android.internal.R.styleable.View_saveEnabled:
3820                    if (!a.getBoolean(attr, true)) {
3821                        viewFlagValues |= SAVE_DISABLED;
3822                        viewFlagMasks |= SAVE_DISABLED_MASK;
3823                    }
3824                    break;
3825                case com.android.internal.R.styleable.View_duplicateParentState:
3826                    if (a.getBoolean(attr, false)) {
3827                        viewFlagValues |= DUPLICATE_PARENT_STATE;
3828                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
3829                    }
3830                    break;
3831                case com.android.internal.R.styleable.View_visibility:
3832                    final int visibility = a.getInt(attr, 0);
3833                    if (visibility != 0) {
3834                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
3835                        viewFlagMasks |= VISIBILITY_MASK;
3836                    }
3837                    break;
3838                case com.android.internal.R.styleable.View_layoutDirection:
3839                    // Clear any layout direction flags (included resolved bits) already set
3840                    mPrivateFlags2 &=
3841                            ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK);
3842                    // Set the layout direction flags depending on the value of the attribute
3843                    final int layoutDirection = a.getInt(attr, -1);
3844                    final int value = (layoutDirection != -1) ?
3845                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
3846                    mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT);
3847                    break;
3848                case com.android.internal.R.styleable.View_drawingCacheQuality:
3849                    final int cacheQuality = a.getInt(attr, 0);
3850                    if (cacheQuality != 0) {
3851                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
3852                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
3853                    }
3854                    break;
3855                case com.android.internal.R.styleable.View_contentDescription:
3856                    setContentDescription(a.getString(attr));
3857                    break;
3858                case com.android.internal.R.styleable.View_labelFor:
3859                    setLabelFor(a.getResourceId(attr, NO_ID));
3860                    break;
3861                case com.android.internal.R.styleable.View_soundEffectsEnabled:
3862                    if (!a.getBoolean(attr, true)) {
3863                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
3864                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
3865                    }
3866                    break;
3867                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
3868                    if (!a.getBoolean(attr, true)) {
3869                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
3870                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
3871                    }
3872                    break;
3873                case R.styleable.View_scrollbars:
3874                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
3875                    if (scrollbars != SCROLLBARS_NONE) {
3876                        viewFlagValues |= scrollbars;
3877                        viewFlagMasks |= SCROLLBARS_MASK;
3878                        initializeScrollbars = true;
3879                    }
3880                    break;
3881                //noinspection deprecation
3882                case R.styleable.View_fadingEdge:
3883                    if (targetSdkVersion >= ICE_CREAM_SANDWICH) {
3884                        // Ignore the attribute starting with ICS
3885                        break;
3886                    }
3887                    // With builds < ICS, fall through and apply fading edges
3888                case R.styleable.View_requiresFadingEdge:
3889                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
3890                    if (fadingEdge != FADING_EDGE_NONE) {
3891                        viewFlagValues |= fadingEdge;
3892                        viewFlagMasks |= FADING_EDGE_MASK;
3893                        initializeFadingEdge(a);
3894                    }
3895                    break;
3896                case R.styleable.View_scrollbarStyle:
3897                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
3898                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3899                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
3900                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
3901                    }
3902                    break;
3903                case R.styleable.View_isScrollContainer:
3904                    setScrollContainer = true;
3905                    if (a.getBoolean(attr, false)) {
3906                        setScrollContainer(true);
3907                    }
3908                    break;
3909                case com.android.internal.R.styleable.View_keepScreenOn:
3910                    if (a.getBoolean(attr, false)) {
3911                        viewFlagValues |= KEEP_SCREEN_ON;
3912                        viewFlagMasks |= KEEP_SCREEN_ON;
3913                    }
3914                    break;
3915                case R.styleable.View_filterTouchesWhenObscured:
3916                    if (a.getBoolean(attr, false)) {
3917                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
3918                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
3919                    }
3920                    break;
3921                case R.styleable.View_nextFocusLeft:
3922                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
3923                    break;
3924                case R.styleable.View_nextFocusRight:
3925                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
3926                    break;
3927                case R.styleable.View_nextFocusUp:
3928                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
3929                    break;
3930                case R.styleable.View_nextFocusDown:
3931                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
3932                    break;
3933                case R.styleable.View_nextFocusForward:
3934                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
3935                    break;
3936                case R.styleable.View_minWidth:
3937                    mMinWidth = a.getDimensionPixelSize(attr, 0);
3938                    break;
3939                case R.styleable.View_minHeight:
3940                    mMinHeight = a.getDimensionPixelSize(attr, 0);
3941                    break;
3942                case R.styleable.View_onClick:
3943                    if (context.isRestricted()) {
3944                        throw new IllegalStateException("The android:onClick attribute cannot "
3945                                + "be used within a restricted context");
3946                    }
3947
3948                    final String handlerName = a.getString(attr);
3949                    if (handlerName != null) {
3950                        setOnClickListener(new OnClickListener() {
3951                            private Method mHandler;
3952
3953                            public void onClick(View v) {
3954                                if (mHandler == null) {
3955                                    try {
3956                                        mHandler = getContext().getClass().getMethod(handlerName,
3957                                                View.class);
3958                                    } catch (NoSuchMethodException e) {
3959                                        int id = getId();
3960                                        String idText = id == NO_ID ? "" : " with id '"
3961                                                + getContext().getResources().getResourceEntryName(
3962                                                    id) + "'";
3963                                        throw new IllegalStateException("Could not find a method " +
3964                                                handlerName + "(View) in the activity "
3965                                                + getContext().getClass() + " for onClick handler"
3966                                                + " on view " + View.this.getClass() + idText, e);
3967                                    }
3968                                }
3969
3970                                try {
3971                                    mHandler.invoke(getContext(), View.this);
3972                                } catch (IllegalAccessException e) {
3973                                    throw new IllegalStateException("Could not execute non "
3974                                            + "public method of the activity", e);
3975                                } catch (InvocationTargetException e) {
3976                                    throw new IllegalStateException("Could not execute "
3977                                            + "method of the activity", e);
3978                                }
3979                            }
3980                        });
3981                    }
3982                    break;
3983                case R.styleable.View_overScrollMode:
3984                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
3985                    break;
3986                case R.styleable.View_verticalScrollbarPosition:
3987                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
3988                    break;
3989                case R.styleable.View_layerType:
3990                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
3991                    break;
3992                case R.styleable.View_textDirection:
3993                    // Clear any text direction flag already set
3994                    mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
3995                    // Set the text direction flags depending on the value of the attribute
3996                    final int textDirection = a.getInt(attr, -1);
3997                    if (textDirection != -1) {
3998                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection];
3999                    }
4000                    break;
4001                case R.styleable.View_textAlignment:
4002                    // Clear any text alignment flag already set
4003                    mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
4004                    // Set the text alignment flag depending on the value of the attribute
4005                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
4006                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment];
4007                    break;
4008                case R.styleable.View_importantForAccessibility:
4009                    setImportantForAccessibility(a.getInt(attr,
4010                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
4011                    break;
4012                case R.styleable.View_accessibilityLiveRegion:
4013                    setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT));
4014                    break;
4015                case R.styleable.View_viewName:
4016                    setViewName(a.getString(attr));
4017                    break;
4018                case R.styleable.View_nestedScrollingEnabled:
4019                    setNestedScrollingEnabled(a.getBoolean(attr, false));
4020                    break;
4021                case R.styleable.View_stateListAnimator:
4022                    setStateListAnimator(AnimatorInflater.loadStateListAnimator(context,
4023                            a.getResourceId(attr, 0)));
4024                    break;
4025            }
4026        }
4027
4028        setOverScrollMode(overScrollMode);
4029
4030        // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet
4031        // the resolved layout direction). Those cached values will be used later during padding
4032        // resolution.
4033        mUserPaddingStart = startPadding;
4034        mUserPaddingEnd = endPadding;
4035
4036        if (background != null) {
4037            setBackground(background);
4038        }
4039
4040        // setBackground above will record that padding is currently provided by the background.
4041        // If we have padding specified via xml, record that here instead and use it.
4042        mLeftPaddingDefined = leftPaddingDefined;
4043        mRightPaddingDefined = rightPaddingDefined;
4044
4045        if (padding >= 0) {
4046            leftPadding = padding;
4047            topPadding = padding;
4048            rightPadding = padding;
4049            bottomPadding = padding;
4050            mUserPaddingLeftInitial = padding;
4051            mUserPaddingRightInitial = padding;
4052        }
4053
4054        if (isRtlCompatibilityMode()) {
4055            // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case.
4056            // left / right padding are used if defined (meaning here nothing to do). If they are not
4057            // defined and start / end padding are defined (e.g. in Frameworks resources), then we use
4058            // start / end and resolve them as left / right (layout direction is not taken into account).
4059            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4060            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4061            // defined.
4062            if (!mLeftPaddingDefined && startPaddingDefined) {
4063                leftPadding = startPadding;
4064            }
4065            mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial;
4066            if (!mRightPaddingDefined && endPaddingDefined) {
4067                rightPadding = endPadding;
4068            }
4069            mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial;
4070        } else {
4071            // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right
4072            // values defined. Otherwise, left /right values are used.
4073            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4074            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4075            // defined.
4076            final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined;
4077
4078            if (mLeftPaddingDefined && !hasRelativePadding) {
4079                mUserPaddingLeftInitial = leftPadding;
4080            }
4081            if (mRightPaddingDefined && !hasRelativePadding) {
4082                mUserPaddingRightInitial = rightPadding;
4083            }
4084        }
4085
4086        internalSetPadding(
4087                mUserPaddingLeftInitial,
4088                topPadding >= 0 ? topPadding : mPaddingTop,
4089                mUserPaddingRightInitial,
4090                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
4091
4092        if (viewFlagMasks != 0) {
4093            setFlags(viewFlagValues, viewFlagMasks);
4094        }
4095
4096        if (initializeScrollbars) {
4097            initializeScrollbars(a);
4098        }
4099
4100        a.recycle();
4101
4102        // Needs to be called after mViewFlags is set
4103        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
4104            recomputePadding();
4105        }
4106
4107        if (x != 0 || y != 0) {
4108            scrollTo(x, y);
4109        }
4110
4111        if (transformSet) {
4112            setTranslationX(tx);
4113            setTranslationY(ty);
4114            setTranslationZ(tz);
4115            setElevation(elevation);
4116            setRotation(rotation);
4117            setRotationX(rotationX);
4118            setRotationY(rotationY);
4119            setScaleX(sx);
4120            setScaleY(sy);
4121        }
4122
4123        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
4124            setScrollContainer(true);
4125        }
4126
4127        computeOpaqueFlags();
4128    }
4129
4130    /**
4131     * Non-public constructor for use in testing
4132     */
4133    View() {
4134        mResources = null;
4135        mRenderNode = RenderNode.create(getClass().getName());
4136    }
4137
4138    public String toString() {
4139        StringBuilder out = new StringBuilder(128);
4140        out.append(getClass().getName());
4141        out.append('{');
4142        out.append(Integer.toHexString(System.identityHashCode(this)));
4143        out.append(' ');
4144        switch (mViewFlags&VISIBILITY_MASK) {
4145            case VISIBLE: out.append('V'); break;
4146            case INVISIBLE: out.append('I'); break;
4147            case GONE: out.append('G'); break;
4148            default: out.append('.'); break;
4149        }
4150        out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.');
4151        out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.');
4152        out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D');
4153        out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.');
4154        out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.');
4155        out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.');
4156        out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.');
4157        out.append(' ');
4158        out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.');
4159        out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.');
4160        out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.');
4161        if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) {
4162            out.append('p');
4163        } else {
4164            out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.');
4165        }
4166        out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.');
4167        out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.');
4168        out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.');
4169        out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.');
4170        out.append(' ');
4171        out.append(mLeft);
4172        out.append(',');
4173        out.append(mTop);
4174        out.append('-');
4175        out.append(mRight);
4176        out.append(',');
4177        out.append(mBottom);
4178        final int id = getId();
4179        if (id != NO_ID) {
4180            out.append(" #");
4181            out.append(Integer.toHexString(id));
4182            final Resources r = mResources;
4183            if (Resources.resourceHasPackage(id) && r != null) {
4184                try {
4185                    String pkgname;
4186                    switch (id&0xff000000) {
4187                        case 0x7f000000:
4188                            pkgname="app";
4189                            break;
4190                        case 0x01000000:
4191                            pkgname="android";
4192                            break;
4193                        default:
4194                            pkgname = r.getResourcePackageName(id);
4195                            break;
4196                    }
4197                    String typename = r.getResourceTypeName(id);
4198                    String entryname = r.getResourceEntryName(id);
4199                    out.append(" ");
4200                    out.append(pkgname);
4201                    out.append(":");
4202                    out.append(typename);
4203                    out.append("/");
4204                    out.append(entryname);
4205                } catch (Resources.NotFoundException e) {
4206                }
4207            }
4208        }
4209        out.append("}");
4210        return out.toString();
4211    }
4212
4213    /**
4214     * <p>
4215     * Initializes the fading edges from a given set of styled attributes. This
4216     * method should be called by subclasses that need fading edges and when an
4217     * instance of these subclasses is created programmatically rather than
4218     * being inflated from XML. This method is automatically called when the XML
4219     * is inflated.
4220     * </p>
4221     *
4222     * @param a the styled attributes set to initialize the fading edges from
4223     */
4224    protected void initializeFadingEdge(TypedArray a) {
4225        initScrollCache();
4226
4227        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
4228                R.styleable.View_fadingEdgeLength,
4229                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
4230    }
4231
4232    /**
4233     * Returns the size of the vertical faded edges used to indicate that more
4234     * content in this view is visible.
4235     *
4236     * @return The size in pixels of the vertical faded edge or 0 if vertical
4237     *         faded edges are not enabled for this view.
4238     * @attr ref android.R.styleable#View_fadingEdgeLength
4239     */
4240    public int getVerticalFadingEdgeLength() {
4241        if (isVerticalFadingEdgeEnabled()) {
4242            ScrollabilityCache cache = mScrollCache;
4243            if (cache != null) {
4244                return cache.fadingEdgeLength;
4245            }
4246        }
4247        return 0;
4248    }
4249
4250    /**
4251     * Set the size of the faded edge used to indicate that more content in this
4252     * view is available.  Will not change whether the fading edge is enabled; use
4253     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
4254     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
4255     * for the vertical or horizontal fading edges.
4256     *
4257     * @param length The size in pixels of the faded edge used to indicate that more
4258     *        content in this view is visible.
4259     */
4260    public void setFadingEdgeLength(int length) {
4261        initScrollCache();
4262        mScrollCache.fadingEdgeLength = length;
4263    }
4264
4265    /**
4266     * Returns the size of the horizontal faded edges used to indicate that more
4267     * content in this view is visible.
4268     *
4269     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
4270     *         faded edges are not enabled for this view.
4271     * @attr ref android.R.styleable#View_fadingEdgeLength
4272     */
4273    public int getHorizontalFadingEdgeLength() {
4274        if (isHorizontalFadingEdgeEnabled()) {
4275            ScrollabilityCache cache = mScrollCache;
4276            if (cache != null) {
4277                return cache.fadingEdgeLength;
4278            }
4279        }
4280        return 0;
4281    }
4282
4283    /**
4284     * Returns the width of the vertical scrollbar.
4285     *
4286     * @return The width in pixels of the vertical scrollbar or 0 if there
4287     *         is no vertical scrollbar.
4288     */
4289    public int getVerticalScrollbarWidth() {
4290        ScrollabilityCache cache = mScrollCache;
4291        if (cache != null) {
4292            ScrollBarDrawable scrollBar = cache.scrollBar;
4293            if (scrollBar != null) {
4294                int size = scrollBar.getSize(true);
4295                if (size <= 0) {
4296                    size = cache.scrollBarSize;
4297                }
4298                return size;
4299            }
4300            return 0;
4301        }
4302        return 0;
4303    }
4304
4305    /**
4306     * Returns the height of the horizontal scrollbar.
4307     *
4308     * @return The height in pixels of the horizontal scrollbar or 0 if
4309     *         there is no horizontal scrollbar.
4310     */
4311    protected int getHorizontalScrollbarHeight() {
4312        ScrollabilityCache cache = mScrollCache;
4313        if (cache != null) {
4314            ScrollBarDrawable scrollBar = cache.scrollBar;
4315            if (scrollBar != null) {
4316                int size = scrollBar.getSize(false);
4317                if (size <= 0) {
4318                    size = cache.scrollBarSize;
4319                }
4320                return size;
4321            }
4322            return 0;
4323        }
4324        return 0;
4325    }
4326
4327    /**
4328     * <p>
4329     * Initializes the scrollbars from a given set of styled attributes. This
4330     * method should be called by subclasses that need scrollbars and when an
4331     * instance of these subclasses is created programmatically rather than
4332     * being inflated from XML. This method is automatically called when the XML
4333     * is inflated.
4334     * </p>
4335     *
4336     * @param a the styled attributes set to initialize the scrollbars from
4337     */
4338    protected void initializeScrollbars(TypedArray a) {
4339        initScrollCache();
4340
4341        final ScrollabilityCache scrollabilityCache = mScrollCache;
4342
4343        if (scrollabilityCache.scrollBar == null) {
4344            scrollabilityCache.scrollBar = new ScrollBarDrawable();
4345        }
4346
4347        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
4348
4349        if (!fadeScrollbars) {
4350            scrollabilityCache.state = ScrollabilityCache.ON;
4351        }
4352        scrollabilityCache.fadeScrollBars = fadeScrollbars;
4353
4354
4355        scrollabilityCache.scrollBarFadeDuration = a.getInt(
4356                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
4357                        .getScrollBarFadeDuration());
4358        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
4359                R.styleable.View_scrollbarDefaultDelayBeforeFade,
4360                ViewConfiguration.getScrollDefaultDelay());
4361
4362
4363        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
4364                com.android.internal.R.styleable.View_scrollbarSize,
4365                ViewConfiguration.get(mContext).getScaledScrollBarSize());
4366
4367        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
4368        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
4369
4370        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
4371        if (thumb != null) {
4372            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
4373        }
4374
4375        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
4376                false);
4377        if (alwaysDraw) {
4378            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
4379        }
4380
4381        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
4382        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
4383
4384        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
4385        if (thumb != null) {
4386            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
4387        }
4388
4389        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
4390                false);
4391        if (alwaysDraw) {
4392            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
4393        }
4394
4395        // Apply layout direction to the new Drawables if needed
4396        final int layoutDirection = getLayoutDirection();
4397        if (track != null) {
4398            track.setLayoutDirection(layoutDirection);
4399        }
4400        if (thumb != null) {
4401            thumb.setLayoutDirection(layoutDirection);
4402        }
4403
4404        // Re-apply user/background padding so that scrollbar(s) get added
4405        resolvePadding();
4406    }
4407
4408    /**
4409     * <p>
4410     * Initalizes the scrollability cache if necessary.
4411     * </p>
4412     */
4413    private void initScrollCache() {
4414        if (mScrollCache == null) {
4415            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
4416        }
4417    }
4418
4419    private ScrollabilityCache getScrollCache() {
4420        initScrollCache();
4421        return mScrollCache;
4422    }
4423
4424    /**
4425     * Set the position of the vertical scroll bar. Should be one of
4426     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
4427     * {@link #SCROLLBAR_POSITION_RIGHT}.
4428     *
4429     * @param position Where the vertical scroll bar should be positioned.
4430     */
4431    public void setVerticalScrollbarPosition(int position) {
4432        if (mVerticalScrollbarPosition != position) {
4433            mVerticalScrollbarPosition = position;
4434            computeOpaqueFlags();
4435            resolvePadding();
4436        }
4437    }
4438
4439    /**
4440     * @return The position where the vertical scroll bar will show, if applicable.
4441     * @see #setVerticalScrollbarPosition(int)
4442     */
4443    public int getVerticalScrollbarPosition() {
4444        return mVerticalScrollbarPosition;
4445    }
4446
4447    ListenerInfo getListenerInfo() {
4448        if (mListenerInfo != null) {
4449            return mListenerInfo;
4450        }
4451        mListenerInfo = new ListenerInfo();
4452        return mListenerInfo;
4453    }
4454
4455    /**
4456     * Register a callback to be invoked when focus of this view changed.
4457     *
4458     * @param l The callback that will run.
4459     */
4460    public void setOnFocusChangeListener(OnFocusChangeListener l) {
4461        getListenerInfo().mOnFocusChangeListener = l;
4462    }
4463
4464    /**
4465     * Add a listener that will be called when the bounds of the view change due to
4466     * layout processing.
4467     *
4468     * @param listener The listener that will be called when layout bounds change.
4469     */
4470    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
4471        ListenerInfo li = getListenerInfo();
4472        if (li.mOnLayoutChangeListeners == null) {
4473            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
4474        }
4475        if (!li.mOnLayoutChangeListeners.contains(listener)) {
4476            li.mOnLayoutChangeListeners.add(listener);
4477        }
4478    }
4479
4480    /**
4481     * Remove a listener for layout changes.
4482     *
4483     * @param listener The listener for layout bounds change.
4484     */
4485    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
4486        ListenerInfo li = mListenerInfo;
4487        if (li == null || li.mOnLayoutChangeListeners == null) {
4488            return;
4489        }
4490        li.mOnLayoutChangeListeners.remove(listener);
4491    }
4492
4493    /**
4494     * Add a listener for attach state changes.
4495     *
4496     * This listener will be called whenever this view is attached or detached
4497     * from a window. Remove the listener using
4498     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
4499     *
4500     * @param listener Listener to attach
4501     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
4502     */
4503    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4504        ListenerInfo li = getListenerInfo();
4505        if (li.mOnAttachStateChangeListeners == null) {
4506            li.mOnAttachStateChangeListeners
4507                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
4508        }
4509        li.mOnAttachStateChangeListeners.add(listener);
4510    }
4511
4512    /**
4513     * Remove a listener for attach state changes. The listener will receive no further
4514     * notification of window attach/detach events.
4515     *
4516     * @param listener Listener to remove
4517     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
4518     */
4519    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4520        ListenerInfo li = mListenerInfo;
4521        if (li == null || li.mOnAttachStateChangeListeners == null) {
4522            return;
4523        }
4524        li.mOnAttachStateChangeListeners.remove(listener);
4525    }
4526
4527    /**
4528     * Returns the focus-change callback registered for this view.
4529     *
4530     * @return The callback, or null if one is not registered.
4531     */
4532    public OnFocusChangeListener getOnFocusChangeListener() {
4533        ListenerInfo li = mListenerInfo;
4534        return li != null ? li.mOnFocusChangeListener : null;
4535    }
4536
4537    /**
4538     * Register a callback to be invoked when this view is clicked. If this view is not
4539     * clickable, it becomes clickable.
4540     *
4541     * @param l The callback that will run
4542     *
4543     * @see #setClickable(boolean)
4544     */
4545    public void setOnClickListener(OnClickListener l) {
4546        if (!isClickable()) {
4547            setClickable(true);
4548        }
4549        getListenerInfo().mOnClickListener = l;
4550    }
4551
4552    /**
4553     * Return whether this view has an attached OnClickListener.  Returns
4554     * true if there is a listener, false if there is none.
4555     */
4556    public boolean hasOnClickListeners() {
4557        ListenerInfo li = mListenerInfo;
4558        return (li != null && li.mOnClickListener != null);
4559    }
4560
4561    /**
4562     * Register a callback to be invoked when this view is clicked and held. If this view is not
4563     * long clickable, it becomes long clickable.
4564     *
4565     * @param l The callback that will run
4566     *
4567     * @see #setLongClickable(boolean)
4568     */
4569    public void setOnLongClickListener(OnLongClickListener l) {
4570        if (!isLongClickable()) {
4571            setLongClickable(true);
4572        }
4573        getListenerInfo().mOnLongClickListener = l;
4574    }
4575
4576    /**
4577     * Register a callback to be invoked when the context menu for this view is
4578     * being built. If this view is not long clickable, it becomes long clickable.
4579     *
4580     * @param l The callback that will run
4581     *
4582     */
4583    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
4584        if (!isLongClickable()) {
4585            setLongClickable(true);
4586        }
4587        getListenerInfo().mOnCreateContextMenuListener = l;
4588    }
4589
4590    /**
4591     * Call this view's OnClickListener, if it is defined.  Performs all normal
4592     * actions associated with clicking: reporting accessibility event, playing
4593     * a sound, etc.
4594     *
4595     * @return True there was an assigned OnClickListener that was called, false
4596     *         otherwise is returned.
4597     */
4598    public boolean performClick() {
4599        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
4600
4601        ListenerInfo li = mListenerInfo;
4602        if (li != null && li.mOnClickListener != null) {
4603            playSoundEffect(SoundEffectConstants.CLICK);
4604            li.mOnClickListener.onClick(this);
4605            return true;
4606        }
4607
4608        return false;
4609    }
4610
4611    /**
4612     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
4613     * this only calls the listener, and does not do any associated clicking
4614     * actions like reporting an accessibility event.
4615     *
4616     * @return True there was an assigned OnClickListener that was called, false
4617     *         otherwise is returned.
4618     */
4619    public boolean callOnClick() {
4620        ListenerInfo li = mListenerInfo;
4621        if (li != null && li.mOnClickListener != null) {
4622            li.mOnClickListener.onClick(this);
4623            return true;
4624        }
4625        return false;
4626    }
4627
4628    /**
4629     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
4630     * OnLongClickListener did not consume the event.
4631     *
4632     * @return True if one of the above receivers consumed the event, false otherwise.
4633     */
4634    public boolean performLongClick() {
4635        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
4636
4637        boolean handled = false;
4638        ListenerInfo li = mListenerInfo;
4639        if (li != null && li.mOnLongClickListener != null) {
4640            handled = li.mOnLongClickListener.onLongClick(View.this);
4641        }
4642        if (!handled) {
4643            handled = showContextMenu();
4644        }
4645        if (handled) {
4646            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
4647        }
4648        return handled;
4649    }
4650
4651    /**
4652     * Performs button-related actions during a touch down event.
4653     *
4654     * @param event The event.
4655     * @return True if the down was consumed.
4656     *
4657     * @hide
4658     */
4659    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
4660        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
4661            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
4662                return true;
4663            }
4664        }
4665        return false;
4666    }
4667
4668    /**
4669     * Bring up the context menu for this view.
4670     *
4671     * @return Whether a context menu was displayed.
4672     */
4673    public boolean showContextMenu() {
4674        return getParent().showContextMenuForChild(this);
4675    }
4676
4677    /**
4678     * Bring up the context menu for this view, referring to the item under the specified point.
4679     *
4680     * @param x The referenced x coordinate.
4681     * @param y The referenced y coordinate.
4682     * @param metaState The keyboard modifiers that were pressed.
4683     * @return Whether a context menu was displayed.
4684     *
4685     * @hide
4686     */
4687    public boolean showContextMenu(float x, float y, int metaState) {
4688        return showContextMenu();
4689    }
4690
4691    /**
4692     * Start an action mode.
4693     *
4694     * @param callback Callback that will control the lifecycle of the action mode
4695     * @return The new action mode if it is started, null otherwise
4696     *
4697     * @see ActionMode
4698     */
4699    public ActionMode startActionMode(ActionMode.Callback callback) {
4700        ViewParent parent = getParent();
4701        if (parent == null) return null;
4702        return parent.startActionModeForChild(this, callback);
4703    }
4704
4705    /**
4706     * Register a callback to be invoked when a hardware key is pressed in this view.
4707     * Key presses in software input methods will generally not trigger the methods of
4708     * this listener.
4709     * @param l the key listener to attach to this view
4710     */
4711    public void setOnKeyListener(OnKeyListener l) {
4712        getListenerInfo().mOnKeyListener = l;
4713    }
4714
4715    /**
4716     * Register a callback to be invoked when a touch event is sent to this view.
4717     * @param l the touch listener to attach to this view
4718     */
4719    public void setOnTouchListener(OnTouchListener l) {
4720        getListenerInfo().mOnTouchListener = l;
4721    }
4722
4723    /**
4724     * Register a callback to be invoked when a generic motion event is sent to this view.
4725     * @param l the generic motion listener to attach to this view
4726     */
4727    public void setOnGenericMotionListener(OnGenericMotionListener l) {
4728        getListenerInfo().mOnGenericMotionListener = l;
4729    }
4730
4731    /**
4732     * Register a callback to be invoked when a hover event is sent to this view.
4733     * @param l the hover listener to attach to this view
4734     */
4735    public void setOnHoverListener(OnHoverListener l) {
4736        getListenerInfo().mOnHoverListener = l;
4737    }
4738
4739    /**
4740     * Register a drag event listener callback object for this View. The parameter is
4741     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
4742     * View, the system calls the
4743     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
4744     * @param l An implementation of {@link android.view.View.OnDragListener}.
4745     */
4746    public void setOnDragListener(OnDragListener l) {
4747        getListenerInfo().mOnDragListener = l;
4748    }
4749
4750    /**
4751     * Give this view focus. This will cause
4752     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
4753     *
4754     * Note: this does not check whether this {@link View} should get focus, it just
4755     * gives it focus no matter what.  It should only be called internally by framework
4756     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
4757     *
4758     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
4759     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
4760     *        focus moved when requestFocus() is called. It may not always
4761     *        apply, in which case use the default View.FOCUS_DOWN.
4762     * @param previouslyFocusedRect The rectangle of the view that had focus
4763     *        prior in this View's coordinate system.
4764     */
4765    void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) {
4766        if (DBG) {
4767            System.out.println(this + " requestFocus()");
4768        }
4769
4770        if ((mPrivateFlags & PFLAG_FOCUSED) == 0) {
4771            mPrivateFlags |= PFLAG_FOCUSED;
4772
4773            View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null;
4774
4775            if (mParent != null) {
4776                mParent.requestChildFocus(this, this);
4777            }
4778
4779            if (mAttachInfo != null) {
4780                mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this);
4781            }
4782
4783            onFocusChanged(true, direction, previouslyFocusedRect);
4784            manageFocusHotspot(true, oldFocus);
4785            refreshDrawableState();
4786        }
4787    }
4788
4789    /**
4790     * Forwards focus information to the background drawable, if necessary. When
4791     * the view is gaining focus, <code>v</code> is the previous focus holder.
4792     * When the view is losing focus, <code>v</code> is the next focus holder.
4793     *
4794     * @param focused whether this view is focused
4795     * @param v previous or the next focus holder, or null if none
4796     */
4797    private void manageFocusHotspot(boolean focused, View v) {
4798        final Rect r = new Rect();
4799        if (!focused && v != null && mAttachInfo != null) {
4800            v.getBoundsOnScreen(r);
4801            final int[] location = mAttachInfo.mTmpLocation;
4802            getLocationOnScreen(location);
4803            r.offset(-location[0], -location[1]);
4804        } else {
4805            r.set(0, 0, mRight - mLeft, mBottom - mTop);
4806        }
4807
4808        final float x = r.exactCenterX();
4809        final float y = r.exactCenterY();
4810        setDrawableHotspot(x, y);
4811    }
4812
4813    /**
4814     * Sets the hotspot position for this View's drawables.
4815     *
4816     * @param x hotspot x coordinate
4817     * @param y hotspot y coordinate
4818     * @hide
4819     */
4820    protected void setDrawableHotspot(float x, float y) {
4821        if (mBackground != null) {
4822            mBackground.setHotspot(x, y);
4823        }
4824    }
4825
4826    /**
4827     * Request that a rectangle of this view be visible on the screen,
4828     * scrolling if necessary just enough.
4829     *
4830     * <p>A View should call this if it maintains some notion of which part
4831     * of its content is interesting.  For example, a text editing view
4832     * should call this when its cursor moves.
4833     *
4834     * @param rectangle The rectangle.
4835     * @return Whether any parent scrolled.
4836     */
4837    public boolean requestRectangleOnScreen(Rect rectangle) {
4838        return requestRectangleOnScreen(rectangle, false);
4839    }
4840
4841    /**
4842     * Request that a rectangle of this view be visible on the screen,
4843     * scrolling if necessary just enough.
4844     *
4845     * <p>A View should call this if it maintains some notion of which part
4846     * of its content is interesting.  For example, a text editing view
4847     * should call this when its cursor moves.
4848     *
4849     * <p>When <code>immediate</code> is set to true, scrolling will not be
4850     * animated.
4851     *
4852     * @param rectangle The rectangle.
4853     * @param immediate True to forbid animated scrolling, false otherwise
4854     * @return Whether any parent scrolled.
4855     */
4856    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
4857        if (mParent == null) {
4858            return false;
4859        }
4860
4861        View child = this;
4862
4863        RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF();
4864        position.set(rectangle);
4865
4866        ViewParent parent = mParent;
4867        boolean scrolled = false;
4868        while (parent != null) {
4869            rectangle.set((int) position.left, (int) position.top,
4870                    (int) position.right, (int) position.bottom);
4871
4872            scrolled |= parent.requestChildRectangleOnScreen(child,
4873                    rectangle, immediate);
4874
4875            if (!child.hasIdentityMatrix()) {
4876                child.getMatrix().mapRect(position);
4877            }
4878
4879            position.offset(child.mLeft, child.mTop);
4880
4881            if (!(parent instanceof View)) {
4882                break;
4883            }
4884
4885            View parentView = (View) parent;
4886
4887            position.offset(-parentView.getScrollX(), -parentView.getScrollY());
4888
4889            child = parentView;
4890            parent = child.getParent();
4891        }
4892
4893        return scrolled;
4894    }
4895
4896    /**
4897     * Called when this view wants to give up focus. If focus is cleared
4898     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
4899     * <p>
4900     * <strong>Note:</strong> When a View clears focus the framework is trying
4901     * to give focus to the first focusable View from the top. Hence, if this
4902     * View is the first from the top that can take focus, then all callbacks
4903     * related to clearing focus will be invoked after wich the framework will
4904     * give focus to this view.
4905     * </p>
4906     */
4907    public void clearFocus() {
4908        if (DBG) {
4909            System.out.println(this + " clearFocus()");
4910        }
4911
4912        clearFocusInternal(null, true, true);
4913    }
4914
4915    /**
4916     * Clears focus from the view, optionally propagating the change up through
4917     * the parent hierarchy and requesting that the root view place new focus.
4918     *
4919     * @param propagate whether to propagate the change up through the parent
4920     *            hierarchy
4921     * @param refocus when propagate is true, specifies whether to request the
4922     *            root view place new focus
4923     */
4924    void clearFocusInternal(View focused, boolean propagate, boolean refocus) {
4925        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
4926            mPrivateFlags &= ~PFLAG_FOCUSED;
4927
4928            if (propagate && mParent != null) {
4929                mParent.clearChildFocus(this);
4930            }
4931
4932            onFocusChanged(false, 0, null);
4933
4934            manageFocusHotspot(false, focused);
4935            refreshDrawableState();
4936
4937            if (propagate && (!refocus || !rootViewRequestFocus())) {
4938                notifyGlobalFocusCleared(this);
4939            }
4940        }
4941    }
4942
4943    void notifyGlobalFocusCleared(View oldFocus) {
4944        if (oldFocus != null && mAttachInfo != null) {
4945            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
4946        }
4947    }
4948
4949    boolean rootViewRequestFocus() {
4950        final View root = getRootView();
4951        return root != null && root.requestFocus();
4952    }
4953
4954    /**
4955     * Called internally by the view system when a new view is getting focus.
4956     * This is what clears the old focus.
4957     * <p>
4958     * <b>NOTE:</b> The parent view's focused child must be updated manually
4959     * after calling this method. Otherwise, the view hierarchy may be left in
4960     * an inconstent state.
4961     */
4962    void unFocus(View focused) {
4963        if (DBG) {
4964            System.out.println(this + " unFocus()");
4965        }
4966
4967        clearFocusInternal(focused, false, false);
4968    }
4969
4970    /**
4971     * Returns true if this view has focus iteself, or is the ancestor of the
4972     * view that has focus.
4973     *
4974     * @return True if this view has or contains focus, false otherwise.
4975     */
4976    @ViewDebug.ExportedProperty(category = "focus")
4977    public boolean hasFocus() {
4978        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
4979    }
4980
4981    /**
4982     * Returns true if this view is focusable or if it contains a reachable View
4983     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
4984     * is a View whose parents do not block descendants focus.
4985     *
4986     * Only {@link #VISIBLE} views are considered focusable.
4987     *
4988     * @return True if the view is focusable or if the view contains a focusable
4989     *         View, false otherwise.
4990     *
4991     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
4992     */
4993    public boolean hasFocusable() {
4994        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
4995    }
4996
4997    /**
4998     * Called by the view system when the focus state of this view changes.
4999     * When the focus change event is caused by directional navigation, direction
5000     * and previouslyFocusedRect provide insight into where the focus is coming from.
5001     * When overriding, be sure to call up through to the super class so that
5002     * the standard focus handling will occur.
5003     *
5004     * @param gainFocus True if the View has focus; false otherwise.
5005     * @param direction The direction focus has moved when requestFocus()
5006     *                  is called to give this view focus. Values are
5007     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
5008     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
5009     *                  It may not always apply, in which case use the default.
5010     * @param previouslyFocusedRect The rectangle, in this view's coordinate
5011     *        system, of the previously focused view.  If applicable, this will be
5012     *        passed in as finer grained information about where the focus is coming
5013     *        from (in addition to direction).  Will be <code>null</code> otherwise.
5014     */
5015    protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction,
5016            @Nullable Rect previouslyFocusedRect) {
5017        if (gainFocus) {
5018            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
5019        } else {
5020            notifyViewAccessibilityStateChangedIfNeeded(
5021                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
5022        }
5023
5024        InputMethodManager imm = InputMethodManager.peekInstance();
5025        if (!gainFocus) {
5026            if (isPressed()) {
5027                setPressed(false);
5028            }
5029            if (imm != null && mAttachInfo != null
5030                    && mAttachInfo.mHasWindowFocus) {
5031                imm.focusOut(this);
5032            }
5033            onFocusLost();
5034        } else if (imm != null && mAttachInfo != null
5035                && mAttachInfo.mHasWindowFocus) {
5036            imm.focusIn(this);
5037        }
5038
5039        invalidate(true);
5040        ListenerInfo li = mListenerInfo;
5041        if (li != null && li.mOnFocusChangeListener != null) {
5042            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
5043        }
5044
5045        if (mAttachInfo != null) {
5046            mAttachInfo.mKeyDispatchState.reset(this);
5047        }
5048    }
5049
5050    /**
5051     * Sends an accessibility event of the given type. If accessibility is
5052     * not enabled this method has no effect. The default implementation calls
5053     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
5054     * to populate information about the event source (this View), then calls
5055     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
5056     * populate the text content of the event source including its descendants,
5057     * and last calls
5058     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
5059     * on its parent to resuest sending of the event to interested parties.
5060     * <p>
5061     * If an {@link AccessibilityDelegate} has been specified via calling
5062     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5063     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
5064     * responsible for handling this call.
5065     * </p>
5066     *
5067     * @param eventType The type of the event to send, as defined by several types from
5068     * {@link android.view.accessibility.AccessibilityEvent}, such as
5069     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
5070     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
5071     *
5072     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
5073     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5074     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
5075     * @see AccessibilityDelegate
5076     */
5077    public void sendAccessibilityEvent(int eventType) {
5078        if (mAccessibilityDelegate != null) {
5079            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
5080        } else {
5081            sendAccessibilityEventInternal(eventType);
5082        }
5083    }
5084
5085    /**
5086     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
5087     * {@link AccessibilityEvent} to make an announcement which is related to some
5088     * sort of a context change for which none of the events representing UI transitions
5089     * is a good fit. For example, announcing a new page in a book. If accessibility
5090     * is not enabled this method does nothing.
5091     *
5092     * @param text The announcement text.
5093     */
5094    public void announceForAccessibility(CharSequence text) {
5095        if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) {
5096            AccessibilityEvent event = AccessibilityEvent.obtain(
5097                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
5098            onInitializeAccessibilityEvent(event);
5099            event.getText().add(text);
5100            event.setContentDescription(null);
5101            mParent.requestSendAccessibilityEvent(this, event);
5102        }
5103    }
5104
5105    /**
5106     * @see #sendAccessibilityEvent(int)
5107     *
5108     * Note: Called from the default {@link AccessibilityDelegate}.
5109     */
5110    void sendAccessibilityEventInternal(int eventType) {
5111        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
5112            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
5113        }
5114    }
5115
5116    /**
5117     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
5118     * takes as an argument an empty {@link AccessibilityEvent} and does not
5119     * perform a check whether accessibility is enabled.
5120     * <p>
5121     * If an {@link AccessibilityDelegate} has been specified via calling
5122     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5123     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
5124     * is responsible for handling this call.
5125     * </p>
5126     *
5127     * @param event The event to send.
5128     *
5129     * @see #sendAccessibilityEvent(int)
5130     */
5131    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
5132        if (mAccessibilityDelegate != null) {
5133            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
5134        } else {
5135            sendAccessibilityEventUncheckedInternal(event);
5136        }
5137    }
5138
5139    /**
5140     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
5141     *
5142     * Note: Called from the default {@link AccessibilityDelegate}.
5143     */
5144    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
5145        if (!isShown()) {
5146            return;
5147        }
5148        onInitializeAccessibilityEvent(event);
5149        // Only a subset of accessibility events populates text content.
5150        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
5151            dispatchPopulateAccessibilityEvent(event);
5152        }
5153        // In the beginning we called #isShown(), so we know that getParent() is not null.
5154        getParent().requestSendAccessibilityEvent(this, event);
5155    }
5156
5157    /**
5158     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
5159     * to its children for adding their text content to the event. Note that the
5160     * event text is populated in a separate dispatch path since we add to the
5161     * event not only the text of the source but also the text of all its descendants.
5162     * A typical implementation will call
5163     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
5164     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
5165     * on each child. Override this method if custom population of the event text
5166     * content is required.
5167     * <p>
5168     * If an {@link AccessibilityDelegate} has been specified via calling
5169     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5170     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
5171     * is responsible for handling this call.
5172     * </p>
5173     * <p>
5174     * <em>Note:</em> Accessibility events of certain types are not dispatched for
5175     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
5176     * </p>
5177     *
5178     * @param event The event.
5179     *
5180     * @return True if the event population was completed.
5181     */
5182    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
5183        if (mAccessibilityDelegate != null) {
5184            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
5185        } else {
5186            return dispatchPopulateAccessibilityEventInternal(event);
5187        }
5188    }
5189
5190    /**
5191     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5192     *
5193     * Note: Called from the default {@link AccessibilityDelegate}.
5194     */
5195    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
5196        onPopulateAccessibilityEvent(event);
5197        return false;
5198    }
5199
5200    /**
5201     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
5202     * giving a chance to this View to populate the accessibility event with its
5203     * text content. While this method is free to modify event
5204     * attributes other than text content, doing so should normally be performed in
5205     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
5206     * <p>
5207     * Example: Adding formatted date string to an accessibility event in addition
5208     *          to the text added by the super implementation:
5209     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
5210     *     super.onPopulateAccessibilityEvent(event);
5211     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
5212     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
5213     *         mCurrentDate.getTimeInMillis(), flags);
5214     *     event.getText().add(selectedDateUtterance);
5215     * }</pre>
5216     * <p>
5217     * If an {@link AccessibilityDelegate} has been specified via calling
5218     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5219     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
5220     * is responsible for handling this call.
5221     * </p>
5222     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
5223     * information to the event, in case the default implementation has basic information to add.
5224     * </p>
5225     *
5226     * @param event The accessibility event which to populate.
5227     *
5228     * @see #sendAccessibilityEvent(int)
5229     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5230     */
5231    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
5232        if (mAccessibilityDelegate != null) {
5233            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
5234        } else {
5235            onPopulateAccessibilityEventInternal(event);
5236        }
5237    }
5238
5239    /**
5240     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
5241     *
5242     * Note: Called from the default {@link AccessibilityDelegate}.
5243     */
5244    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
5245    }
5246
5247    /**
5248     * Initializes an {@link AccessibilityEvent} with information about
5249     * this View which is the event source. In other words, the source of
5250     * an accessibility event is the view whose state change triggered firing
5251     * the event.
5252     * <p>
5253     * Example: Setting the password property of an event in addition
5254     *          to properties set by the super implementation:
5255     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
5256     *     super.onInitializeAccessibilityEvent(event);
5257     *     event.setPassword(true);
5258     * }</pre>
5259     * <p>
5260     * If an {@link AccessibilityDelegate} has been specified via calling
5261     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5262     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
5263     * is responsible for handling this call.
5264     * </p>
5265     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
5266     * information to the event, in case the default implementation has basic information to add.
5267     * </p>
5268     * @param event The event to initialize.
5269     *
5270     * @see #sendAccessibilityEvent(int)
5271     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5272     */
5273    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
5274        if (mAccessibilityDelegate != null) {
5275            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
5276        } else {
5277            onInitializeAccessibilityEventInternal(event);
5278        }
5279    }
5280
5281    /**
5282     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
5283     *
5284     * Note: Called from the default {@link AccessibilityDelegate}.
5285     */
5286    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
5287        event.setSource(this);
5288        event.setClassName(View.class.getName());
5289        event.setPackageName(getContext().getPackageName());
5290        event.setEnabled(isEnabled());
5291        event.setContentDescription(mContentDescription);
5292
5293        switch (event.getEventType()) {
5294            case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
5295                ArrayList<View> focusablesTempList = (mAttachInfo != null)
5296                        ? mAttachInfo.mTempArrayList : new ArrayList<View>();
5297                getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
5298                event.setItemCount(focusablesTempList.size());
5299                event.setCurrentItemIndex(focusablesTempList.indexOf(this));
5300                if (mAttachInfo != null) {
5301                    focusablesTempList.clear();
5302                }
5303            } break;
5304            case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: {
5305                CharSequence text = getIterableTextForAccessibility();
5306                if (text != null && text.length() > 0) {
5307                    event.setFromIndex(getAccessibilitySelectionStart());
5308                    event.setToIndex(getAccessibilitySelectionEnd());
5309                    event.setItemCount(text.length());
5310                }
5311            } break;
5312        }
5313    }
5314
5315    /**
5316     * Returns an {@link AccessibilityNodeInfo} representing this view from the
5317     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
5318     * This method is responsible for obtaining an accessibility node info from a
5319     * pool of reusable instances and calling
5320     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
5321     * initialize the former.
5322     * <p>
5323     * Note: The client is responsible for recycling the obtained instance by calling
5324     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
5325     * </p>
5326     *
5327     * @return A populated {@link AccessibilityNodeInfo}.
5328     *
5329     * @see AccessibilityNodeInfo
5330     */
5331    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
5332        if (mAccessibilityDelegate != null) {
5333            return mAccessibilityDelegate.createAccessibilityNodeInfo(this);
5334        } else {
5335            return createAccessibilityNodeInfoInternal();
5336        }
5337    }
5338
5339    /**
5340     * @see #createAccessibilityNodeInfo()
5341     */
5342    AccessibilityNodeInfo createAccessibilityNodeInfoInternal() {
5343        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
5344        if (provider != null) {
5345            return provider.createAccessibilityNodeInfo(View.NO_ID);
5346        } else {
5347            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
5348            onInitializeAccessibilityNodeInfo(info);
5349            return info;
5350        }
5351    }
5352
5353    /**
5354     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
5355     * The base implementation sets:
5356     * <ul>
5357     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
5358     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
5359     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
5360     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
5361     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
5362     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
5363     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
5364     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
5365     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
5366     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
5367     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
5368     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
5369     * </ul>
5370     * <p>
5371     * Subclasses should override this method, call the super implementation,
5372     * and set additional attributes.
5373     * </p>
5374     * <p>
5375     * If an {@link AccessibilityDelegate} has been specified via calling
5376     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5377     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
5378     * is responsible for handling this call.
5379     * </p>
5380     *
5381     * @param info The instance to initialize.
5382     */
5383    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
5384        if (mAccessibilityDelegate != null) {
5385            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
5386        } else {
5387            onInitializeAccessibilityNodeInfoInternal(info);
5388        }
5389    }
5390
5391    /**
5392     * Gets the location of this view in screen coordintates.
5393     *
5394     * @param outRect The output location
5395     * @hide
5396     */
5397    public void getBoundsOnScreen(Rect outRect) {
5398        if (mAttachInfo == null) {
5399            return;
5400        }
5401
5402        RectF position = mAttachInfo.mTmpTransformRect;
5403        position.set(0, 0, mRight - mLeft, mBottom - mTop);
5404
5405        if (!hasIdentityMatrix()) {
5406            getMatrix().mapRect(position);
5407        }
5408
5409        position.offset(mLeft, mTop);
5410
5411        ViewParent parent = mParent;
5412        while (parent instanceof View) {
5413            View parentView = (View) parent;
5414
5415            position.offset(-parentView.mScrollX, -parentView.mScrollY);
5416
5417            if (!parentView.hasIdentityMatrix()) {
5418                parentView.getMatrix().mapRect(position);
5419            }
5420
5421            position.offset(parentView.mLeft, parentView.mTop);
5422
5423            parent = parentView.mParent;
5424        }
5425
5426        if (parent instanceof ViewRootImpl) {
5427            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
5428            position.offset(0, -viewRootImpl.mCurScrollY);
5429        }
5430
5431        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
5432
5433        outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f),
5434                (int) (position.right + 0.5f), (int) (position.bottom + 0.5f));
5435    }
5436
5437    /**
5438     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
5439     *
5440     * Note: Called from the default {@link AccessibilityDelegate}.
5441     */
5442    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
5443        Rect bounds = mAttachInfo.mTmpInvalRect;
5444
5445        getDrawingRect(bounds);
5446        info.setBoundsInParent(bounds);
5447
5448        getBoundsOnScreen(bounds);
5449        info.setBoundsInScreen(bounds);
5450
5451        ViewParent parent = getParentForAccessibility();
5452        if (parent instanceof View) {
5453            info.setParent((View) parent);
5454        }
5455
5456        if (mID != View.NO_ID) {
5457            View rootView = getRootView();
5458            if (rootView == null) {
5459                rootView = this;
5460            }
5461            View label = rootView.findLabelForView(this, mID);
5462            if (label != null) {
5463                info.setLabeledBy(label);
5464            }
5465
5466            if ((mAttachInfo.mAccessibilityFetchFlags
5467                    & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0
5468                    && Resources.resourceHasPackage(mID)) {
5469                try {
5470                    String viewId = getResources().getResourceName(mID);
5471                    info.setViewIdResourceName(viewId);
5472                } catch (Resources.NotFoundException nfe) {
5473                    /* ignore */
5474                }
5475            }
5476        }
5477
5478        if (mLabelForId != View.NO_ID) {
5479            View rootView = getRootView();
5480            if (rootView == null) {
5481                rootView = this;
5482            }
5483            View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId);
5484            if (labeled != null) {
5485                info.setLabelFor(labeled);
5486            }
5487        }
5488
5489        info.setVisibleToUser(isVisibleToUser());
5490
5491        info.setPackageName(mContext.getPackageName());
5492        info.setClassName(View.class.getName());
5493        info.setContentDescription(getContentDescription());
5494
5495        info.setEnabled(isEnabled());
5496        info.setClickable(isClickable());
5497        info.setFocusable(isFocusable());
5498        info.setFocused(isFocused());
5499        info.setAccessibilityFocused(isAccessibilityFocused());
5500        info.setSelected(isSelected());
5501        info.setLongClickable(isLongClickable());
5502        info.setLiveRegion(getAccessibilityLiveRegion());
5503
5504        // TODO: These make sense only if we are in an AdapterView but all
5505        // views can be selected. Maybe from accessibility perspective
5506        // we should report as selectable view in an AdapterView.
5507        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
5508        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
5509
5510        if (isFocusable()) {
5511            if (isFocused()) {
5512                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
5513            } else {
5514                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
5515            }
5516        }
5517
5518        if (!isAccessibilityFocused()) {
5519            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
5520        } else {
5521            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
5522        }
5523
5524        if (isClickable() && isEnabled()) {
5525            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
5526        }
5527
5528        if (isLongClickable() && isEnabled()) {
5529            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
5530        }
5531
5532        CharSequence text = getIterableTextForAccessibility();
5533        if (text != null && text.length() > 0) {
5534            info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd());
5535
5536            info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION);
5537            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
5538            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
5539            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
5540                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
5541                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
5542        }
5543    }
5544
5545    private View findLabelForView(View view, int labeledId) {
5546        if (mMatchLabelForPredicate == null) {
5547            mMatchLabelForPredicate = new MatchLabelForPredicate();
5548        }
5549        mMatchLabelForPredicate.mLabeledId = labeledId;
5550        return findViewByPredicateInsideOut(view, mMatchLabelForPredicate);
5551    }
5552
5553    /**
5554     * Computes whether this view is visible to the user. Such a view is
5555     * attached, visible, all its predecessors are visible, it is not clipped
5556     * entirely by its predecessors, and has an alpha greater than zero.
5557     *
5558     * @return Whether the view is visible on the screen.
5559     *
5560     * @hide
5561     */
5562    protected boolean isVisibleToUser() {
5563        return isVisibleToUser(null);
5564    }
5565
5566    /**
5567     * Computes whether the given portion of this view is visible to the user.
5568     * Such a view is attached, visible, all its predecessors are visible,
5569     * has an alpha greater than zero, and the specified portion is not
5570     * clipped entirely by its predecessors.
5571     *
5572     * @param boundInView the portion of the view to test; coordinates should be relative; may be
5573     *                    <code>null</code>, and the entire view will be tested in this case.
5574     *                    When <code>true</code> is returned by the function, the actual visible
5575     *                    region will be stored in this parameter; that is, if boundInView is fully
5576     *                    contained within the view, no modification will be made, otherwise regions
5577     *                    outside of the visible area of the view will be clipped.
5578     *
5579     * @return Whether the specified portion of the view is visible on the screen.
5580     *
5581     * @hide
5582     */
5583    protected boolean isVisibleToUser(Rect boundInView) {
5584        if (mAttachInfo != null) {
5585            // Attached to invisible window means this view is not visible.
5586            if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
5587                return false;
5588            }
5589            // An invisible predecessor or one with alpha zero means
5590            // that this view is not visible to the user.
5591            Object current = this;
5592            while (current instanceof View) {
5593                View view = (View) current;
5594                // We have attach info so this view is attached and there is no
5595                // need to check whether we reach to ViewRootImpl on the way up.
5596                if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 ||
5597                        view.getVisibility() != VISIBLE) {
5598                    return false;
5599                }
5600                current = view.mParent;
5601            }
5602            // Check if the view is entirely covered by its predecessors.
5603            Rect visibleRect = mAttachInfo.mTmpInvalRect;
5604            Point offset = mAttachInfo.mPoint;
5605            if (!getGlobalVisibleRect(visibleRect, offset)) {
5606                return false;
5607            }
5608            // Check if the visible portion intersects the rectangle of interest.
5609            if (boundInView != null) {
5610                visibleRect.offset(-offset.x, -offset.y);
5611                return boundInView.intersect(visibleRect);
5612            }
5613            return true;
5614        }
5615        return false;
5616    }
5617
5618    /**
5619     * Returns the delegate for implementing accessibility support via
5620     * composition. For more details see {@link AccessibilityDelegate}.
5621     *
5622     * @return The delegate, or null if none set.
5623     *
5624     * @hide
5625     */
5626    public AccessibilityDelegate getAccessibilityDelegate() {
5627        return mAccessibilityDelegate;
5628    }
5629
5630    /**
5631     * Sets a delegate for implementing accessibility support via composition as
5632     * opposed to inheritance. The delegate's primary use is for implementing
5633     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
5634     *
5635     * @param delegate The delegate instance.
5636     *
5637     * @see AccessibilityDelegate
5638     */
5639    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
5640        mAccessibilityDelegate = delegate;
5641    }
5642
5643    /**
5644     * Gets the provider for managing a virtual view hierarchy rooted at this View
5645     * and reported to {@link android.accessibilityservice.AccessibilityService}s
5646     * that explore the window content.
5647     * <p>
5648     * If this method returns an instance, this instance is responsible for managing
5649     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
5650     * View including the one representing the View itself. Similarly the returned
5651     * instance is responsible for performing accessibility actions on any virtual
5652     * view or the root view itself.
5653     * </p>
5654     * <p>
5655     * If an {@link AccessibilityDelegate} has been specified via calling
5656     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5657     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
5658     * is responsible for handling this call.
5659     * </p>
5660     *
5661     * @return The provider.
5662     *
5663     * @see AccessibilityNodeProvider
5664     */
5665    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
5666        if (mAccessibilityDelegate != null) {
5667            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
5668        } else {
5669            return null;
5670        }
5671    }
5672
5673    /**
5674     * Gets the unique identifier of this view on the screen for accessibility purposes.
5675     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
5676     *
5677     * @return The view accessibility id.
5678     *
5679     * @hide
5680     */
5681    public int getAccessibilityViewId() {
5682        if (mAccessibilityViewId == NO_ID) {
5683            mAccessibilityViewId = sNextAccessibilityViewId++;
5684        }
5685        return mAccessibilityViewId;
5686    }
5687
5688    /**
5689     * Gets the unique identifier of the window in which this View reseides.
5690     *
5691     * @return The window accessibility id.
5692     *
5693     * @hide
5694     */
5695    public int getAccessibilityWindowId() {
5696        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId
5697                : AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
5698    }
5699
5700    /**
5701     * Gets the {@link View} description. It briefly describes the view and is
5702     * primarily used for accessibility support. Set this property to enable
5703     * better accessibility support for your application. This is especially
5704     * true for views that do not have textual representation (For example,
5705     * ImageButton).
5706     *
5707     * @return The content description.
5708     *
5709     * @attr ref android.R.styleable#View_contentDescription
5710     */
5711    @ViewDebug.ExportedProperty(category = "accessibility")
5712    public CharSequence getContentDescription() {
5713        return mContentDescription;
5714    }
5715
5716    /**
5717     * Sets the {@link View} description. It briefly describes the view and is
5718     * primarily used for accessibility support. Set this property to enable
5719     * better accessibility support for your application. This is especially
5720     * true for views that do not have textual representation (For example,
5721     * ImageButton).
5722     *
5723     * @param contentDescription The content description.
5724     *
5725     * @attr ref android.R.styleable#View_contentDescription
5726     */
5727    @RemotableViewMethod
5728    public void setContentDescription(CharSequence contentDescription) {
5729        if (mContentDescription == null) {
5730            if (contentDescription == null) {
5731                return;
5732            }
5733        } else if (mContentDescription.equals(contentDescription)) {
5734            return;
5735        }
5736        mContentDescription = contentDescription;
5737        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
5738        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
5739            setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
5740            notifySubtreeAccessibilityStateChangedIfNeeded();
5741        } else {
5742            notifyViewAccessibilityStateChangedIfNeeded(
5743                    AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION);
5744        }
5745    }
5746
5747    /**
5748     * Gets the id of a view for which this view serves as a label for
5749     * accessibility purposes.
5750     *
5751     * @return The labeled view id.
5752     */
5753    @ViewDebug.ExportedProperty(category = "accessibility")
5754    public int getLabelFor() {
5755        return mLabelForId;
5756    }
5757
5758    /**
5759     * Sets the id of a view for which this view serves as a label for
5760     * accessibility purposes.
5761     *
5762     * @param id The labeled view id.
5763     */
5764    @RemotableViewMethod
5765    public void setLabelFor(int id) {
5766        mLabelForId = id;
5767        if (mLabelForId != View.NO_ID
5768                && mID == View.NO_ID) {
5769            mID = generateViewId();
5770        }
5771    }
5772
5773    /**
5774     * Invoked whenever this view loses focus, either by losing window focus or by losing
5775     * focus within its window. This method can be used to clear any state tied to the
5776     * focus. For instance, if a button is held pressed with the trackball and the window
5777     * loses focus, this method can be used to cancel the press.
5778     *
5779     * Subclasses of View overriding this method should always call super.onFocusLost().
5780     *
5781     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
5782     * @see #onWindowFocusChanged(boolean)
5783     *
5784     * @hide pending API council approval
5785     */
5786    protected void onFocusLost() {
5787        resetPressedState();
5788    }
5789
5790    private void resetPressedState() {
5791        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
5792            return;
5793        }
5794
5795        if (isPressed()) {
5796            setPressed(false);
5797
5798            if (!mHasPerformedLongPress) {
5799                removeLongPressCallback();
5800            }
5801        }
5802    }
5803
5804    /**
5805     * Returns true if this view has focus
5806     *
5807     * @return True if this view has focus, false otherwise.
5808     */
5809    @ViewDebug.ExportedProperty(category = "focus")
5810    public boolean isFocused() {
5811        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
5812    }
5813
5814    /**
5815     * Find the view in the hierarchy rooted at this view that currently has
5816     * focus.
5817     *
5818     * @return The view that currently has focus, or null if no focused view can
5819     *         be found.
5820     */
5821    public View findFocus() {
5822        return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
5823    }
5824
5825    /**
5826     * Indicates whether this view is one of the set of scrollable containers in
5827     * its window.
5828     *
5829     * @return whether this view is one of the set of scrollable containers in
5830     * its window
5831     *
5832     * @attr ref android.R.styleable#View_isScrollContainer
5833     */
5834    public boolean isScrollContainer() {
5835        return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0;
5836    }
5837
5838    /**
5839     * Change whether this view is one of the set of scrollable containers in
5840     * its window.  This will be used to determine whether the window can
5841     * resize or must pan when a soft input area is open -- scrollable
5842     * containers allow the window to use resize mode since the container
5843     * will appropriately shrink.
5844     *
5845     * @attr ref android.R.styleable#View_isScrollContainer
5846     */
5847    public void setScrollContainer(boolean isScrollContainer) {
5848        if (isScrollContainer) {
5849            if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) {
5850                mAttachInfo.mScrollContainers.add(this);
5851                mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
5852            }
5853            mPrivateFlags |= PFLAG_SCROLL_CONTAINER;
5854        } else {
5855            if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
5856                mAttachInfo.mScrollContainers.remove(this);
5857            }
5858            mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED);
5859        }
5860    }
5861
5862    /**
5863     * Returns the quality of the drawing cache.
5864     *
5865     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5866     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5867     *
5868     * @see #setDrawingCacheQuality(int)
5869     * @see #setDrawingCacheEnabled(boolean)
5870     * @see #isDrawingCacheEnabled()
5871     *
5872     * @attr ref android.R.styleable#View_drawingCacheQuality
5873     */
5874    @DrawingCacheQuality
5875    public int getDrawingCacheQuality() {
5876        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
5877    }
5878
5879    /**
5880     * Set the drawing cache quality of this view. This value is used only when the
5881     * drawing cache is enabled
5882     *
5883     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5884     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5885     *
5886     * @see #getDrawingCacheQuality()
5887     * @see #setDrawingCacheEnabled(boolean)
5888     * @see #isDrawingCacheEnabled()
5889     *
5890     * @attr ref android.R.styleable#View_drawingCacheQuality
5891     */
5892    public void setDrawingCacheQuality(@DrawingCacheQuality int quality) {
5893        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
5894    }
5895
5896    /**
5897     * Returns whether the screen should remain on, corresponding to the current
5898     * value of {@link #KEEP_SCREEN_ON}.
5899     *
5900     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
5901     *
5902     * @see #setKeepScreenOn(boolean)
5903     *
5904     * @attr ref android.R.styleable#View_keepScreenOn
5905     */
5906    public boolean getKeepScreenOn() {
5907        return (mViewFlags & KEEP_SCREEN_ON) != 0;
5908    }
5909
5910    /**
5911     * Controls whether the screen should remain on, modifying the
5912     * value of {@link #KEEP_SCREEN_ON}.
5913     *
5914     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
5915     *
5916     * @see #getKeepScreenOn()
5917     *
5918     * @attr ref android.R.styleable#View_keepScreenOn
5919     */
5920    public void setKeepScreenOn(boolean keepScreenOn) {
5921        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
5922    }
5923
5924    /**
5925     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5926     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5927     *
5928     * @attr ref android.R.styleable#View_nextFocusLeft
5929     */
5930    public int getNextFocusLeftId() {
5931        return mNextFocusLeftId;
5932    }
5933
5934    /**
5935     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5936     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
5937     * decide automatically.
5938     *
5939     * @attr ref android.R.styleable#View_nextFocusLeft
5940     */
5941    public void setNextFocusLeftId(int nextFocusLeftId) {
5942        mNextFocusLeftId = nextFocusLeftId;
5943    }
5944
5945    /**
5946     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5947     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5948     *
5949     * @attr ref android.R.styleable#View_nextFocusRight
5950     */
5951    public int getNextFocusRightId() {
5952        return mNextFocusRightId;
5953    }
5954
5955    /**
5956     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5957     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
5958     * decide automatically.
5959     *
5960     * @attr ref android.R.styleable#View_nextFocusRight
5961     */
5962    public void setNextFocusRightId(int nextFocusRightId) {
5963        mNextFocusRightId = nextFocusRightId;
5964    }
5965
5966    /**
5967     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5968     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5969     *
5970     * @attr ref android.R.styleable#View_nextFocusUp
5971     */
5972    public int getNextFocusUpId() {
5973        return mNextFocusUpId;
5974    }
5975
5976    /**
5977     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5978     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
5979     * decide automatically.
5980     *
5981     * @attr ref android.R.styleable#View_nextFocusUp
5982     */
5983    public void setNextFocusUpId(int nextFocusUpId) {
5984        mNextFocusUpId = nextFocusUpId;
5985    }
5986
5987    /**
5988     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5989     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5990     *
5991     * @attr ref android.R.styleable#View_nextFocusDown
5992     */
5993    public int getNextFocusDownId() {
5994        return mNextFocusDownId;
5995    }
5996
5997    /**
5998     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5999     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
6000     * decide automatically.
6001     *
6002     * @attr ref android.R.styleable#View_nextFocusDown
6003     */
6004    public void setNextFocusDownId(int nextFocusDownId) {
6005        mNextFocusDownId = nextFocusDownId;
6006    }
6007
6008    /**
6009     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
6010     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6011     *
6012     * @attr ref android.R.styleable#View_nextFocusForward
6013     */
6014    public int getNextFocusForwardId() {
6015        return mNextFocusForwardId;
6016    }
6017
6018    /**
6019     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
6020     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
6021     * decide automatically.
6022     *
6023     * @attr ref android.R.styleable#View_nextFocusForward
6024     */
6025    public void setNextFocusForwardId(int nextFocusForwardId) {
6026        mNextFocusForwardId = nextFocusForwardId;
6027    }
6028
6029    /**
6030     * Returns the visibility of this view and all of its ancestors
6031     *
6032     * @return True if this view and all of its ancestors are {@link #VISIBLE}
6033     */
6034    public boolean isShown() {
6035        View current = this;
6036        //noinspection ConstantConditions
6037        do {
6038            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6039                return false;
6040            }
6041            ViewParent parent = current.mParent;
6042            if (parent == null) {
6043                return false; // We are not attached to the view root
6044            }
6045            if (!(parent instanceof View)) {
6046                return true;
6047            }
6048            current = (View) parent;
6049        } while (current != null);
6050
6051        return false;
6052    }
6053
6054    /**
6055     * Called by the view hierarchy when the content insets for a window have
6056     * changed, to allow it to adjust its content to fit within those windows.
6057     * The content insets tell you the space that the status bar, input method,
6058     * and other system windows infringe on the application's window.
6059     *
6060     * <p>You do not normally need to deal with this function, since the default
6061     * window decoration given to applications takes care of applying it to the
6062     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
6063     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
6064     * and your content can be placed under those system elements.  You can then
6065     * use this method within your view hierarchy if you have parts of your UI
6066     * which you would like to ensure are not being covered.
6067     *
6068     * <p>The default implementation of this method simply applies the content
6069     * insets to the view's padding, consuming that content (modifying the
6070     * insets to be 0), and returning true.  This behavior is off by default, but can
6071     * be enabled through {@link #setFitsSystemWindows(boolean)}.
6072     *
6073     * <p>This function's traversal down the hierarchy is depth-first.  The same content
6074     * insets object is propagated down the hierarchy, so any changes made to it will
6075     * be seen by all following views (including potentially ones above in
6076     * the hierarchy since this is a depth-first traversal).  The first view
6077     * that returns true will abort the entire traversal.
6078     *
6079     * <p>The default implementation works well for a situation where it is
6080     * used with a container that covers the entire window, allowing it to
6081     * apply the appropriate insets to its content on all edges.  If you need
6082     * a more complicated layout (such as two different views fitting system
6083     * windows, one on the top of the window, and one on the bottom),
6084     * you can override the method and handle the insets however you would like.
6085     * Note that the insets provided by the framework are always relative to the
6086     * far edges of the window, not accounting for the location of the called view
6087     * within that window.  (In fact when this method is called you do not yet know
6088     * where the layout will place the view, as it is done before layout happens.)
6089     *
6090     * <p>Note: unlike many View methods, there is no dispatch phase to this
6091     * call.  If you are overriding it in a ViewGroup and want to allow the
6092     * call to continue to your children, you must be sure to call the super
6093     * implementation.
6094     *
6095     * <p>Here is a sample layout that makes use of fitting system windows
6096     * to have controls for a video view placed inside of the window decorations
6097     * that it hides and shows.  This can be used with code like the second
6098     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
6099     *
6100     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
6101     *
6102     * @param insets Current content insets of the window.  Prior to
6103     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
6104     * the insets or else you and Android will be unhappy.
6105     *
6106     * @return {@code true} if this view applied the insets and it should not
6107     * continue propagating further down the hierarchy, {@code false} otherwise.
6108     * @see #getFitsSystemWindows()
6109     * @see #setFitsSystemWindows(boolean)
6110     * @see #setSystemUiVisibility(int)
6111     *
6112     * @deprecated As of API XX use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply
6113     * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use
6114     * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)}
6115     * to implement handling their own insets.
6116     */
6117    protected boolean fitSystemWindows(Rect insets) {
6118        if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) {
6119            // If we're not in the process of dispatching the newer apply insets call,
6120            // that means we're not in the compatibility path. Dispatch into the newer
6121            // apply insets path and take things from there.
6122            try {
6123                mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS;
6124                return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed();
6125            } finally {
6126                mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS;
6127            }
6128        } else {
6129            // We're being called from the newer apply insets path.
6130            // Perform the standard fallback behavior.
6131            return fitSystemWindowsInt(insets);
6132        }
6133    }
6134
6135    private boolean fitSystemWindowsInt(Rect insets) {
6136        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
6137            mUserPaddingStart = UNDEFINED_PADDING;
6138            mUserPaddingEnd = UNDEFINED_PADDING;
6139            Rect localInsets = sThreadLocal.get();
6140            if (localInsets == null) {
6141                localInsets = new Rect();
6142                sThreadLocal.set(localInsets);
6143            }
6144            boolean res = computeFitSystemWindows(insets, localInsets);
6145            mUserPaddingLeftInitial = localInsets.left;
6146            mUserPaddingRightInitial = localInsets.right;
6147            internalSetPadding(localInsets.left, localInsets.top,
6148                    localInsets.right, localInsets.bottom);
6149            return res;
6150        }
6151        return false;
6152    }
6153
6154    /**
6155     * Called when the view should apply {@link WindowInsets} according to its internal policy.
6156     *
6157     * <p>This method should be overridden by views that wish to apply a policy different from or
6158     * in addition to the default behavior. Clients that wish to force a view subtree
6159     * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p>
6160     *
6161     * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set
6162     * it will be called during dispatch instead of this method. The listener may optionally
6163     * call this method from its own implementation if it wishes to apply the view's default
6164     * insets policy in addition to its own.</p>
6165     *
6166     * <p>Implementations of this method should either return the insets parameter unchanged
6167     * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed
6168     * that this view applied itself. This allows new inset types added in future platform
6169     * versions to pass through existing implementations unchanged without being erroneously
6170     * consumed.</p>
6171     *
6172     * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows}
6173     * property is set then the view will consume the system window insets and apply them
6174     * as padding for the view.</p>
6175     *
6176     * @param insets Insets to apply
6177     * @return The supplied insets with any applied insets consumed
6178     */
6179    public WindowInsets onApplyWindowInsets(WindowInsets insets) {
6180        if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) {
6181            // We weren't called from within a direct call to fitSystemWindows,
6182            // call into it as a fallback in case we're in a class that overrides it
6183            // and has logic to perform.
6184            if (fitSystemWindows(insets.getSystemWindowInsets())) {
6185                return insets.consumeSystemWindowInsets();
6186            }
6187        } else {
6188            // We were called from within a direct call to fitSystemWindows.
6189            if (fitSystemWindowsInt(insets.getSystemWindowInsets())) {
6190                return insets.consumeSystemWindowInsets();
6191            }
6192        }
6193        return insets;
6194    }
6195
6196    /**
6197     * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying
6198     * window insets to this view. The listener's
6199     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
6200     * method will be called instead of the view's
6201     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
6202     *
6203     * @param listener Listener to set
6204     *
6205     * @see #onApplyWindowInsets(WindowInsets)
6206     */
6207    public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) {
6208        getListenerInfo().mOnApplyWindowInsetsListener = listener;
6209    }
6210
6211    /**
6212     * Request to apply the given window insets to this view or another view in its subtree.
6213     *
6214     * <p>This method should be called by clients wishing to apply insets corresponding to areas
6215     * obscured by window decorations or overlays. This can include the status and navigation bars,
6216     * action bars, input methods and more. New inset categories may be added in the future.
6217     * The method returns the insets provided minus any that were applied by this view or its
6218     * children.</p>
6219     *
6220     * <p>Clients wishing to provide custom behavior should override the
6221     * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a
6222     * {@link OnApplyWindowInsetsListener} via the
6223     * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener}
6224     * method.</p>
6225     *
6226     * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method.
6227     * </p>
6228     *
6229     * @param insets Insets to apply
6230     * @return The provided insets minus the insets that were consumed
6231     */
6232    public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) {
6233        try {
6234            mPrivateFlags3 |= PFLAG3_APPLYING_INSETS;
6235            if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) {
6236                return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets);
6237            } else {
6238                return onApplyWindowInsets(insets);
6239            }
6240        } finally {
6241            mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS;
6242        }
6243    }
6244
6245    /**
6246     * @hide Compute the insets that should be consumed by this view and the ones
6247     * that should propagate to those under it.
6248     */
6249    protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) {
6250        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
6251                || mAttachInfo == null
6252                || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0
6253                        && !mAttachInfo.mOverscanRequested)) {
6254            outLocalInsets.set(inoutInsets);
6255            inoutInsets.set(0, 0, 0, 0);
6256            return true;
6257        } else {
6258            // The application wants to take care of fitting system window for
6259            // the content...  however we still need to take care of any overscan here.
6260            final Rect overscan = mAttachInfo.mOverscanInsets;
6261            outLocalInsets.set(overscan);
6262            inoutInsets.left -= overscan.left;
6263            inoutInsets.top -= overscan.top;
6264            inoutInsets.right -= overscan.right;
6265            inoutInsets.bottom -= overscan.bottom;
6266            return false;
6267        }
6268    }
6269
6270    /**
6271     * Sets whether or not this view should account for system screen decorations
6272     * such as the status bar and inset its content; that is, controlling whether
6273     * the default implementation of {@link #fitSystemWindows(Rect)} will be
6274     * executed.  See that method for more details.
6275     *
6276     * <p>Note that if you are providing your own implementation of
6277     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
6278     * flag to true -- your implementation will be overriding the default
6279     * implementation that checks this flag.
6280     *
6281     * @param fitSystemWindows If true, then the default implementation of
6282     * {@link #fitSystemWindows(Rect)} will be executed.
6283     *
6284     * @attr ref android.R.styleable#View_fitsSystemWindows
6285     * @see #getFitsSystemWindows()
6286     * @see #fitSystemWindows(Rect)
6287     * @see #setSystemUiVisibility(int)
6288     */
6289    public void setFitsSystemWindows(boolean fitSystemWindows) {
6290        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
6291    }
6292
6293    /**
6294     * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method
6295     * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)}
6296     * will be executed.
6297     *
6298     * @return {@code true} if the default implementation of
6299     * {@link #fitSystemWindows(Rect)} will be executed.
6300     *
6301     * @attr ref android.R.styleable#View_fitsSystemWindows
6302     * @see #setFitsSystemWindows(boolean)
6303     * @see #fitSystemWindows(Rect)
6304     * @see #setSystemUiVisibility(int)
6305     */
6306    public boolean getFitsSystemWindows() {
6307        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
6308    }
6309
6310    /** @hide */
6311    public boolean fitsSystemWindows() {
6312        return getFitsSystemWindows();
6313    }
6314
6315    /**
6316     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
6317     * @deprecated Use {@link #requestApplyInsets()} for newer platform versions.
6318     */
6319    public void requestFitSystemWindows() {
6320        if (mParent != null) {
6321            mParent.requestFitSystemWindows();
6322        }
6323    }
6324
6325    /**
6326     * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed.
6327     */
6328    public void requestApplyInsets() {
6329        requestFitSystemWindows();
6330    }
6331
6332    /**
6333     * For use by PhoneWindow to make its own system window fitting optional.
6334     * @hide
6335     */
6336    public void makeOptionalFitsSystemWindows() {
6337        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
6338    }
6339
6340    /**
6341     * Returns the visibility status for this view.
6342     *
6343     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
6344     * @attr ref android.R.styleable#View_visibility
6345     */
6346    @ViewDebug.ExportedProperty(mapping = {
6347        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
6348        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
6349        @ViewDebug.IntToString(from = GONE,      to = "GONE")
6350    })
6351    @Visibility
6352    public int getVisibility() {
6353        return mViewFlags & VISIBILITY_MASK;
6354    }
6355
6356    /**
6357     * Set the enabled state of this view.
6358     *
6359     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
6360     * @attr ref android.R.styleable#View_visibility
6361     */
6362    @RemotableViewMethod
6363    public void setVisibility(@Visibility int visibility) {
6364        setFlags(visibility, VISIBILITY_MASK);
6365        if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false);
6366    }
6367
6368    /**
6369     * Returns the enabled status for this view. The interpretation of the
6370     * enabled state varies by subclass.
6371     *
6372     * @return True if this view is enabled, false otherwise.
6373     */
6374    @ViewDebug.ExportedProperty
6375    public boolean isEnabled() {
6376        return (mViewFlags & ENABLED_MASK) == ENABLED;
6377    }
6378
6379    /**
6380     * Set the enabled state of this view. The interpretation of the enabled
6381     * state varies by subclass.
6382     *
6383     * @param enabled True if this view is enabled, false otherwise.
6384     */
6385    @RemotableViewMethod
6386    public void setEnabled(boolean enabled) {
6387        if (enabled == isEnabled()) return;
6388
6389        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
6390
6391        /*
6392         * The View most likely has to change its appearance, so refresh
6393         * the drawable state.
6394         */
6395        refreshDrawableState();
6396
6397        // Invalidate too, since the default behavior for views is to be
6398        // be drawn at 50% alpha rather than to change the drawable.
6399        invalidate(true);
6400
6401        if (!enabled) {
6402            cancelPendingInputEvents();
6403        }
6404    }
6405
6406    /**
6407     * Set whether this view can receive the focus.
6408     *
6409     * Setting this to false will also ensure that this view is not focusable
6410     * in touch mode.
6411     *
6412     * @param focusable If true, this view can receive the focus.
6413     *
6414     * @see #setFocusableInTouchMode(boolean)
6415     * @attr ref android.R.styleable#View_focusable
6416     */
6417    public void setFocusable(boolean focusable) {
6418        if (!focusable) {
6419            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
6420        }
6421        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
6422    }
6423
6424    /**
6425     * Set whether this view can receive focus while in touch mode.
6426     *
6427     * Setting this to true will also ensure that this view is focusable.
6428     *
6429     * @param focusableInTouchMode If true, this view can receive the focus while
6430     *   in touch mode.
6431     *
6432     * @see #setFocusable(boolean)
6433     * @attr ref android.R.styleable#View_focusableInTouchMode
6434     */
6435    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
6436        // Focusable in touch mode should always be set before the focusable flag
6437        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
6438        // which, in touch mode, will not successfully request focus on this view
6439        // because the focusable in touch mode flag is not set
6440        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
6441        if (focusableInTouchMode) {
6442            setFlags(FOCUSABLE, FOCUSABLE_MASK);
6443        }
6444    }
6445
6446    /**
6447     * Set whether this view should have sound effects enabled for events such as
6448     * clicking and touching.
6449     *
6450     * <p>You may wish to disable sound effects for a view if you already play sounds,
6451     * for instance, a dial key that plays dtmf tones.
6452     *
6453     * @param soundEffectsEnabled whether sound effects are enabled for this view.
6454     * @see #isSoundEffectsEnabled()
6455     * @see #playSoundEffect(int)
6456     * @attr ref android.R.styleable#View_soundEffectsEnabled
6457     */
6458    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
6459        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
6460    }
6461
6462    /**
6463     * @return whether this view should have sound effects enabled for events such as
6464     *     clicking and touching.
6465     *
6466     * @see #setSoundEffectsEnabled(boolean)
6467     * @see #playSoundEffect(int)
6468     * @attr ref android.R.styleable#View_soundEffectsEnabled
6469     */
6470    @ViewDebug.ExportedProperty
6471    public boolean isSoundEffectsEnabled() {
6472        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
6473    }
6474
6475    /**
6476     * Set whether this view should have haptic feedback for events such as
6477     * long presses.
6478     *
6479     * <p>You may wish to disable haptic feedback if your view already controls
6480     * its own haptic feedback.
6481     *
6482     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
6483     * @see #isHapticFeedbackEnabled()
6484     * @see #performHapticFeedback(int)
6485     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
6486     */
6487    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
6488        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
6489    }
6490
6491    /**
6492     * @return whether this view should have haptic feedback enabled for events
6493     * long presses.
6494     *
6495     * @see #setHapticFeedbackEnabled(boolean)
6496     * @see #performHapticFeedback(int)
6497     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
6498     */
6499    @ViewDebug.ExportedProperty
6500    public boolean isHapticFeedbackEnabled() {
6501        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
6502    }
6503
6504    /**
6505     * Returns the layout direction for this view.
6506     *
6507     * @return One of {@link #LAYOUT_DIRECTION_LTR},
6508     *   {@link #LAYOUT_DIRECTION_RTL},
6509     *   {@link #LAYOUT_DIRECTION_INHERIT} or
6510     *   {@link #LAYOUT_DIRECTION_LOCALE}.
6511     *
6512     * @attr ref android.R.styleable#View_layoutDirection
6513     *
6514     * @hide
6515     */
6516    @ViewDebug.ExportedProperty(category = "layout", mapping = {
6517        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
6518        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
6519        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
6520        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
6521    })
6522    @LayoutDir
6523    public int getRawLayoutDirection() {
6524        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
6525    }
6526
6527    /**
6528     * Set the layout direction for this view. This will propagate a reset of layout direction
6529     * resolution to the view's children and resolve layout direction for this view.
6530     *
6531     * @param layoutDirection the layout direction to set. Should be one of:
6532     *
6533     * {@link #LAYOUT_DIRECTION_LTR},
6534     * {@link #LAYOUT_DIRECTION_RTL},
6535     * {@link #LAYOUT_DIRECTION_INHERIT},
6536     * {@link #LAYOUT_DIRECTION_LOCALE}.
6537     *
6538     * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution
6539     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
6540     * will return the default {@link #LAYOUT_DIRECTION_LTR}.
6541     *
6542     * @attr ref android.R.styleable#View_layoutDirection
6543     */
6544    @RemotableViewMethod
6545    public void setLayoutDirection(@LayoutDir int layoutDirection) {
6546        if (getRawLayoutDirection() != layoutDirection) {
6547            // Reset the current layout direction and the resolved one
6548            mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK;
6549            resetRtlProperties();
6550            // Set the new layout direction (filtered)
6551            mPrivateFlags2 |=
6552                    ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK);
6553            // We need to resolve all RTL properties as they all depend on layout direction
6554            resolveRtlPropertiesIfNeeded();
6555            requestLayout();
6556            invalidate(true);
6557        }
6558    }
6559
6560    /**
6561     * Returns the resolved layout direction for this view.
6562     *
6563     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
6564     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
6565     *
6566     * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version
6567     * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}.
6568     *
6569     * @attr ref android.R.styleable#View_layoutDirection
6570     */
6571    @ViewDebug.ExportedProperty(category = "layout", mapping = {
6572        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
6573        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
6574    })
6575    @ResolvedLayoutDir
6576    public int getLayoutDirection() {
6577        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
6578        if (targetSdkVersion < JELLY_BEAN_MR1) {
6579            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
6580            return LAYOUT_DIRECTION_RESOLVED_DEFAULT;
6581        }
6582        return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ==
6583                PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
6584    }
6585
6586    /**
6587     * Indicates whether or not this view's layout is right-to-left. This is resolved from
6588     * layout attribute and/or the inherited value from the parent
6589     *
6590     * @return true if the layout is right-to-left.
6591     *
6592     * @hide
6593     */
6594    @ViewDebug.ExportedProperty(category = "layout")
6595    public boolean isLayoutRtl() {
6596        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
6597    }
6598
6599    /**
6600     * Indicates whether the view is currently tracking transient state that the
6601     * app should not need to concern itself with saving and restoring, but that
6602     * the framework should take special note to preserve when possible.
6603     *
6604     * <p>A view with transient state cannot be trivially rebound from an external
6605     * data source, such as an adapter binding item views in a list. This may be
6606     * because the view is performing an animation, tracking user selection
6607     * of content, or similar.</p>
6608     *
6609     * @return true if the view has transient state
6610     */
6611    @ViewDebug.ExportedProperty(category = "layout")
6612    public boolean hasTransientState() {
6613        return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE;
6614    }
6615
6616    /**
6617     * Set whether this view is currently tracking transient state that the
6618     * framework should attempt to preserve when possible. This flag is reference counted,
6619     * so every call to setHasTransientState(true) should be paired with a later call
6620     * to setHasTransientState(false).
6621     *
6622     * <p>A view with transient state cannot be trivially rebound from an external
6623     * data source, such as an adapter binding item views in a list. This may be
6624     * because the view is performing an animation, tracking user selection
6625     * of content, or similar.</p>
6626     *
6627     * @param hasTransientState true if this view has transient state
6628     */
6629    public void setHasTransientState(boolean hasTransientState) {
6630        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
6631                mTransientStateCount - 1;
6632        if (mTransientStateCount < 0) {
6633            mTransientStateCount = 0;
6634            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
6635                    "unmatched pair of setHasTransientState calls");
6636        } else if ((hasTransientState && mTransientStateCount == 1) ||
6637                (!hasTransientState && mTransientStateCount == 0)) {
6638            // update flag if we've just incremented up from 0 or decremented down to 0
6639            mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) |
6640                    (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0);
6641            if (mParent != null) {
6642                try {
6643                    mParent.childHasTransientStateChanged(this, hasTransientState);
6644                } catch (AbstractMethodError e) {
6645                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
6646                            " does not fully implement ViewParent", e);
6647                }
6648            }
6649        }
6650    }
6651
6652    /**
6653     * Returns true if this view is currently attached to a window.
6654     */
6655    public boolean isAttachedToWindow() {
6656        return mAttachInfo != null;
6657    }
6658
6659    /**
6660     * Returns true if this view has been through at least one layout since it
6661     * was last attached to or detached from a window.
6662     */
6663    public boolean isLaidOut() {
6664        return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT;
6665    }
6666
6667    /**
6668     * If this view doesn't do any drawing on its own, set this flag to
6669     * allow further optimizations. By default, this flag is not set on
6670     * View, but could be set on some View subclasses such as ViewGroup.
6671     *
6672     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
6673     * you should clear this flag.
6674     *
6675     * @param willNotDraw whether or not this View draw on its own
6676     */
6677    public void setWillNotDraw(boolean willNotDraw) {
6678        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
6679    }
6680
6681    /**
6682     * Returns whether or not this View draws on its own.
6683     *
6684     * @return true if this view has nothing to draw, false otherwise
6685     */
6686    @ViewDebug.ExportedProperty(category = "drawing")
6687    public boolean willNotDraw() {
6688        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
6689    }
6690
6691    /**
6692     * When a View's drawing cache is enabled, drawing is redirected to an
6693     * offscreen bitmap. Some views, like an ImageView, must be able to
6694     * bypass this mechanism if they already draw a single bitmap, to avoid
6695     * unnecessary usage of the memory.
6696     *
6697     * @param willNotCacheDrawing true if this view does not cache its
6698     *        drawing, false otherwise
6699     */
6700    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
6701        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
6702    }
6703
6704    /**
6705     * Returns whether or not this View can cache its drawing or not.
6706     *
6707     * @return true if this view does not cache its drawing, false otherwise
6708     */
6709    @ViewDebug.ExportedProperty(category = "drawing")
6710    public boolean willNotCacheDrawing() {
6711        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
6712    }
6713
6714    /**
6715     * Indicates whether this view reacts to click events or not.
6716     *
6717     * @return true if the view is clickable, false otherwise
6718     *
6719     * @see #setClickable(boolean)
6720     * @attr ref android.R.styleable#View_clickable
6721     */
6722    @ViewDebug.ExportedProperty
6723    public boolean isClickable() {
6724        return (mViewFlags & CLICKABLE) == CLICKABLE;
6725    }
6726
6727    /**
6728     * Enables or disables click events for this view. When a view
6729     * is clickable it will change its state to "pressed" on every click.
6730     * Subclasses should set the view clickable to visually react to
6731     * user's clicks.
6732     *
6733     * @param clickable true to make the view clickable, false otherwise
6734     *
6735     * @see #isClickable()
6736     * @attr ref android.R.styleable#View_clickable
6737     */
6738    public void setClickable(boolean clickable) {
6739        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
6740    }
6741
6742    /**
6743     * Indicates whether this view reacts to long click events or not.
6744     *
6745     * @return true if the view is long clickable, false otherwise
6746     *
6747     * @see #setLongClickable(boolean)
6748     * @attr ref android.R.styleable#View_longClickable
6749     */
6750    public boolean isLongClickable() {
6751        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
6752    }
6753
6754    /**
6755     * Enables or disables long click events for this view. When a view is long
6756     * clickable it reacts to the user holding down the button for a longer
6757     * duration than a tap. This event can either launch the listener or a
6758     * context menu.
6759     *
6760     * @param longClickable true to make the view long clickable, false otherwise
6761     * @see #isLongClickable()
6762     * @attr ref android.R.styleable#View_longClickable
6763     */
6764    public void setLongClickable(boolean longClickable) {
6765        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
6766    }
6767
6768    /**
6769     * Sets the pressed state for this view and provides a touch coordinate for
6770     * animation hinting.
6771     *
6772     * @param pressed Pass true to set the View's internal state to "pressed",
6773     *            or false to reverts the View's internal state from a
6774     *            previously set "pressed" state.
6775     * @param x The x coordinate of the touch that caused the press
6776     * @param y The y coordinate of the touch that caused the press
6777     */
6778    private void setPressed(boolean pressed, float x, float y) {
6779        if (pressed) {
6780            setDrawableHotspot(x, y);
6781        }
6782
6783        setPressed(pressed);
6784    }
6785
6786    /**
6787     * Sets the pressed state for this view.
6788     *
6789     * @see #isClickable()
6790     * @see #setClickable(boolean)
6791     *
6792     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
6793     *        the View's internal state from a previously set "pressed" state.
6794     */
6795    public void setPressed(boolean pressed) {
6796        final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
6797
6798        if (pressed) {
6799            mPrivateFlags |= PFLAG_PRESSED;
6800        } else {
6801            mPrivateFlags &= ~PFLAG_PRESSED;
6802        }
6803
6804        if (needsRefresh) {
6805            refreshDrawableState();
6806        }
6807        dispatchSetPressed(pressed);
6808    }
6809
6810    /**
6811     * Dispatch setPressed to all of this View's children.
6812     *
6813     * @see #setPressed(boolean)
6814     *
6815     * @param pressed The new pressed state
6816     */
6817    protected void dispatchSetPressed(boolean pressed) {
6818    }
6819
6820    /**
6821     * Indicates whether the view is currently in pressed state. Unless
6822     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
6823     * the pressed state.
6824     *
6825     * @see #setPressed(boolean)
6826     * @see #isClickable()
6827     * @see #setClickable(boolean)
6828     *
6829     * @return true if the view is currently pressed, false otherwise
6830     */
6831    public boolean isPressed() {
6832        return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED;
6833    }
6834
6835    /**
6836     * Indicates whether this view will save its state (that is,
6837     * whether its {@link #onSaveInstanceState} method will be called).
6838     *
6839     * @return Returns true if the view state saving is enabled, else false.
6840     *
6841     * @see #setSaveEnabled(boolean)
6842     * @attr ref android.R.styleable#View_saveEnabled
6843     */
6844    public boolean isSaveEnabled() {
6845        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
6846    }
6847
6848    /**
6849     * Controls whether the saving of this view's state is
6850     * enabled (that is, whether its {@link #onSaveInstanceState} method
6851     * will be called).  Note that even if freezing is enabled, the
6852     * view still must have an id assigned to it (via {@link #setId(int)})
6853     * for its state to be saved.  This flag can only disable the
6854     * saving of this view; any child views may still have their state saved.
6855     *
6856     * @param enabled Set to false to <em>disable</em> state saving, or true
6857     * (the default) to allow it.
6858     *
6859     * @see #isSaveEnabled()
6860     * @see #setId(int)
6861     * @see #onSaveInstanceState()
6862     * @attr ref android.R.styleable#View_saveEnabled
6863     */
6864    public void setSaveEnabled(boolean enabled) {
6865        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
6866    }
6867
6868    /**
6869     * Gets whether the framework should discard touches when the view's
6870     * window is obscured by another visible window.
6871     * Refer to the {@link View} security documentation for more details.
6872     *
6873     * @return True if touch filtering is enabled.
6874     *
6875     * @see #setFilterTouchesWhenObscured(boolean)
6876     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
6877     */
6878    @ViewDebug.ExportedProperty
6879    public boolean getFilterTouchesWhenObscured() {
6880        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
6881    }
6882
6883    /**
6884     * Sets whether the framework should discard touches when the view's
6885     * window is obscured by another visible window.
6886     * Refer to the {@link View} security documentation for more details.
6887     *
6888     * @param enabled True if touch filtering should be enabled.
6889     *
6890     * @see #getFilterTouchesWhenObscured
6891     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
6892     */
6893    public void setFilterTouchesWhenObscured(boolean enabled) {
6894        setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0,
6895                FILTER_TOUCHES_WHEN_OBSCURED);
6896    }
6897
6898    /**
6899     * Indicates whether the entire hierarchy under this view will save its
6900     * state when a state saving traversal occurs from its parent.  The default
6901     * is true; if false, these views will not be saved unless
6902     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
6903     *
6904     * @return Returns true if the view state saving from parent is enabled, else false.
6905     *
6906     * @see #setSaveFromParentEnabled(boolean)
6907     */
6908    public boolean isSaveFromParentEnabled() {
6909        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
6910    }
6911
6912    /**
6913     * Controls whether the entire hierarchy under this view will save its
6914     * state when a state saving traversal occurs from its parent.  The default
6915     * is true; if false, these views will not be saved unless
6916     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
6917     *
6918     * @param enabled Set to false to <em>disable</em> state saving, or true
6919     * (the default) to allow it.
6920     *
6921     * @see #isSaveFromParentEnabled()
6922     * @see #setId(int)
6923     * @see #onSaveInstanceState()
6924     */
6925    public void setSaveFromParentEnabled(boolean enabled) {
6926        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
6927    }
6928
6929
6930    /**
6931     * Returns whether this View is able to take focus.
6932     *
6933     * @return True if this view can take focus, or false otherwise.
6934     * @attr ref android.R.styleable#View_focusable
6935     */
6936    @ViewDebug.ExportedProperty(category = "focus")
6937    public final boolean isFocusable() {
6938        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
6939    }
6940
6941    /**
6942     * When a view is focusable, it may not want to take focus when in touch mode.
6943     * For example, a button would like focus when the user is navigating via a D-pad
6944     * so that the user can click on it, but once the user starts touching the screen,
6945     * the button shouldn't take focus
6946     * @return Whether the view is focusable in touch mode.
6947     * @attr ref android.R.styleable#View_focusableInTouchMode
6948     */
6949    @ViewDebug.ExportedProperty
6950    public final boolean isFocusableInTouchMode() {
6951        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
6952    }
6953
6954    /**
6955     * Find the nearest view in the specified direction that can take focus.
6956     * This does not actually give focus to that view.
6957     *
6958     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6959     *
6960     * @return The nearest focusable in the specified direction, or null if none
6961     *         can be found.
6962     */
6963    public View focusSearch(@FocusRealDirection int direction) {
6964        if (mParent != null) {
6965            return mParent.focusSearch(this, direction);
6966        } else {
6967            return null;
6968        }
6969    }
6970
6971    /**
6972     * This method is the last chance for the focused view and its ancestors to
6973     * respond to an arrow key. This is called when the focused view did not
6974     * consume the key internally, nor could the view system find a new view in
6975     * the requested direction to give focus to.
6976     *
6977     * @param focused The currently focused view.
6978     * @param direction The direction focus wants to move. One of FOCUS_UP,
6979     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
6980     * @return True if the this view consumed this unhandled move.
6981     */
6982    public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) {
6983        return false;
6984    }
6985
6986    /**
6987     * If a user manually specified the next view id for a particular direction,
6988     * use the root to look up the view.
6989     * @param root The root view of the hierarchy containing this view.
6990     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
6991     * or FOCUS_BACKWARD.
6992     * @return The user specified next view, or null if there is none.
6993     */
6994    View findUserSetNextFocus(View root, @FocusDirection int direction) {
6995        switch (direction) {
6996            case FOCUS_LEFT:
6997                if (mNextFocusLeftId == View.NO_ID) return null;
6998                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
6999            case FOCUS_RIGHT:
7000                if (mNextFocusRightId == View.NO_ID) return null;
7001                return findViewInsideOutShouldExist(root, mNextFocusRightId);
7002            case FOCUS_UP:
7003                if (mNextFocusUpId == View.NO_ID) return null;
7004                return findViewInsideOutShouldExist(root, mNextFocusUpId);
7005            case FOCUS_DOWN:
7006                if (mNextFocusDownId == View.NO_ID) return null;
7007                return findViewInsideOutShouldExist(root, mNextFocusDownId);
7008            case FOCUS_FORWARD:
7009                if (mNextFocusForwardId == View.NO_ID) return null;
7010                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
7011            case FOCUS_BACKWARD: {
7012                if (mID == View.NO_ID) return null;
7013                final int id = mID;
7014                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
7015                    @Override
7016                    public boolean apply(View t) {
7017                        return t.mNextFocusForwardId == id;
7018                    }
7019                });
7020            }
7021        }
7022        return null;
7023    }
7024
7025    private View findViewInsideOutShouldExist(View root, int id) {
7026        if (mMatchIdPredicate == null) {
7027            mMatchIdPredicate = new MatchIdPredicate();
7028        }
7029        mMatchIdPredicate.mId = id;
7030        View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate);
7031        if (result == null) {
7032            Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id);
7033        }
7034        return result;
7035    }
7036
7037    /**
7038     * Find and return all focusable views that are descendants of this view,
7039     * possibly including this view if it is focusable itself.
7040     *
7041     * @param direction The direction of the focus
7042     * @return A list of focusable views
7043     */
7044    public ArrayList<View> getFocusables(@FocusDirection int direction) {
7045        ArrayList<View> result = new ArrayList<View>(24);
7046        addFocusables(result, direction);
7047        return result;
7048    }
7049
7050    /**
7051     * Add any focusable views that are descendants of this view (possibly
7052     * including this view if it is focusable itself) to views.  If we are in touch mode,
7053     * only add views that are also focusable in touch mode.
7054     *
7055     * @param views Focusable views found so far
7056     * @param direction The direction of the focus
7057     */
7058    public void addFocusables(ArrayList<View> views, @FocusDirection int direction) {
7059        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
7060    }
7061
7062    /**
7063     * Adds any focusable views that are descendants of this view (possibly
7064     * including this view if it is focusable itself) to views. This method
7065     * adds all focusable views regardless if we are in touch mode or
7066     * only views focusable in touch mode if we are in touch mode or
7067     * only views that can take accessibility focus if accessibility is enabeld
7068     * depending on the focusable mode paramater.
7069     *
7070     * @param views Focusable views found so far or null if all we are interested is
7071     *        the number of focusables.
7072     * @param direction The direction of the focus.
7073     * @param focusableMode The type of focusables to be added.
7074     *
7075     * @see #FOCUSABLES_ALL
7076     * @see #FOCUSABLES_TOUCH_MODE
7077     */
7078    public void addFocusables(ArrayList<View> views, @FocusDirection int direction,
7079            @FocusableMode int focusableMode) {
7080        if (views == null) {
7081            return;
7082        }
7083        if (!isFocusable()) {
7084            return;
7085        }
7086        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
7087                && isInTouchMode() && !isFocusableInTouchMode()) {
7088            return;
7089        }
7090        views.add(this);
7091    }
7092
7093    /**
7094     * Finds the Views that contain given text. The containment is case insensitive.
7095     * The search is performed by either the text that the View renders or the content
7096     * description that describes the view for accessibility purposes and the view does
7097     * not render or both. Clients can specify how the search is to be performed via
7098     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
7099     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
7100     *
7101     * @param outViews The output list of matching Views.
7102     * @param searched The text to match against.
7103     *
7104     * @see #FIND_VIEWS_WITH_TEXT
7105     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
7106     * @see #setContentDescription(CharSequence)
7107     */
7108    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched,
7109            @FindViewFlags int flags) {
7110        if (getAccessibilityNodeProvider() != null) {
7111            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
7112                outViews.add(this);
7113            }
7114        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
7115                && (searched != null && searched.length() > 0)
7116                && (mContentDescription != null && mContentDescription.length() > 0)) {
7117            String searchedLowerCase = searched.toString().toLowerCase();
7118            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
7119            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
7120                outViews.add(this);
7121            }
7122        }
7123    }
7124
7125    /**
7126     * Find and return all touchable views that are descendants of this view,
7127     * possibly including this view if it is touchable itself.
7128     *
7129     * @return A list of touchable views
7130     */
7131    public ArrayList<View> getTouchables() {
7132        ArrayList<View> result = new ArrayList<View>();
7133        addTouchables(result);
7134        return result;
7135    }
7136
7137    /**
7138     * Add any touchable views that are descendants of this view (possibly
7139     * including this view if it is touchable itself) to views.
7140     *
7141     * @param views Touchable views found so far
7142     */
7143    public void addTouchables(ArrayList<View> views) {
7144        final int viewFlags = mViewFlags;
7145
7146        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
7147                && (viewFlags & ENABLED_MASK) == ENABLED) {
7148            views.add(this);
7149        }
7150    }
7151
7152    /**
7153     * Returns whether this View is accessibility focused.
7154     *
7155     * @return True if this View is accessibility focused.
7156     */
7157    public boolean isAccessibilityFocused() {
7158        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
7159    }
7160
7161    /**
7162     * Call this to try to give accessibility focus to this view.
7163     *
7164     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
7165     * returns false or the view is no visible or the view already has accessibility
7166     * focus.
7167     *
7168     * See also {@link #focusSearch(int)}, which is what you call to say that you
7169     * have focus, and you want your parent to look for the next one.
7170     *
7171     * @return Whether this view actually took accessibility focus.
7172     *
7173     * @hide
7174     */
7175    public boolean requestAccessibilityFocus() {
7176        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
7177        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
7178            return false;
7179        }
7180        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
7181            return false;
7182        }
7183        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
7184            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
7185            ViewRootImpl viewRootImpl = getViewRootImpl();
7186            if (viewRootImpl != null) {
7187                viewRootImpl.setAccessibilityFocus(this, null);
7188            }
7189            Rect rect = (mAttachInfo != null) ? mAttachInfo.mTmpInvalRect : new Rect();
7190            getDrawingRect(rect);
7191            requestRectangleOnScreen(rect, false);
7192            invalidate();
7193            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
7194            return true;
7195        }
7196        return false;
7197    }
7198
7199    /**
7200     * Call this to try to clear accessibility focus of this view.
7201     *
7202     * See also {@link #focusSearch(int)}, which is what you call to say that you
7203     * have focus, and you want your parent to look for the next one.
7204     *
7205     * @hide
7206     */
7207    public void clearAccessibilityFocus() {
7208        clearAccessibilityFocusNoCallbacks();
7209        // Clear the global reference of accessibility focus if this
7210        // view or any of its descendants had accessibility focus.
7211        ViewRootImpl viewRootImpl = getViewRootImpl();
7212        if (viewRootImpl != null) {
7213            View focusHost = viewRootImpl.getAccessibilityFocusedHost();
7214            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
7215                viewRootImpl.setAccessibilityFocus(null, null);
7216            }
7217        }
7218    }
7219
7220    private void sendAccessibilityHoverEvent(int eventType) {
7221        // Since we are not delivering to a client accessibility events from not
7222        // important views (unless the clinet request that) we need to fire the
7223        // event from the deepest view exposed to the client. As a consequence if
7224        // the user crosses a not exposed view the client will see enter and exit
7225        // of the exposed predecessor followed by and enter and exit of that same
7226        // predecessor when entering and exiting the not exposed descendant. This
7227        // is fine since the client has a clear idea which view is hovered at the
7228        // price of a couple more events being sent. This is a simple and
7229        // working solution.
7230        View source = this;
7231        while (true) {
7232            if (source.includeForAccessibility()) {
7233                source.sendAccessibilityEvent(eventType);
7234                return;
7235            }
7236            ViewParent parent = source.getParent();
7237            if (parent instanceof View) {
7238                source = (View) parent;
7239            } else {
7240                return;
7241            }
7242        }
7243    }
7244
7245    /**
7246     * Clears accessibility focus without calling any callback methods
7247     * normally invoked in {@link #clearAccessibilityFocus()}. This method
7248     * is used for clearing accessibility focus when giving this focus to
7249     * another view.
7250     */
7251    void clearAccessibilityFocusNoCallbacks() {
7252        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
7253            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
7254            invalidate();
7255            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
7256        }
7257    }
7258
7259    /**
7260     * Call this to try to give focus to a specific view or to one of its
7261     * descendants.
7262     *
7263     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7264     * false), or if it is focusable and it is not focusable in touch mode
7265     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7266     *
7267     * See also {@link #focusSearch(int)}, which is what you call to say that you
7268     * have focus, and you want your parent to look for the next one.
7269     *
7270     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
7271     * {@link #FOCUS_DOWN} and <code>null</code>.
7272     *
7273     * @return Whether this view or one of its descendants actually took focus.
7274     */
7275    public final boolean requestFocus() {
7276        return requestFocus(View.FOCUS_DOWN);
7277    }
7278
7279    /**
7280     * Call this to try to give focus to a specific view or to one of its
7281     * descendants and give it a hint about what direction focus is heading.
7282     *
7283     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7284     * false), or if it is focusable and it is not focusable in touch mode
7285     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
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     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
7291     * <code>null</code> set for the previously focused rectangle.
7292     *
7293     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
7294     * @return Whether this view or one of its descendants actually took focus.
7295     */
7296    public final boolean requestFocus(int direction) {
7297        return requestFocus(direction, null);
7298    }
7299
7300    /**
7301     * Call this to try to give focus to a specific view or to one of its descendants
7302     * and give it hints about the direction and a specific rectangle that the focus
7303     * is coming from.  The rectangle can help give larger views a finer grained hint
7304     * about where focus is coming from, and therefore, where to show selection, or
7305     * forward focus change internally.
7306     *
7307     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7308     * false), or if it is focusable and it is not focusable in touch mode
7309     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7310     *
7311     * A View will not take focus if it is not visible.
7312     *
7313     * A View will not take focus if one of its parents has
7314     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
7315     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
7316     *
7317     * See also {@link #focusSearch(int)}, which is what you call to say that you
7318     * have focus, and you want your parent to look for the next one.
7319     *
7320     * You may wish to override this method if your custom {@link View} has an internal
7321     * {@link View} that it wishes to forward the request to.
7322     *
7323     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
7324     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
7325     *        to give a finer grained hint about where focus is coming from.  May be null
7326     *        if there is no hint.
7327     * @return Whether this view or one of its descendants actually took focus.
7328     */
7329    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
7330        return requestFocusNoSearch(direction, previouslyFocusedRect);
7331    }
7332
7333    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
7334        // need to be focusable
7335        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
7336                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
7337            return false;
7338        }
7339
7340        // need to be focusable in touch mode if in touch mode
7341        if (isInTouchMode() &&
7342            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
7343               return false;
7344        }
7345
7346        // need to not have any parents blocking us
7347        if (hasAncestorThatBlocksDescendantFocus()) {
7348            return false;
7349        }
7350
7351        handleFocusGainInternal(direction, previouslyFocusedRect);
7352        return true;
7353    }
7354
7355    /**
7356     * Call this to try to give focus to a specific view or to one of its descendants. This is a
7357     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
7358     * touch mode to request focus when they are touched.
7359     *
7360     * @return Whether this view or one of its descendants actually took focus.
7361     *
7362     * @see #isInTouchMode()
7363     *
7364     */
7365    public final boolean requestFocusFromTouch() {
7366        // Leave touch mode if we need to
7367        if (isInTouchMode()) {
7368            ViewRootImpl viewRoot = getViewRootImpl();
7369            if (viewRoot != null) {
7370                viewRoot.ensureTouchMode(false);
7371            }
7372        }
7373        return requestFocus(View.FOCUS_DOWN);
7374    }
7375
7376    /**
7377     * @return Whether any ancestor of this view blocks descendant focus.
7378     */
7379    private boolean hasAncestorThatBlocksDescendantFocus() {
7380        ViewParent ancestor = mParent;
7381        while (ancestor instanceof ViewGroup) {
7382            final ViewGroup vgAncestor = (ViewGroup) ancestor;
7383            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
7384                return true;
7385            } else {
7386                ancestor = vgAncestor.getParent();
7387            }
7388        }
7389        return false;
7390    }
7391
7392    /**
7393     * Gets the mode for determining whether this View is important for accessibility
7394     * which is if it fires accessibility events and if it is reported to
7395     * accessibility services that query the screen.
7396     *
7397     * @return The mode for determining whether a View is important for accessibility.
7398     *
7399     * @attr ref android.R.styleable#View_importantForAccessibility
7400     *
7401     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
7402     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
7403     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
7404     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
7405     */
7406    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
7407            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
7408            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
7409            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"),
7410            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS,
7411                    to = "noHideDescendants")
7412        })
7413    public int getImportantForAccessibility() {
7414        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
7415                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
7416    }
7417
7418    /**
7419     * Sets the live region mode for this view. This indicates to accessibility
7420     * services whether they should automatically notify the user about changes
7421     * to the view's content description or text, or to the content descriptions
7422     * or text of the view's children (where applicable).
7423     * <p>
7424     * For example, in a login screen with a TextView that displays an "incorrect
7425     * password" notification, that view should be marked as a live region with
7426     * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
7427     * <p>
7428     * To disable change notifications for this view, use
7429     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region
7430     * mode for most views.
7431     * <p>
7432     * To indicate that the user should be notified of changes, use
7433     * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
7434     * <p>
7435     * If the view's changes should interrupt ongoing speech and notify the user
7436     * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}.
7437     *
7438     * @param mode The live region mode for this view, one of:
7439     *        <ul>
7440     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE}
7441     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE}
7442     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}
7443     *        </ul>
7444     * @attr ref android.R.styleable#View_accessibilityLiveRegion
7445     */
7446    public void setAccessibilityLiveRegion(int mode) {
7447        if (mode != getAccessibilityLiveRegion()) {
7448            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
7449            mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT)
7450                    & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
7451            notifyViewAccessibilityStateChangedIfNeeded(
7452                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7453        }
7454    }
7455
7456    /**
7457     * Gets the live region mode for this View.
7458     *
7459     * @return The live region mode for the view.
7460     *
7461     * @attr ref android.R.styleable#View_accessibilityLiveRegion
7462     *
7463     * @see #setAccessibilityLiveRegion(int)
7464     */
7465    public int getAccessibilityLiveRegion() {
7466        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK)
7467                >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
7468    }
7469
7470    /**
7471     * Sets how to determine whether this view is important for accessibility
7472     * which is if it fires accessibility events and if it is reported to
7473     * accessibility services that query the screen.
7474     *
7475     * @param mode How to determine whether this view is important for accessibility.
7476     *
7477     * @attr ref android.R.styleable#View_importantForAccessibility
7478     *
7479     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
7480     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
7481     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
7482     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
7483     */
7484    public void setImportantForAccessibility(int mode) {
7485        final int oldMode = getImportantForAccessibility();
7486        if (mode != oldMode) {
7487            // If we're moving between AUTO and another state, we might not need
7488            // to send a subtree changed notification. We'll store the computed
7489            // importance, since we'll need to check it later to make sure.
7490            final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO
7491                    || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO;
7492            final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility();
7493            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
7494            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
7495                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
7496            if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) {
7497                notifySubtreeAccessibilityStateChangedIfNeeded();
7498            } else {
7499                notifyViewAccessibilityStateChangedIfNeeded(
7500                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7501            }
7502        }
7503    }
7504
7505    /**
7506     * Computes whether this view should be exposed for accessibility. In
7507     * general, views that are interactive or provide information are exposed
7508     * while views that serve only as containers are hidden.
7509     * <p>
7510     * If an ancestor of this view has importance
7511     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method
7512     * returns <code>false</code>.
7513     * <p>
7514     * Otherwise, the value is computed according to the view's
7515     * {@link #getImportantForAccessibility()} value:
7516     * <ol>
7517     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or
7518     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false
7519     * </code>
7520     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code>
7521     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if
7522     * view satisfies any of the following:
7523     * <ul>
7524     * <li>Is actionable, e.g. {@link #isClickable()},
7525     * {@link #isLongClickable()}, or {@link #isFocusable()}
7526     * <li>Has an {@link AccessibilityDelegate}
7527     * <li>Has an interaction listener, e.g. {@link OnTouchListener},
7528     * {@link OnKeyListener}, etc.
7529     * <li>Is an accessibility live region, e.g.
7530     * {@link #getAccessibilityLiveRegion()} is not
7531     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}.
7532     * </ul>
7533     * </ol>
7534     *
7535     * @return Whether the view is exposed for accessibility.
7536     * @see #setImportantForAccessibility(int)
7537     * @see #getImportantForAccessibility()
7538     */
7539    public boolean isImportantForAccessibility() {
7540        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
7541                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
7542        if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO
7543                || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
7544            return false;
7545        }
7546
7547        // Check parent mode to ensure we're not hidden.
7548        ViewParent parent = mParent;
7549        while (parent instanceof View) {
7550            if (((View) parent).getImportantForAccessibility()
7551                    == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
7552                return false;
7553            }
7554            parent = parent.getParent();
7555        }
7556
7557        return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility()
7558                || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null
7559                || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE;
7560    }
7561
7562    /**
7563     * Gets the parent for accessibility purposes. Note that the parent for
7564     * accessibility is not necessary the immediate parent. It is the first
7565     * predecessor that is important for accessibility.
7566     *
7567     * @return The parent for accessibility purposes.
7568     */
7569    public ViewParent getParentForAccessibility() {
7570        if (mParent instanceof View) {
7571            View parentView = (View) mParent;
7572            if (parentView.includeForAccessibility()) {
7573                return mParent;
7574            } else {
7575                return mParent.getParentForAccessibility();
7576            }
7577        }
7578        return null;
7579    }
7580
7581    /**
7582     * Adds the children of a given View for accessibility. Since some Views are
7583     * not important for accessibility the children for accessibility are not
7584     * necessarily direct children of the view, rather they are the first level of
7585     * descendants important for accessibility.
7586     *
7587     * @param children The list of children for accessibility.
7588     */
7589    public void addChildrenForAccessibility(ArrayList<View> children) {
7590
7591    }
7592
7593    /**
7594     * Whether to regard this view for accessibility. A view is regarded for
7595     * accessibility if it is important for accessibility or the querying
7596     * accessibility service has explicitly requested that view not
7597     * important for accessibility are regarded.
7598     *
7599     * @return Whether to regard the view for accessibility.
7600     *
7601     * @hide
7602     */
7603    public boolean includeForAccessibility() {
7604        if (mAttachInfo != null) {
7605            return (mAttachInfo.mAccessibilityFetchFlags
7606                    & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0
7607                    || isImportantForAccessibility();
7608        }
7609        return false;
7610    }
7611
7612    /**
7613     * Returns whether the View is considered actionable from
7614     * accessibility perspective. Such view are important for
7615     * accessibility.
7616     *
7617     * @return True if the view is actionable for accessibility.
7618     *
7619     * @hide
7620     */
7621    public boolean isActionableForAccessibility() {
7622        return (isClickable() || isLongClickable() || isFocusable());
7623    }
7624
7625    /**
7626     * Returns whether the View has registered callbacks which makes it
7627     * important for accessibility.
7628     *
7629     * @return True if the view is actionable for accessibility.
7630     */
7631    private boolean hasListenersForAccessibility() {
7632        ListenerInfo info = getListenerInfo();
7633        return mTouchDelegate != null || info.mOnKeyListener != null
7634                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
7635                || info.mOnHoverListener != null || info.mOnDragListener != null;
7636    }
7637
7638    /**
7639     * Notifies that the accessibility state of this view changed. The change
7640     * is local to this view and does not represent structural changes such
7641     * as children and parent. For example, the view became focusable. The
7642     * notification is at at most once every
7643     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
7644     * to avoid unnecessary load to the system. Also once a view has a pending
7645     * notification this method is a NOP until the notification has been sent.
7646     *
7647     * @hide
7648     */
7649    public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) {
7650        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
7651            return;
7652        }
7653        if (mSendViewStateChangedAccessibilityEvent == null) {
7654            mSendViewStateChangedAccessibilityEvent =
7655                    new SendViewStateChangedAccessibilityEvent();
7656        }
7657        mSendViewStateChangedAccessibilityEvent.runOrPost(changeType);
7658    }
7659
7660    /**
7661     * Notifies that the accessibility state of this view changed. The change
7662     * is *not* local to this view and does represent structural changes such
7663     * as children and parent. For example, the view size changed. The
7664     * notification is at at most once every
7665     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
7666     * to avoid unnecessary load to the system. Also once a view has a pending
7667     * notification this method is a NOP until the notification has been sent.
7668     *
7669     * @hide
7670     */
7671    public void notifySubtreeAccessibilityStateChangedIfNeeded() {
7672        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
7673            return;
7674        }
7675        if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) {
7676            mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
7677            if (mParent != null) {
7678                try {
7679                    mParent.notifySubtreeAccessibilityStateChanged(
7680                            this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
7681                } catch (AbstractMethodError e) {
7682                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
7683                            " does not fully implement ViewParent", e);
7684                }
7685            }
7686        }
7687    }
7688
7689    /**
7690     * Reset the flag indicating the accessibility state of the subtree rooted
7691     * at this view changed.
7692     */
7693    void resetSubtreeAccessibilityStateChanged() {
7694        mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
7695    }
7696
7697    /**
7698     * Performs the specified accessibility action on the view. For
7699     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
7700     * <p>
7701     * If an {@link AccessibilityDelegate} has been specified via calling
7702     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
7703     * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
7704     * is responsible for handling this call.
7705     * </p>
7706     *
7707     * @param action The action to perform.
7708     * @param arguments Optional action arguments.
7709     * @return Whether the action was performed.
7710     */
7711    public boolean performAccessibilityAction(int action, Bundle arguments) {
7712      if (mAccessibilityDelegate != null) {
7713          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
7714      } else {
7715          return performAccessibilityActionInternal(action, arguments);
7716      }
7717    }
7718
7719   /**
7720    * @see #performAccessibilityAction(int, Bundle)
7721    *
7722    * Note: Called from the default {@link AccessibilityDelegate}.
7723    */
7724    boolean performAccessibilityActionInternal(int action, Bundle arguments) {
7725        switch (action) {
7726            case AccessibilityNodeInfo.ACTION_CLICK: {
7727                if (isClickable()) {
7728                    performClick();
7729                    return true;
7730                }
7731            } break;
7732            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
7733                if (isLongClickable()) {
7734                    performLongClick();
7735                    return true;
7736                }
7737            } break;
7738            case AccessibilityNodeInfo.ACTION_FOCUS: {
7739                if (!hasFocus()) {
7740                    // Get out of touch mode since accessibility
7741                    // wants to move focus around.
7742                    getViewRootImpl().ensureTouchMode(false);
7743                    return requestFocus();
7744                }
7745            } break;
7746            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
7747                if (hasFocus()) {
7748                    clearFocus();
7749                    return !isFocused();
7750                }
7751            } break;
7752            case AccessibilityNodeInfo.ACTION_SELECT: {
7753                if (!isSelected()) {
7754                    setSelected(true);
7755                    return isSelected();
7756                }
7757            } break;
7758            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
7759                if (isSelected()) {
7760                    setSelected(false);
7761                    return !isSelected();
7762                }
7763            } break;
7764            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
7765                if (!isAccessibilityFocused()) {
7766                    return requestAccessibilityFocus();
7767                }
7768            } break;
7769            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
7770                if (isAccessibilityFocused()) {
7771                    clearAccessibilityFocus();
7772                    return true;
7773                }
7774            } break;
7775            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
7776                if (arguments != null) {
7777                    final int granularity = arguments.getInt(
7778                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
7779                    final boolean extendSelection = arguments.getBoolean(
7780                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
7781                    return traverseAtGranularity(granularity, true, extendSelection);
7782                }
7783            } break;
7784            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
7785                if (arguments != null) {
7786                    final int granularity = arguments.getInt(
7787                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
7788                    final boolean extendSelection = arguments.getBoolean(
7789                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
7790                    return traverseAtGranularity(granularity, false, extendSelection);
7791                }
7792            } break;
7793            case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
7794                CharSequence text = getIterableTextForAccessibility();
7795                if (text == null) {
7796                    return false;
7797                }
7798                final int start = (arguments != null) ? arguments.getInt(
7799                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1;
7800                final int end = (arguments != null) ? arguments.getInt(
7801                AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1;
7802                // Only cursor position can be specified (selection length == 0)
7803                if ((getAccessibilitySelectionStart() != start
7804                        || getAccessibilitySelectionEnd() != end)
7805                        && (start == end)) {
7806                    setAccessibilitySelection(start, end);
7807                    notifyViewAccessibilityStateChangedIfNeeded(
7808                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7809                    return true;
7810                }
7811            } break;
7812        }
7813        return false;
7814    }
7815
7816    private boolean traverseAtGranularity(int granularity, boolean forward,
7817            boolean extendSelection) {
7818        CharSequence text = getIterableTextForAccessibility();
7819        if (text == null || text.length() == 0) {
7820            return false;
7821        }
7822        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
7823        if (iterator == null) {
7824            return false;
7825        }
7826        int current = getAccessibilitySelectionEnd();
7827        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7828            current = forward ? 0 : text.length();
7829        }
7830        final int[] range = forward ? iterator.following(current) : iterator.preceding(current);
7831        if (range == null) {
7832            return false;
7833        }
7834        final int segmentStart = range[0];
7835        final int segmentEnd = range[1];
7836        int selectionStart;
7837        int selectionEnd;
7838        if (extendSelection && isAccessibilitySelectionExtendable()) {
7839            selectionStart = getAccessibilitySelectionStart();
7840            if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7841                selectionStart = forward ? segmentStart : segmentEnd;
7842            }
7843            selectionEnd = forward ? segmentEnd : segmentStart;
7844        } else {
7845            selectionStart = selectionEnd= forward ? segmentEnd : segmentStart;
7846        }
7847        setAccessibilitySelection(selectionStart, selectionEnd);
7848        final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY
7849                : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY;
7850        sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd);
7851        return true;
7852    }
7853
7854    /**
7855     * Gets the text reported for accessibility purposes.
7856     *
7857     * @return The accessibility text.
7858     *
7859     * @hide
7860     */
7861    public CharSequence getIterableTextForAccessibility() {
7862        return getContentDescription();
7863    }
7864
7865    /**
7866     * Gets whether accessibility selection can be extended.
7867     *
7868     * @return If selection is extensible.
7869     *
7870     * @hide
7871     */
7872    public boolean isAccessibilitySelectionExtendable() {
7873        return false;
7874    }
7875
7876    /**
7877     * @hide
7878     */
7879    public int getAccessibilitySelectionStart() {
7880        return mAccessibilityCursorPosition;
7881    }
7882
7883    /**
7884     * @hide
7885     */
7886    public int getAccessibilitySelectionEnd() {
7887        return getAccessibilitySelectionStart();
7888    }
7889
7890    /**
7891     * @hide
7892     */
7893    public void setAccessibilitySelection(int start, int end) {
7894        if (start ==  end && end == mAccessibilityCursorPosition) {
7895            return;
7896        }
7897        if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) {
7898            mAccessibilityCursorPosition = start;
7899        } else {
7900            mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
7901        }
7902        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
7903    }
7904
7905    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
7906            int fromIndex, int toIndex) {
7907        if (mParent == null) {
7908            return;
7909        }
7910        AccessibilityEvent event = AccessibilityEvent.obtain(
7911                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
7912        onInitializeAccessibilityEvent(event);
7913        onPopulateAccessibilityEvent(event);
7914        event.setFromIndex(fromIndex);
7915        event.setToIndex(toIndex);
7916        event.setAction(action);
7917        event.setMovementGranularity(granularity);
7918        mParent.requestSendAccessibilityEvent(this, event);
7919    }
7920
7921    /**
7922     * @hide
7923     */
7924    public TextSegmentIterator getIteratorForGranularity(int granularity) {
7925        switch (granularity) {
7926            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
7927                CharSequence text = getIterableTextForAccessibility();
7928                if (text != null && text.length() > 0) {
7929                    CharacterTextSegmentIterator iterator =
7930                        CharacterTextSegmentIterator.getInstance(
7931                                mContext.getResources().getConfiguration().locale);
7932                    iterator.initialize(text.toString());
7933                    return iterator;
7934                }
7935            } break;
7936            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
7937                CharSequence text = getIterableTextForAccessibility();
7938                if (text != null && text.length() > 0) {
7939                    WordTextSegmentIterator iterator =
7940                        WordTextSegmentIterator.getInstance(
7941                                mContext.getResources().getConfiguration().locale);
7942                    iterator.initialize(text.toString());
7943                    return iterator;
7944                }
7945            } break;
7946            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
7947                CharSequence text = getIterableTextForAccessibility();
7948                if (text != null && text.length() > 0) {
7949                    ParagraphTextSegmentIterator iterator =
7950                        ParagraphTextSegmentIterator.getInstance();
7951                    iterator.initialize(text.toString());
7952                    return iterator;
7953                }
7954            } break;
7955        }
7956        return null;
7957    }
7958
7959    /**
7960     * @hide
7961     */
7962    public void dispatchStartTemporaryDetach() {
7963        onStartTemporaryDetach();
7964    }
7965
7966    /**
7967     * This is called when a container is going to temporarily detach a child, with
7968     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
7969     * It will either be followed by {@link #onFinishTemporaryDetach()} or
7970     * {@link #onDetachedFromWindow()} when the container is done.
7971     */
7972    public void onStartTemporaryDetach() {
7973        removeUnsetPressCallback();
7974        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
7975    }
7976
7977    /**
7978     * @hide
7979     */
7980    public void dispatchFinishTemporaryDetach() {
7981        onFinishTemporaryDetach();
7982    }
7983
7984    /**
7985     * Called after {@link #onStartTemporaryDetach} when the container is done
7986     * changing the view.
7987     */
7988    public void onFinishTemporaryDetach() {
7989    }
7990
7991    /**
7992     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
7993     * for this view's window.  Returns null if the view is not currently attached
7994     * to the window.  Normally you will not need to use this directly, but
7995     * just use the standard high-level event callbacks like
7996     * {@link #onKeyDown(int, KeyEvent)}.
7997     */
7998    public KeyEvent.DispatcherState getKeyDispatcherState() {
7999        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
8000    }
8001
8002    /**
8003     * Dispatch a key event before it is processed by any input method
8004     * associated with the view hierarchy.  This can be used to intercept
8005     * key events in special situations before the IME consumes them; a
8006     * typical example would be handling the BACK key to update the application's
8007     * UI instead of allowing the IME to see it and close itself.
8008     *
8009     * @param event The key event to be dispatched.
8010     * @return True if the event was handled, false otherwise.
8011     */
8012    public boolean dispatchKeyEventPreIme(KeyEvent event) {
8013        return onKeyPreIme(event.getKeyCode(), event);
8014    }
8015
8016    /**
8017     * Dispatch a key event to the next view on the focus path. This path runs
8018     * from the top of the view tree down to the currently focused view. If this
8019     * view has focus, it will dispatch to itself. Otherwise it will dispatch
8020     * the next node down the focus path. This method also fires any key
8021     * listeners.
8022     *
8023     * @param event The key event to be dispatched.
8024     * @return True if the event was handled, false otherwise.
8025     */
8026    public boolean dispatchKeyEvent(KeyEvent event) {
8027        if (mInputEventConsistencyVerifier != null) {
8028            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
8029        }
8030
8031        // Give any attached key listener a first crack at the event.
8032        //noinspection SimplifiableIfStatement
8033        ListenerInfo li = mListenerInfo;
8034        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
8035                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
8036            return true;
8037        }
8038
8039        if (event.dispatch(this, mAttachInfo != null
8040                ? mAttachInfo.mKeyDispatchState : null, this)) {
8041            return true;
8042        }
8043
8044        if (mInputEventConsistencyVerifier != null) {
8045            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8046        }
8047        return false;
8048    }
8049
8050    /**
8051     * Dispatches a key shortcut event.
8052     *
8053     * @param event The key event to be dispatched.
8054     * @return True if the event was handled by the view, false otherwise.
8055     */
8056    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
8057        return onKeyShortcut(event.getKeyCode(), event);
8058    }
8059
8060    /**
8061     * Pass the touch screen motion event down to the target view, or this
8062     * view if it is the target.
8063     *
8064     * @param event The motion event to be dispatched.
8065     * @return True if the event was handled by the view, false otherwise.
8066     */
8067    public boolean dispatchTouchEvent(MotionEvent event) {
8068        boolean result = false;
8069
8070        if (mInputEventConsistencyVerifier != null) {
8071            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
8072        }
8073
8074        final int actionMasked = event.getActionMasked();
8075        if (actionMasked == MotionEvent.ACTION_DOWN) {
8076            // Defensive cleanup for new gesture
8077            stopNestedScroll();
8078        }
8079
8080        if (onFilterTouchEventForSecurity(event)) {
8081            //noinspection SimplifiableIfStatement
8082            ListenerInfo li = mListenerInfo;
8083            if (li != null && li.mOnTouchListener != null
8084                    && (mViewFlags & ENABLED_MASK) == ENABLED
8085                    && li.mOnTouchListener.onTouch(this, event)) {
8086                result = true;
8087            }
8088
8089            if (!result && onTouchEvent(event)) {
8090                result = true;
8091            }
8092        }
8093
8094        if (!result && mInputEventConsistencyVerifier != null) {
8095            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8096        }
8097
8098        // Clean up after nested scrolls if this is the end of a gesture;
8099        // also cancel it if we tried an ACTION_DOWN but we didn't want the rest
8100        // of the gesture.
8101        if (actionMasked == MotionEvent.ACTION_UP ||
8102                actionMasked == MotionEvent.ACTION_CANCEL ||
8103                (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
8104            stopNestedScroll();
8105        }
8106
8107        return result;
8108    }
8109
8110    /**
8111     * Filter the touch event to apply security policies.
8112     *
8113     * @param event The motion event to be filtered.
8114     * @return True if the event should be dispatched, false if the event should be dropped.
8115     *
8116     * @see #getFilterTouchesWhenObscured
8117     */
8118    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
8119        //noinspection RedundantIfStatement
8120        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
8121                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
8122            // Window is obscured, drop this touch.
8123            return false;
8124        }
8125        return true;
8126    }
8127
8128    /**
8129     * Pass a trackball motion event down to the focused view.
8130     *
8131     * @param event The motion event to be dispatched.
8132     * @return True if the event was handled by the view, false otherwise.
8133     */
8134    public boolean dispatchTrackballEvent(MotionEvent event) {
8135        if (mInputEventConsistencyVerifier != null) {
8136            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
8137        }
8138
8139        return onTrackballEvent(event);
8140    }
8141
8142    /**
8143     * Dispatch a generic motion event.
8144     * <p>
8145     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
8146     * are delivered to the view under the pointer.  All other generic motion events are
8147     * delivered to the focused view.  Hover events are handled specially and are delivered
8148     * to {@link #onHoverEvent(MotionEvent)}.
8149     * </p>
8150     *
8151     * @param event The motion event to be dispatched.
8152     * @return True if the event was handled by the view, false otherwise.
8153     */
8154    public boolean dispatchGenericMotionEvent(MotionEvent event) {
8155        if (mInputEventConsistencyVerifier != null) {
8156            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
8157        }
8158
8159        final int source = event.getSource();
8160        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
8161            final int action = event.getAction();
8162            if (action == MotionEvent.ACTION_HOVER_ENTER
8163                    || action == MotionEvent.ACTION_HOVER_MOVE
8164                    || action == MotionEvent.ACTION_HOVER_EXIT) {
8165                if (dispatchHoverEvent(event)) {
8166                    return true;
8167                }
8168            } else if (dispatchGenericPointerEvent(event)) {
8169                return true;
8170            }
8171        } else if (dispatchGenericFocusedEvent(event)) {
8172            return true;
8173        }
8174
8175        if (dispatchGenericMotionEventInternal(event)) {
8176            return true;
8177        }
8178
8179        if (mInputEventConsistencyVerifier != null) {
8180            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8181        }
8182        return false;
8183    }
8184
8185    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
8186        //noinspection SimplifiableIfStatement
8187        ListenerInfo li = mListenerInfo;
8188        if (li != null && li.mOnGenericMotionListener != null
8189                && (mViewFlags & ENABLED_MASK) == ENABLED
8190                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
8191            return true;
8192        }
8193
8194        if (onGenericMotionEvent(event)) {
8195            return true;
8196        }
8197
8198        if (mInputEventConsistencyVerifier != null) {
8199            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8200        }
8201        return false;
8202    }
8203
8204    /**
8205     * Dispatch a hover event.
8206     * <p>
8207     * Do not call this method directly.
8208     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8209     * </p>
8210     *
8211     * @param event The motion event to be dispatched.
8212     * @return True if the event was handled by the view, false otherwise.
8213     */
8214    protected boolean dispatchHoverEvent(MotionEvent event) {
8215        ListenerInfo li = mListenerInfo;
8216        //noinspection SimplifiableIfStatement
8217        if (li != null && li.mOnHoverListener != null
8218                && (mViewFlags & ENABLED_MASK) == ENABLED
8219                && li.mOnHoverListener.onHover(this, event)) {
8220            return true;
8221        }
8222
8223        return onHoverEvent(event);
8224    }
8225
8226    /**
8227     * Returns true if the view has a child to which it has recently sent
8228     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
8229     * it does not have a hovered child, then it must be the innermost hovered view.
8230     * @hide
8231     */
8232    protected boolean hasHoveredChild() {
8233        return false;
8234    }
8235
8236    /**
8237     * Dispatch a generic motion event to the view under the first pointer.
8238     * <p>
8239     * Do not call this method directly.
8240     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8241     * </p>
8242     *
8243     * @param event The motion event to be dispatched.
8244     * @return True if the event was handled by the view, false otherwise.
8245     */
8246    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
8247        return false;
8248    }
8249
8250    /**
8251     * Dispatch a generic motion event to the currently focused view.
8252     * <p>
8253     * Do not call this method directly.
8254     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8255     * </p>
8256     *
8257     * @param event The motion event to be dispatched.
8258     * @return True if the event was handled by the view, false otherwise.
8259     */
8260    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
8261        return false;
8262    }
8263
8264    /**
8265     * Dispatch a pointer event.
8266     * <p>
8267     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
8268     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
8269     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
8270     * and should not be expected to handle other pointing device features.
8271     * </p>
8272     *
8273     * @param event The motion event to be dispatched.
8274     * @return True if the event was handled by the view, false otherwise.
8275     * @hide
8276     */
8277    public final boolean dispatchPointerEvent(MotionEvent event) {
8278        if (event.isTouchEvent()) {
8279            return dispatchTouchEvent(event);
8280        } else {
8281            return dispatchGenericMotionEvent(event);
8282        }
8283    }
8284
8285    /**
8286     * Called when the window containing this view gains or loses window focus.
8287     * ViewGroups should override to route to their children.
8288     *
8289     * @param hasFocus True if the window containing this view now has focus,
8290     *        false otherwise.
8291     */
8292    public void dispatchWindowFocusChanged(boolean hasFocus) {
8293        onWindowFocusChanged(hasFocus);
8294    }
8295
8296    /**
8297     * Called when the window containing this view gains or loses focus.  Note
8298     * that this is separate from view focus: to receive key events, both
8299     * your view and its window must have focus.  If a window is displayed
8300     * on top of yours that takes input focus, then your own window will lose
8301     * focus but the view focus will remain unchanged.
8302     *
8303     * @param hasWindowFocus True if the window containing this view now has
8304     *        focus, false otherwise.
8305     */
8306    public void onWindowFocusChanged(boolean hasWindowFocus) {
8307        InputMethodManager imm = InputMethodManager.peekInstance();
8308        if (!hasWindowFocus) {
8309            if (isPressed()) {
8310                setPressed(false);
8311            }
8312            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
8313                imm.focusOut(this);
8314            }
8315            removeLongPressCallback();
8316            removeTapCallback();
8317            onFocusLost();
8318        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
8319            imm.focusIn(this);
8320        }
8321        refreshDrawableState();
8322    }
8323
8324    /**
8325     * Returns true if this view is in a window that currently has window focus.
8326     * Note that this is not the same as the view itself having focus.
8327     *
8328     * @return True if this view is in a window that currently has window focus.
8329     */
8330    public boolean hasWindowFocus() {
8331        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
8332    }
8333
8334    /**
8335     * Dispatch a view visibility change down the view hierarchy.
8336     * ViewGroups should override to route to their children.
8337     * @param changedView The view whose visibility changed. Could be 'this' or
8338     * an ancestor view.
8339     * @param visibility The new visibility of changedView: {@link #VISIBLE},
8340     * {@link #INVISIBLE} or {@link #GONE}.
8341     */
8342    protected void dispatchVisibilityChanged(@NonNull View changedView,
8343            @Visibility int visibility) {
8344        onVisibilityChanged(changedView, visibility);
8345    }
8346
8347    /**
8348     * Called when the visibility of the view or an ancestor of the view is changed.
8349     * @param changedView The view whose visibility changed. Could be 'this' or
8350     * an ancestor view.
8351     * @param visibility The new visibility of changedView: {@link #VISIBLE},
8352     * {@link #INVISIBLE} or {@link #GONE}.
8353     */
8354    protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) {
8355        if (visibility == VISIBLE) {
8356            if (mAttachInfo != null) {
8357                initialAwakenScrollBars();
8358            } else {
8359                mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
8360            }
8361        }
8362    }
8363
8364    /**
8365     * Dispatch a hint about whether this view is displayed. For instance, when
8366     * a View moves out of the screen, it might receives a display hint indicating
8367     * the view is not displayed. Applications should not <em>rely</em> on this hint
8368     * as there is no guarantee that they will receive one.
8369     *
8370     * @param hint A hint about whether or not this view is displayed:
8371     * {@link #VISIBLE} or {@link #INVISIBLE}.
8372     */
8373    public void dispatchDisplayHint(@Visibility int hint) {
8374        onDisplayHint(hint);
8375    }
8376
8377    /**
8378     * Gives this view a hint about whether is displayed or not. For instance, when
8379     * a View moves out of the screen, it might receives a display hint indicating
8380     * the view is not displayed. Applications should not <em>rely</em> on this hint
8381     * as there is no guarantee that they will receive one.
8382     *
8383     * @param hint A hint about whether or not this view is displayed:
8384     * {@link #VISIBLE} or {@link #INVISIBLE}.
8385     */
8386    protected void onDisplayHint(@Visibility int hint) {
8387    }
8388
8389    /**
8390     * Dispatch a window visibility change down the view hierarchy.
8391     * ViewGroups should override to route to their children.
8392     *
8393     * @param visibility The new visibility of the window.
8394     *
8395     * @see #onWindowVisibilityChanged(int)
8396     */
8397    public void dispatchWindowVisibilityChanged(@Visibility int visibility) {
8398        onWindowVisibilityChanged(visibility);
8399    }
8400
8401    /**
8402     * Called when the window containing has change its visibility
8403     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
8404     * that this tells you whether or not your window is being made visible
8405     * to the window manager; this does <em>not</em> tell you whether or not
8406     * your window is obscured by other windows on the screen, even if it
8407     * is itself visible.
8408     *
8409     * @param visibility The new visibility of the window.
8410     */
8411    protected void onWindowVisibilityChanged(@Visibility int visibility) {
8412        if (visibility == VISIBLE) {
8413            initialAwakenScrollBars();
8414        }
8415    }
8416
8417    /**
8418     * Returns the current visibility of the window this view is attached to
8419     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
8420     *
8421     * @return Returns the current visibility of the view's window.
8422     */
8423    @Visibility
8424    public int getWindowVisibility() {
8425        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
8426    }
8427
8428    /**
8429     * Retrieve the overall visible display size in which the window this view is
8430     * attached to has been positioned in.  This takes into account screen
8431     * decorations above the window, for both cases where the window itself
8432     * is being position inside of them or the window is being placed under
8433     * then and covered insets are used for the window to position its content
8434     * inside.  In effect, this tells you the available area where content can
8435     * be placed and remain visible to users.
8436     *
8437     * <p>This function requires an IPC back to the window manager to retrieve
8438     * the requested information, so should not be used in performance critical
8439     * code like drawing.
8440     *
8441     * @param outRect Filled in with the visible display frame.  If the view
8442     * is not attached to a window, this is simply the raw display size.
8443     */
8444    public void getWindowVisibleDisplayFrame(Rect outRect) {
8445        if (mAttachInfo != null) {
8446            try {
8447                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
8448            } catch (RemoteException e) {
8449                return;
8450            }
8451            // XXX This is really broken, and probably all needs to be done
8452            // in the window manager, and we need to know more about whether
8453            // we want the area behind or in front of the IME.
8454            final Rect insets = mAttachInfo.mVisibleInsets;
8455            outRect.left += insets.left;
8456            outRect.top += insets.top;
8457            outRect.right -= insets.right;
8458            outRect.bottom -= insets.bottom;
8459            return;
8460        }
8461        // The view is not attached to a display so we don't have a context.
8462        // Make a best guess about the display size.
8463        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
8464        d.getRectSize(outRect);
8465    }
8466
8467    /**
8468     * Dispatch a notification about a resource configuration change down
8469     * the view hierarchy.
8470     * ViewGroups should override to route to their children.
8471     *
8472     * @param newConfig The new resource configuration.
8473     *
8474     * @see #onConfigurationChanged(android.content.res.Configuration)
8475     */
8476    public void dispatchConfigurationChanged(Configuration newConfig) {
8477        onConfigurationChanged(newConfig);
8478    }
8479
8480    /**
8481     * Called when the current configuration of the resources being used
8482     * by the application have changed.  You can use this to decide when
8483     * to reload resources that can changed based on orientation and other
8484     * configuration characterstics.  You only need to use this if you are
8485     * not relying on the normal {@link android.app.Activity} mechanism of
8486     * recreating the activity instance upon a configuration change.
8487     *
8488     * @param newConfig The new resource configuration.
8489     */
8490    protected void onConfigurationChanged(Configuration newConfig) {
8491    }
8492
8493    /**
8494     * Private function to aggregate all per-view attributes in to the view
8495     * root.
8496     */
8497    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
8498        performCollectViewAttributes(attachInfo, visibility);
8499    }
8500
8501    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
8502        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
8503            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
8504                attachInfo.mKeepScreenOn = true;
8505            }
8506            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
8507            ListenerInfo li = mListenerInfo;
8508            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
8509                attachInfo.mHasSystemUiListeners = true;
8510            }
8511        }
8512    }
8513
8514    void needGlobalAttributesUpdate(boolean force) {
8515        final AttachInfo ai = mAttachInfo;
8516        if (ai != null && !ai.mRecomputeGlobalAttributes) {
8517            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
8518                    || ai.mHasSystemUiListeners) {
8519                ai.mRecomputeGlobalAttributes = true;
8520            }
8521        }
8522    }
8523
8524    /**
8525     * Returns whether the device is currently in touch mode.  Touch mode is entered
8526     * once the user begins interacting with the device by touch, and affects various
8527     * things like whether focus is always visible to the user.
8528     *
8529     * @return Whether the device is in touch mode.
8530     */
8531    @ViewDebug.ExportedProperty
8532    public boolean isInTouchMode() {
8533        if (mAttachInfo != null) {
8534            return mAttachInfo.mInTouchMode;
8535        } else {
8536            return ViewRootImpl.isInTouchMode();
8537        }
8538    }
8539
8540    /**
8541     * Returns the context the view is running in, through which it can
8542     * access the current theme, resources, etc.
8543     *
8544     * @return The view's Context.
8545     */
8546    @ViewDebug.CapturedViewProperty
8547    public final Context getContext() {
8548        return mContext;
8549    }
8550
8551    /**
8552     * Handle a key event before it is processed by any input method
8553     * associated with the view hierarchy.  This can be used to intercept
8554     * key events in special situations before the IME consumes them; a
8555     * typical example would be handling the BACK key to update the application's
8556     * UI instead of allowing the IME to see it and close itself.
8557     *
8558     * @param keyCode The value in event.getKeyCode().
8559     * @param event Description of the key event.
8560     * @return If you handled the event, return true. If you want to allow the
8561     *         event to be handled by the next receiver, return false.
8562     */
8563    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
8564        return false;
8565    }
8566
8567    /**
8568     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
8569     * KeyEvent.Callback.onKeyDown()}: perform press of the view
8570     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
8571     * is released, if the view is enabled and clickable.
8572     *
8573     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8574     * although some may elect to do so in some situations. Do not rely on this to
8575     * catch software key presses.
8576     *
8577     * @param keyCode A key code that represents the button pressed, from
8578     *                {@link android.view.KeyEvent}.
8579     * @param event   The KeyEvent object that defines the button action.
8580     */
8581    public boolean onKeyDown(int keyCode, KeyEvent event) {
8582        boolean result = false;
8583
8584        if (KeyEvent.isConfirmKey(keyCode)) {
8585            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
8586                return true;
8587            }
8588            // Long clickable items don't necessarily have to be clickable
8589            if (((mViewFlags & CLICKABLE) == CLICKABLE ||
8590                    (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
8591                    (event.getRepeatCount() == 0)) {
8592                setPressed(true);
8593                checkForLongClick(0);
8594                return true;
8595            }
8596        }
8597        return result;
8598    }
8599
8600    /**
8601     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
8602     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
8603     * the event).
8604     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8605     * although some may elect to do so in some situations. Do not rely on this to
8606     * catch software key presses.
8607     */
8608    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
8609        return false;
8610    }
8611
8612    /**
8613     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
8614     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
8615     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
8616     * {@link KeyEvent#KEYCODE_ENTER} is released.
8617     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8618     * although some may elect to do so in some situations. Do not rely on this to
8619     * catch software key presses.
8620     *
8621     * @param keyCode A key code that represents the button pressed, from
8622     *                {@link android.view.KeyEvent}.
8623     * @param event   The KeyEvent object that defines the button action.
8624     */
8625    public boolean onKeyUp(int keyCode, KeyEvent event) {
8626        if (KeyEvent.isConfirmKey(keyCode)) {
8627            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
8628                return true;
8629            }
8630            if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
8631                setPressed(false);
8632
8633                if (!mHasPerformedLongPress) {
8634                    // This is a tap, so remove the longpress check
8635                    removeLongPressCallback();
8636                    return performClick();
8637                }
8638            }
8639        }
8640        return false;
8641    }
8642
8643    /**
8644     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
8645     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
8646     * the event).
8647     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8648     * although some may elect to do so in some situations. Do not rely on this to
8649     * catch software key presses.
8650     *
8651     * @param keyCode     A key code that represents the button pressed, from
8652     *                    {@link android.view.KeyEvent}.
8653     * @param repeatCount The number of times the action was made.
8654     * @param event       The KeyEvent object that defines the button action.
8655     */
8656    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
8657        return false;
8658    }
8659
8660    /**
8661     * Called on the focused view when a key shortcut event is not handled.
8662     * Override this method to implement local key shortcuts for the View.
8663     * Key shortcuts can also be implemented by setting the
8664     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
8665     *
8666     * @param keyCode The value in event.getKeyCode().
8667     * @param event Description of the key event.
8668     * @return If you handled the event, return true. If you want to allow the
8669     *         event to be handled by the next receiver, return false.
8670     */
8671    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
8672        return false;
8673    }
8674
8675    /**
8676     * Check whether the called view is a text editor, in which case it
8677     * would make sense to automatically display a soft input window for
8678     * it.  Subclasses should override this if they implement
8679     * {@link #onCreateInputConnection(EditorInfo)} to return true if
8680     * a call on that method would return a non-null InputConnection, and
8681     * they are really a first-class editor that the user would normally
8682     * start typing on when the go into a window containing your view.
8683     *
8684     * <p>The default implementation always returns false.  This does
8685     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
8686     * will not be called or the user can not otherwise perform edits on your
8687     * view; it is just a hint to the system that this is not the primary
8688     * purpose of this view.
8689     *
8690     * @return Returns true if this view is a text editor, else false.
8691     */
8692    public boolean onCheckIsTextEditor() {
8693        return false;
8694    }
8695
8696    /**
8697     * Create a new InputConnection for an InputMethod to interact
8698     * with the view.  The default implementation returns null, since it doesn't
8699     * support input methods.  You can override this to implement such support.
8700     * This is only needed for views that take focus and text input.
8701     *
8702     * <p>When implementing this, you probably also want to implement
8703     * {@link #onCheckIsTextEditor()} to indicate you will return a
8704     * non-null InputConnection.</p>
8705     *
8706     * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo}
8707     * object correctly and in its entirety, so that the connected IME can rely
8708     * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart}
8709     * and  {@link android.view.inputmethod.EditorInfo#initialSelEnd} members
8710     * must be filled in with the correct cursor position for IMEs to work correctly
8711     * with your application.</p>
8712     *
8713     * @param outAttrs Fill in with attribute information about the connection.
8714     */
8715    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
8716        return null;
8717    }
8718
8719    /**
8720     * Called by the {@link android.view.inputmethod.InputMethodManager}
8721     * when a view who is not the current
8722     * input connection target is trying to make a call on the manager.  The
8723     * default implementation returns false; you can override this to return
8724     * true for certain views if you are performing InputConnection proxying
8725     * to them.
8726     * @param view The View that is making the InputMethodManager call.
8727     * @return Return true to allow the call, false to reject.
8728     */
8729    public boolean checkInputConnectionProxy(View view) {
8730        return false;
8731    }
8732
8733    /**
8734     * Show the context menu for this view. It is not safe to hold on to the
8735     * menu after returning from this method.
8736     *
8737     * You should normally not overload this method. Overload
8738     * {@link #onCreateContextMenu(ContextMenu)} or define an
8739     * {@link OnCreateContextMenuListener} to add items to the context menu.
8740     *
8741     * @param menu The context menu to populate
8742     */
8743    public void createContextMenu(ContextMenu menu) {
8744        ContextMenuInfo menuInfo = getContextMenuInfo();
8745
8746        // Sets the current menu info so all items added to menu will have
8747        // my extra info set.
8748        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
8749
8750        onCreateContextMenu(menu);
8751        ListenerInfo li = mListenerInfo;
8752        if (li != null && li.mOnCreateContextMenuListener != null) {
8753            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
8754        }
8755
8756        // Clear the extra information so subsequent items that aren't mine don't
8757        // have my extra info.
8758        ((MenuBuilder)menu).setCurrentMenuInfo(null);
8759
8760        if (mParent != null) {
8761            mParent.createContextMenu(menu);
8762        }
8763    }
8764
8765    /**
8766     * Views should implement this if they have extra information to associate
8767     * with the context menu. The return result is supplied as a parameter to
8768     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
8769     * callback.
8770     *
8771     * @return Extra information about the item for which the context menu
8772     *         should be shown. This information will vary across different
8773     *         subclasses of View.
8774     */
8775    protected ContextMenuInfo getContextMenuInfo() {
8776        return null;
8777    }
8778
8779    /**
8780     * Views should implement this if the view itself is going to add items to
8781     * the context menu.
8782     *
8783     * @param menu the context menu to populate
8784     */
8785    protected void onCreateContextMenu(ContextMenu menu) {
8786    }
8787
8788    /**
8789     * Implement this method to handle trackball motion events.  The
8790     * <em>relative</em> movement of the trackball since the last event
8791     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
8792     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
8793     * that a movement of 1 corresponds to the user pressing one DPAD key (so
8794     * they will often be fractional values, representing the more fine-grained
8795     * movement information available from a trackball).
8796     *
8797     * @param event The motion event.
8798     * @return True if the event was handled, false otherwise.
8799     */
8800    public boolean onTrackballEvent(MotionEvent event) {
8801        return false;
8802    }
8803
8804    /**
8805     * Implement this method to handle generic motion events.
8806     * <p>
8807     * Generic motion events describe joystick movements, mouse hovers, track pad
8808     * touches, scroll wheel movements and other input events.  The
8809     * {@link MotionEvent#getSource() source} of the motion event specifies
8810     * the class of input that was received.  Implementations of this method
8811     * must examine the bits in the source before processing the event.
8812     * The following code example shows how this is done.
8813     * </p><p>
8814     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
8815     * are delivered to the view under the pointer.  All other generic motion events are
8816     * delivered to the focused view.
8817     * </p>
8818     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
8819     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {
8820     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
8821     *             // process the joystick movement...
8822     *             return true;
8823     *         }
8824     *     }
8825     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
8826     *         switch (event.getAction()) {
8827     *             case MotionEvent.ACTION_HOVER_MOVE:
8828     *                 // process the mouse hover movement...
8829     *                 return true;
8830     *             case MotionEvent.ACTION_SCROLL:
8831     *                 // process the scroll wheel movement...
8832     *                 return true;
8833     *         }
8834     *     }
8835     *     return super.onGenericMotionEvent(event);
8836     * }</pre>
8837     *
8838     * @param event The generic motion event being processed.
8839     * @return True if the event was handled, false otherwise.
8840     */
8841    public boolean onGenericMotionEvent(MotionEvent event) {
8842        return false;
8843    }
8844
8845    /**
8846     * Implement this method to handle hover events.
8847     * <p>
8848     * This method is called whenever a pointer is hovering into, over, or out of the
8849     * bounds of a view and the view is not currently being touched.
8850     * Hover events are represented as pointer events with action
8851     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
8852     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
8853     * </p>
8854     * <ul>
8855     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
8856     * when the pointer enters the bounds of the view.</li>
8857     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
8858     * when the pointer has already entered the bounds of the view and has moved.</li>
8859     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
8860     * when the pointer has exited the bounds of the view or when the pointer is
8861     * about to go down due to a button click, tap, or similar user action that
8862     * causes the view to be touched.</li>
8863     * </ul>
8864     * <p>
8865     * The view should implement this method to return true to indicate that it is
8866     * handling the hover event, such as by changing its drawable state.
8867     * </p><p>
8868     * The default implementation calls {@link #setHovered} to update the hovered state
8869     * of the view when a hover enter or hover exit event is received, if the view
8870     * is enabled and is clickable.  The default implementation also sends hover
8871     * accessibility events.
8872     * </p>
8873     *
8874     * @param event The motion event that describes the hover.
8875     * @return True if the view handled the hover event.
8876     *
8877     * @see #isHovered
8878     * @see #setHovered
8879     * @see #onHoverChanged
8880     */
8881    public boolean onHoverEvent(MotionEvent event) {
8882        // The root view may receive hover (or touch) events that are outside the bounds of
8883        // the window.  This code ensures that we only send accessibility events for
8884        // hovers that are actually within the bounds of the root view.
8885        final int action = event.getActionMasked();
8886        if (!mSendingHoverAccessibilityEvents) {
8887            if ((action == MotionEvent.ACTION_HOVER_ENTER
8888                    || action == MotionEvent.ACTION_HOVER_MOVE)
8889                    && !hasHoveredChild()
8890                    && pointInView(event.getX(), event.getY())) {
8891                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
8892                mSendingHoverAccessibilityEvents = true;
8893            }
8894        } else {
8895            if (action == MotionEvent.ACTION_HOVER_EXIT
8896                    || (action == MotionEvent.ACTION_MOVE
8897                            && !pointInView(event.getX(), event.getY()))) {
8898                mSendingHoverAccessibilityEvents = false;
8899                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
8900            }
8901        }
8902
8903        if (isHoverable()) {
8904            switch (action) {
8905                case MotionEvent.ACTION_HOVER_ENTER:
8906                    setHovered(true);
8907                    break;
8908                case MotionEvent.ACTION_HOVER_EXIT:
8909                    setHovered(false);
8910                    break;
8911            }
8912
8913            // Dispatch the event to onGenericMotionEvent before returning true.
8914            // This is to provide compatibility with existing applications that
8915            // handled HOVER_MOVE events in onGenericMotionEvent and that would
8916            // break because of the new default handling for hoverable views
8917            // in onHoverEvent.
8918            // Note that onGenericMotionEvent will be called by default when
8919            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
8920            dispatchGenericMotionEventInternal(event);
8921            // The event was already handled by calling setHovered(), so always
8922            // return true.
8923            return true;
8924        }
8925
8926        return false;
8927    }
8928
8929    /**
8930     * Returns true if the view should handle {@link #onHoverEvent}
8931     * by calling {@link #setHovered} to change its hovered state.
8932     *
8933     * @return True if the view is hoverable.
8934     */
8935    private boolean isHoverable() {
8936        final int viewFlags = mViewFlags;
8937        if ((viewFlags & ENABLED_MASK) == DISABLED) {
8938            return false;
8939        }
8940
8941        return (viewFlags & CLICKABLE) == CLICKABLE
8942                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
8943    }
8944
8945    /**
8946     * Returns true if the view is currently hovered.
8947     *
8948     * @return True if the view is currently hovered.
8949     *
8950     * @see #setHovered
8951     * @see #onHoverChanged
8952     */
8953    @ViewDebug.ExportedProperty
8954    public boolean isHovered() {
8955        return (mPrivateFlags & PFLAG_HOVERED) != 0;
8956    }
8957
8958    /**
8959     * Sets whether the view is currently hovered.
8960     * <p>
8961     * Calling this method also changes the drawable state of the view.  This
8962     * enables the view to react to hover by using different drawable resources
8963     * to change its appearance.
8964     * </p><p>
8965     * The {@link #onHoverChanged} method is called when the hovered state changes.
8966     * </p>
8967     *
8968     * @param hovered True if the view is hovered.
8969     *
8970     * @see #isHovered
8971     * @see #onHoverChanged
8972     */
8973    public void setHovered(boolean hovered) {
8974        if (hovered) {
8975            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
8976                mPrivateFlags |= PFLAG_HOVERED;
8977                refreshDrawableState();
8978                onHoverChanged(true);
8979            }
8980        } else {
8981            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
8982                mPrivateFlags &= ~PFLAG_HOVERED;
8983                refreshDrawableState();
8984                onHoverChanged(false);
8985            }
8986        }
8987    }
8988
8989    /**
8990     * Implement this method to handle hover state changes.
8991     * <p>
8992     * This method is called whenever the hover state changes as a result of a
8993     * call to {@link #setHovered}.
8994     * </p>
8995     *
8996     * @param hovered The current hover state, as returned by {@link #isHovered}.
8997     *
8998     * @see #isHovered
8999     * @see #setHovered
9000     */
9001    public void onHoverChanged(boolean hovered) {
9002    }
9003
9004    /**
9005     * Implement this method to handle touch screen motion events.
9006     * <p>
9007     * If this method is used to detect click actions, it is recommended that
9008     * the actions be performed by implementing and calling
9009     * {@link #performClick()}. This will ensure consistent system behavior,
9010     * including:
9011     * <ul>
9012     * <li>obeying click sound preferences
9013     * <li>dispatching OnClickListener calls
9014     * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when
9015     * accessibility features are enabled
9016     * </ul>
9017     *
9018     * @param event The motion event.
9019     * @return True if the event was handled, false otherwise.
9020     */
9021    public boolean onTouchEvent(MotionEvent event) {
9022        final float x = event.getX();
9023        final float y = event.getY();
9024        final int viewFlags = mViewFlags;
9025
9026        if ((viewFlags & ENABLED_MASK) == DISABLED) {
9027            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
9028                setPressed(false);
9029            }
9030            // A disabled view that is clickable still consumes the touch
9031            // events, it just doesn't respond to them.
9032            return (((viewFlags & CLICKABLE) == CLICKABLE ||
9033                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
9034        }
9035
9036        if (mTouchDelegate != null) {
9037            if (mTouchDelegate.onTouchEvent(event)) {
9038                return true;
9039            }
9040        }
9041
9042        if (((viewFlags & CLICKABLE) == CLICKABLE ||
9043                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
9044            switch (event.getAction()) {
9045                case MotionEvent.ACTION_UP:
9046                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
9047                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
9048                        // take focus if we don't have it already and we should in
9049                        // touch mode.
9050                        boolean focusTaken = false;
9051                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
9052                            focusTaken = requestFocus();
9053                        }
9054
9055                        if (prepressed) {
9056                            // The button is being released before we actually
9057                            // showed it as pressed.  Make it show the pressed
9058                            // state now (before scheduling the click) to ensure
9059                            // the user sees it.
9060                            setPressed(true, x, y);
9061                       }
9062
9063                        if (!mHasPerformedLongPress) {
9064                            // This is a tap, so remove the longpress check
9065                            removeLongPressCallback();
9066
9067                            // Only perform take click actions if we were in the pressed state
9068                            if (!focusTaken) {
9069                                // Use a Runnable and post this rather than calling
9070                                // performClick directly. This lets other visual state
9071                                // of the view update before click actions start.
9072                                if (mPerformClick == null) {
9073                                    mPerformClick = new PerformClick();
9074                                }
9075                                if (!post(mPerformClick)) {
9076                                    performClick();
9077                                }
9078                            }
9079                        }
9080
9081                        if (mUnsetPressedState == null) {
9082                            mUnsetPressedState = new UnsetPressedState();
9083                        }
9084
9085                        if (prepressed) {
9086                            postDelayed(mUnsetPressedState,
9087                                    ViewConfiguration.getPressedStateDuration());
9088                        } else if (!post(mUnsetPressedState)) {
9089                            // If the post failed, unpress right now
9090                            mUnsetPressedState.run();
9091                        }
9092
9093                        removeTapCallback();
9094                    }
9095                    break;
9096
9097                case MotionEvent.ACTION_DOWN:
9098                    mHasPerformedLongPress = false;
9099
9100                    if (performButtonActionOnTouchDown(event)) {
9101                        break;
9102                    }
9103
9104                    // Walk up the hierarchy to determine if we're inside a scrolling container.
9105                    boolean isInScrollingContainer = isInScrollingContainer();
9106
9107                    // For views inside a scrolling container, delay the pressed feedback for
9108                    // a short period in case this is a scroll.
9109                    if (isInScrollingContainer) {
9110                        mPrivateFlags |= PFLAG_PREPRESSED;
9111                        if (mPendingCheckForTap == null) {
9112                            mPendingCheckForTap = new CheckForTap();
9113                        }
9114                        mPendingCheckForTap.x = event.getX();
9115                        mPendingCheckForTap.y = event.getY();
9116                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
9117                    } else {
9118                        // Not inside a scrolling container, so show the feedback right away
9119                        setPressed(true, x, y);
9120                        checkForLongClick(0);
9121                    }
9122                    break;
9123
9124                case MotionEvent.ACTION_CANCEL:
9125                    setPressed(false);
9126                    removeTapCallback();
9127                    removeLongPressCallback();
9128                    break;
9129
9130                case MotionEvent.ACTION_MOVE:
9131                    setDrawableHotspot(x, y);
9132
9133                    // Be lenient about moving outside of buttons
9134                    if (!pointInView(x, y, mTouchSlop)) {
9135                        // Outside button
9136                        removeTapCallback();
9137                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
9138                            // Remove any future long press/tap checks
9139                            removeLongPressCallback();
9140
9141                            setPressed(false);
9142                        }
9143                    }
9144                    break;
9145            }
9146
9147            return true;
9148        }
9149
9150        return false;
9151    }
9152
9153    /**
9154     * @hide
9155     */
9156    public boolean isInScrollingContainer() {
9157        ViewParent p = getParent();
9158        while (p != null && p instanceof ViewGroup) {
9159            if (((ViewGroup) p).shouldDelayChildPressedState()) {
9160                return true;
9161            }
9162            p = p.getParent();
9163        }
9164        return false;
9165    }
9166
9167    /**
9168     * Remove the longpress detection timer.
9169     */
9170    private void removeLongPressCallback() {
9171        if (mPendingCheckForLongPress != null) {
9172          removeCallbacks(mPendingCheckForLongPress);
9173        }
9174    }
9175
9176    /**
9177     * Remove the pending click action
9178     */
9179    private void removePerformClickCallback() {
9180        if (mPerformClick != null) {
9181            removeCallbacks(mPerformClick);
9182        }
9183    }
9184
9185    /**
9186     * Remove the prepress detection timer.
9187     */
9188    private void removeUnsetPressCallback() {
9189        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
9190            setPressed(false);
9191            removeCallbacks(mUnsetPressedState);
9192        }
9193    }
9194
9195    /**
9196     * Remove the tap detection timer.
9197     */
9198    private void removeTapCallback() {
9199        if (mPendingCheckForTap != null) {
9200            mPrivateFlags &= ~PFLAG_PREPRESSED;
9201            removeCallbacks(mPendingCheckForTap);
9202        }
9203    }
9204
9205    /**
9206     * Cancels a pending long press.  Your subclass can use this if you
9207     * want the context menu to come up if the user presses and holds
9208     * at the same place, but you don't want it to come up if they press
9209     * and then move around enough to cause scrolling.
9210     */
9211    public void cancelLongPress() {
9212        removeLongPressCallback();
9213
9214        /*
9215         * The prepressed state handled by the tap callback is a display
9216         * construct, but the tap callback will post a long press callback
9217         * less its own timeout. Remove it here.
9218         */
9219        removeTapCallback();
9220    }
9221
9222    /**
9223     * Remove the pending callback for sending a
9224     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
9225     */
9226    private void removeSendViewScrolledAccessibilityEventCallback() {
9227        if (mSendViewScrolledAccessibilityEvent != null) {
9228            removeCallbacks(mSendViewScrolledAccessibilityEvent);
9229            mSendViewScrolledAccessibilityEvent.mIsPending = false;
9230        }
9231    }
9232
9233    /**
9234     * Sets the TouchDelegate for this View.
9235     */
9236    public void setTouchDelegate(TouchDelegate delegate) {
9237        mTouchDelegate = delegate;
9238    }
9239
9240    /**
9241     * Gets the TouchDelegate for this View.
9242     */
9243    public TouchDelegate getTouchDelegate() {
9244        return mTouchDelegate;
9245    }
9246
9247    /**
9248     * Request unbuffered dispatch of the given stream of MotionEvents to this View.
9249     *
9250     * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input
9251     * system not batch {@link MotionEvent}s but instead deliver them as soon as they're
9252     * available. This method should only be called for touch events.
9253     *
9254     * <p class="note">This api is not intended for most applications. Buffered dispatch
9255     * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent
9256     * streams will not improve your input latency. Side effects include: increased latency,
9257     * jittery scrolls and inability to take advantage of system resampling. Talk to your input
9258     * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for
9259     * you.</p>
9260     */
9261    public final void requestUnbufferedDispatch(MotionEvent event) {
9262        final int action = event.getAction();
9263        if (mAttachInfo == null
9264                || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE
9265                || !event.isTouchEvent()) {
9266            return;
9267        }
9268        mAttachInfo.mUnbufferedDispatchRequested = true;
9269    }
9270
9271    /**
9272     * Set flags controlling behavior of this view.
9273     *
9274     * @param flags Constant indicating the value which should be set
9275     * @param mask Constant indicating the bit range that should be changed
9276     */
9277    void setFlags(int flags, int mask) {
9278        final boolean accessibilityEnabled =
9279                AccessibilityManager.getInstance(mContext).isEnabled();
9280        final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility();
9281
9282        int old = mViewFlags;
9283        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
9284
9285        int changed = mViewFlags ^ old;
9286        if (changed == 0) {
9287            return;
9288        }
9289        int privateFlags = mPrivateFlags;
9290
9291        /* Check if the FOCUSABLE bit has changed */
9292        if (((changed & FOCUSABLE_MASK) != 0) &&
9293                ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) {
9294            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
9295                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
9296                /* Give up focus if we are no longer focusable */
9297                clearFocus();
9298            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
9299                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
9300                /*
9301                 * Tell the view system that we are now available to take focus
9302                 * if no one else already has it.
9303                 */
9304                if (mParent != null) mParent.focusableViewAvailable(this);
9305            }
9306        }
9307
9308        final int newVisibility = flags & VISIBILITY_MASK;
9309        if (newVisibility == VISIBLE) {
9310            if ((changed & VISIBILITY_MASK) != 0) {
9311                /*
9312                 * If this view is becoming visible, invalidate it in case it changed while
9313                 * it was not visible. Marking it drawn ensures that the invalidation will
9314                 * go through.
9315                 */
9316                mPrivateFlags |= PFLAG_DRAWN;
9317                invalidate(true);
9318
9319                needGlobalAttributesUpdate(true);
9320
9321                // a view becoming visible is worth notifying the parent
9322                // about in case nothing has focus.  even if this specific view
9323                // isn't focusable, it may contain something that is, so let
9324                // the root view try to give this focus if nothing else does.
9325                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
9326                    mParent.focusableViewAvailable(this);
9327                }
9328            }
9329        }
9330
9331        /* Check if the GONE bit has changed */
9332        if ((changed & GONE) != 0) {
9333            needGlobalAttributesUpdate(false);
9334            requestLayout();
9335
9336            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
9337                if (hasFocus()) clearFocus();
9338                clearAccessibilityFocus();
9339                destroyDrawingCache();
9340                if (mParent instanceof View) {
9341                    // GONE views noop invalidation, so invalidate the parent
9342                    ((View) mParent).invalidate(true);
9343                }
9344                // Mark the view drawn to ensure that it gets invalidated properly the next
9345                // time it is visible and gets invalidated
9346                mPrivateFlags |= PFLAG_DRAWN;
9347            }
9348            if (mAttachInfo != null) {
9349                mAttachInfo.mViewVisibilityChanged = true;
9350            }
9351        }
9352
9353        /* Check if the VISIBLE bit has changed */
9354        if ((changed & INVISIBLE) != 0) {
9355            needGlobalAttributesUpdate(false);
9356            /*
9357             * If this view is becoming invisible, set the DRAWN flag so that
9358             * the next invalidate() will not be skipped.
9359             */
9360            mPrivateFlags |= PFLAG_DRAWN;
9361
9362            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) {
9363                // root view becoming invisible shouldn't clear focus and accessibility focus
9364                if (getRootView() != this) {
9365                    if (hasFocus()) clearFocus();
9366                    clearAccessibilityFocus();
9367                }
9368            }
9369            if (mAttachInfo != null) {
9370                mAttachInfo.mViewVisibilityChanged = true;
9371            }
9372        }
9373
9374        if ((changed & VISIBILITY_MASK) != 0) {
9375            // If the view is invisible, cleanup its display list to free up resources
9376            if (newVisibility != VISIBLE && mAttachInfo != null) {
9377                cleanupDraw();
9378            }
9379
9380            if (mParent instanceof ViewGroup) {
9381                ((ViewGroup) mParent).onChildVisibilityChanged(this,
9382                        (changed & VISIBILITY_MASK), newVisibility);
9383                ((View) mParent).invalidate(true);
9384            } else if (mParent != null) {
9385                mParent.invalidateChild(this, null);
9386            }
9387            dispatchVisibilityChanged(this, newVisibility);
9388
9389            notifySubtreeAccessibilityStateChangedIfNeeded();
9390        }
9391
9392        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
9393            destroyDrawingCache();
9394        }
9395
9396        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
9397            destroyDrawingCache();
9398            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
9399            invalidateParentCaches();
9400        }
9401
9402        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
9403            destroyDrawingCache();
9404            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
9405        }
9406
9407        if ((changed & DRAW_MASK) != 0) {
9408            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
9409                if (mBackground != null) {
9410                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
9411                    mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
9412                } else {
9413                    mPrivateFlags |= PFLAG_SKIP_DRAW;
9414                }
9415            } else {
9416                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
9417            }
9418            requestLayout();
9419            invalidate(true);
9420        }
9421
9422        if ((changed & KEEP_SCREEN_ON) != 0) {
9423            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
9424                mParent.recomputeViewAttributes(this);
9425            }
9426        }
9427
9428        if (accessibilityEnabled) {
9429            if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0
9430                    || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0) {
9431                if (oldIncludeForAccessibility != includeForAccessibility()) {
9432                    notifySubtreeAccessibilityStateChangedIfNeeded();
9433                } else {
9434                    notifyViewAccessibilityStateChangedIfNeeded(
9435                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9436                }
9437            } else if ((changed & ENABLED_MASK) != 0) {
9438                notifyViewAccessibilityStateChangedIfNeeded(
9439                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9440            }
9441        }
9442    }
9443
9444    /**
9445     * Change the view's z order in the tree, so it's on top of other sibling
9446     * views. This ordering change may affect layout, if the parent container
9447     * uses an order-dependent layout scheme (e.g., LinearLayout). Prior
9448     * to {@link android.os.Build.VERSION_CODES#KITKAT} this
9449     * method should be followed by calls to {@link #requestLayout()} and
9450     * {@link View#invalidate()} on the view's parent to force the parent to redraw
9451     * with the new child ordering.
9452     *
9453     * @see ViewGroup#bringChildToFront(View)
9454     */
9455    public void bringToFront() {
9456        if (mParent != null) {
9457            mParent.bringChildToFront(this);
9458        }
9459    }
9460
9461    /**
9462     * This is called in response to an internal scroll in this view (i.e., the
9463     * view scrolled its own contents). This is typically as a result of
9464     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
9465     * called.
9466     *
9467     * @param l Current horizontal scroll origin.
9468     * @param t Current vertical scroll origin.
9469     * @param oldl Previous horizontal scroll origin.
9470     * @param oldt Previous vertical scroll origin.
9471     */
9472    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
9473        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
9474            postSendViewScrolledAccessibilityEventCallback();
9475        }
9476
9477        mBackgroundSizeChanged = true;
9478
9479        final AttachInfo ai = mAttachInfo;
9480        if (ai != null) {
9481            ai.mViewScrollChanged = true;
9482        }
9483    }
9484
9485    /**
9486     * Interface definition for a callback to be invoked when the layout bounds of a view
9487     * changes due to layout processing.
9488     */
9489    public interface OnLayoutChangeListener {
9490        /**
9491         * Called when the layout bounds of a view changes due to layout processing.
9492         *
9493         * @param v The view whose bounds have changed.
9494         * @param left The new value of the view's left property.
9495         * @param top The new value of the view's top property.
9496         * @param right The new value of the view's right property.
9497         * @param bottom The new value of the view's bottom property.
9498         * @param oldLeft The previous value of the view's left property.
9499         * @param oldTop The previous value of the view's top property.
9500         * @param oldRight The previous value of the view's right property.
9501         * @param oldBottom The previous value of the view's bottom property.
9502         */
9503        void onLayoutChange(View v, int left, int top, int right, int bottom,
9504            int oldLeft, int oldTop, int oldRight, int oldBottom);
9505    }
9506
9507    /**
9508     * This is called during layout when the size of this view has changed. If
9509     * you were just added to the view hierarchy, you're called with the old
9510     * values of 0.
9511     *
9512     * @param w Current width of this view.
9513     * @param h Current height of this view.
9514     * @param oldw Old width of this view.
9515     * @param oldh Old height of this view.
9516     */
9517    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
9518    }
9519
9520    /**
9521     * Called by draw to draw the child views. This may be overridden
9522     * by derived classes to gain control just before its children are drawn
9523     * (but after its own view has been drawn).
9524     * @param canvas the canvas on which to draw the view
9525     */
9526    protected void dispatchDraw(Canvas canvas) {
9527
9528    }
9529
9530    /**
9531     * Gets the parent of this view. Note that the parent is a
9532     * ViewParent and not necessarily a View.
9533     *
9534     * @return Parent of this view.
9535     */
9536    public final ViewParent getParent() {
9537        return mParent;
9538    }
9539
9540    /**
9541     * Set the horizontal scrolled position of your view. This will cause a call to
9542     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9543     * invalidated.
9544     * @param value the x position to scroll to
9545     */
9546    public void setScrollX(int value) {
9547        scrollTo(value, mScrollY);
9548    }
9549
9550    /**
9551     * Set the vertical scrolled position of your view. This will cause a call to
9552     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9553     * invalidated.
9554     * @param value the y position to scroll to
9555     */
9556    public void setScrollY(int value) {
9557        scrollTo(mScrollX, value);
9558    }
9559
9560    /**
9561     * Return the scrolled left position of this view. This is the left edge of
9562     * the displayed part of your view. You do not need to draw any pixels
9563     * farther left, since those are outside of the frame of your view on
9564     * screen.
9565     *
9566     * @return The left edge of the displayed part of your view, in pixels.
9567     */
9568    public final int getScrollX() {
9569        return mScrollX;
9570    }
9571
9572    /**
9573     * Return the scrolled top position of this view. This is the top edge of
9574     * the displayed part of your view. You do not need to draw any pixels above
9575     * it, since those are outside of the frame of your view on screen.
9576     *
9577     * @return The top edge of the displayed part of your view, in pixels.
9578     */
9579    public final int getScrollY() {
9580        return mScrollY;
9581    }
9582
9583    /**
9584     * Return the width of the your view.
9585     *
9586     * @return The width of your view, in pixels.
9587     */
9588    @ViewDebug.ExportedProperty(category = "layout")
9589    public final int getWidth() {
9590        return mRight - mLeft;
9591    }
9592
9593    /**
9594     * Return the height of your view.
9595     *
9596     * @return The height of your view, in pixels.
9597     */
9598    @ViewDebug.ExportedProperty(category = "layout")
9599    public final int getHeight() {
9600        return mBottom - mTop;
9601    }
9602
9603    /**
9604     * Return the visible drawing bounds of your view. Fills in the output
9605     * rectangle with the values from getScrollX(), getScrollY(),
9606     * getWidth(), and getHeight(). These bounds do not account for any
9607     * transformation properties currently set on the view, such as
9608     * {@link #setScaleX(float)} or {@link #setRotation(float)}.
9609     *
9610     * @param outRect The (scrolled) drawing bounds of the view.
9611     */
9612    public void getDrawingRect(Rect outRect) {
9613        outRect.left = mScrollX;
9614        outRect.top = mScrollY;
9615        outRect.right = mScrollX + (mRight - mLeft);
9616        outRect.bottom = mScrollY + (mBottom - mTop);
9617    }
9618
9619    /**
9620     * Like {@link #getMeasuredWidthAndState()}, but only returns the
9621     * raw width component (that is the result is masked by
9622     * {@link #MEASURED_SIZE_MASK}).
9623     *
9624     * @return The raw measured width of this view.
9625     */
9626    public final int getMeasuredWidth() {
9627        return mMeasuredWidth & MEASURED_SIZE_MASK;
9628    }
9629
9630    /**
9631     * Return the full width measurement information for this view as computed
9632     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
9633     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
9634     * This should be used during measurement and layout calculations only. Use
9635     * {@link #getWidth()} to see how wide a view is after layout.
9636     *
9637     * @return The measured width of this view as a bit mask.
9638     */
9639    public final int getMeasuredWidthAndState() {
9640        return mMeasuredWidth;
9641    }
9642
9643    /**
9644     * Like {@link #getMeasuredHeightAndState()}, but only returns the
9645     * raw width component (that is the result is masked by
9646     * {@link #MEASURED_SIZE_MASK}).
9647     *
9648     * @return The raw measured height of this view.
9649     */
9650    public final int getMeasuredHeight() {
9651        return mMeasuredHeight & MEASURED_SIZE_MASK;
9652    }
9653
9654    /**
9655     * Return the full height measurement information for this view as computed
9656     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
9657     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
9658     * This should be used during measurement and layout calculations only. Use
9659     * {@link #getHeight()} to see how wide a view is after layout.
9660     *
9661     * @return The measured width of this view as a bit mask.
9662     */
9663    public final int getMeasuredHeightAndState() {
9664        return mMeasuredHeight;
9665    }
9666
9667    /**
9668     * Return only the state bits of {@link #getMeasuredWidthAndState()}
9669     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
9670     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
9671     * and the height component is at the shifted bits
9672     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
9673     */
9674    public final int getMeasuredState() {
9675        return (mMeasuredWidth&MEASURED_STATE_MASK)
9676                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
9677                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
9678    }
9679
9680    /**
9681     * The transform matrix of this view, which is calculated based on the current
9682     * rotation, scale, and pivot properties.
9683     *
9684     * @see #getRotation()
9685     * @see #getScaleX()
9686     * @see #getScaleY()
9687     * @see #getPivotX()
9688     * @see #getPivotY()
9689     * @return The current transform matrix for the view
9690     */
9691    public Matrix getMatrix() {
9692        ensureTransformationInfo();
9693        final Matrix matrix = mTransformationInfo.mMatrix;
9694        mRenderNode.getMatrix(matrix);
9695        return matrix;
9696    }
9697
9698    /**
9699     * Returns true if the transform matrix is the identity matrix.
9700     * Recomputes the matrix if necessary.
9701     *
9702     * @return True if the transform matrix is the identity matrix, false otherwise.
9703     */
9704    final boolean hasIdentityMatrix() {
9705        return mRenderNode.hasIdentityMatrix();
9706    }
9707
9708    void ensureTransformationInfo() {
9709        if (mTransformationInfo == null) {
9710            mTransformationInfo = new TransformationInfo();
9711        }
9712    }
9713
9714   /**
9715     * Utility method to retrieve the inverse of the current mMatrix property.
9716     * We cache the matrix to avoid recalculating it when transform properties
9717     * have not changed.
9718     *
9719     * @return The inverse of the current matrix of this view.
9720     */
9721    final Matrix getInverseMatrix() {
9722        ensureTransformationInfo();
9723        if (mTransformationInfo.mInverseMatrix == null) {
9724            mTransformationInfo.mInverseMatrix = new Matrix();
9725        }
9726        final Matrix matrix = mTransformationInfo.mInverseMatrix;
9727        mRenderNode.getInverseMatrix(matrix);
9728        return matrix;
9729    }
9730
9731    /**
9732     * Gets the distance along the Z axis from the camera to this view.
9733     *
9734     * @see #setCameraDistance(float)
9735     *
9736     * @return The distance along the Z axis.
9737     */
9738    public float getCameraDistance() {
9739        final float dpi = mResources.getDisplayMetrics().densityDpi;
9740        return -(mRenderNode.getCameraDistance() * dpi);
9741    }
9742
9743    /**
9744     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
9745     * views are drawn) from the camera to this view. The camera's distance
9746     * affects 3D transformations, for instance rotations around the X and Y
9747     * axis. If the rotationX or rotationY properties are changed and this view is
9748     * large (more than half the size of the screen), it is recommended to always
9749     * use a camera distance that's greater than the height (X axis rotation) or
9750     * the width (Y axis rotation) of this view.</p>
9751     *
9752     * <p>The distance of the camera from the view plane can have an affect on the
9753     * perspective distortion of the view when it is rotated around the x or y axis.
9754     * For example, a large distance will result in a large viewing angle, and there
9755     * will not be much perspective distortion of the view as it rotates. A short
9756     * distance may cause much more perspective distortion upon rotation, and can
9757     * also result in some drawing artifacts if the rotated view ends up partially
9758     * behind the camera (which is why the recommendation is to use a distance at
9759     * least as far as the size of the view, if the view is to be rotated.)</p>
9760     *
9761     * <p>The distance is expressed in "depth pixels." The default distance depends
9762     * on the screen density. For instance, on a medium density display, the
9763     * default distance is 1280. On a high density display, the default distance
9764     * is 1920.</p>
9765     *
9766     * <p>If you want to specify a distance that leads to visually consistent
9767     * results across various densities, use the following formula:</p>
9768     * <pre>
9769     * float scale = context.getResources().getDisplayMetrics().density;
9770     * view.setCameraDistance(distance * scale);
9771     * </pre>
9772     *
9773     * <p>The density scale factor of a high density display is 1.5,
9774     * and 1920 = 1280 * 1.5.</p>
9775     *
9776     * @param distance The distance in "depth pixels", if negative the opposite
9777     *        value is used
9778     *
9779     * @see #setRotationX(float)
9780     * @see #setRotationY(float)
9781     */
9782    public void setCameraDistance(float distance) {
9783        final float dpi = mResources.getDisplayMetrics().densityDpi;
9784
9785        invalidateViewProperty(true, false);
9786        mRenderNode.setCameraDistance(-Math.abs(distance) / dpi);
9787        invalidateViewProperty(false, false);
9788
9789        invalidateParentIfNeededAndWasQuickRejected();
9790    }
9791
9792    /**
9793     * The degrees that the view is rotated around the pivot point.
9794     *
9795     * @see #setRotation(float)
9796     * @see #getPivotX()
9797     * @see #getPivotY()
9798     *
9799     * @return The degrees of rotation.
9800     */
9801    @ViewDebug.ExportedProperty(category = "drawing")
9802    public float getRotation() {
9803        return mRenderNode.getRotation();
9804    }
9805
9806    /**
9807     * Sets the degrees that the view is rotated around the pivot point. Increasing values
9808     * result in clockwise rotation.
9809     *
9810     * @param rotation The degrees of rotation.
9811     *
9812     * @see #getRotation()
9813     * @see #getPivotX()
9814     * @see #getPivotY()
9815     * @see #setRotationX(float)
9816     * @see #setRotationY(float)
9817     *
9818     * @attr ref android.R.styleable#View_rotation
9819     */
9820    public void setRotation(float rotation) {
9821        if (rotation != getRotation()) {
9822            // Double-invalidation is necessary to capture view's old and new areas
9823            invalidateViewProperty(true, false);
9824            mRenderNode.setRotation(rotation);
9825            invalidateViewProperty(false, true);
9826
9827            invalidateParentIfNeededAndWasQuickRejected();
9828            notifySubtreeAccessibilityStateChangedIfNeeded();
9829        }
9830    }
9831
9832    /**
9833     * The degrees that the view is rotated around the vertical axis through the pivot point.
9834     *
9835     * @see #getPivotX()
9836     * @see #getPivotY()
9837     * @see #setRotationY(float)
9838     *
9839     * @return The degrees of Y rotation.
9840     */
9841    @ViewDebug.ExportedProperty(category = "drawing")
9842    public float getRotationY() {
9843        return mRenderNode.getRotationY();
9844    }
9845
9846    /**
9847     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
9848     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
9849     * down the y axis.
9850     *
9851     * When rotating large views, it is recommended to adjust the camera distance
9852     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
9853     *
9854     * @param rotationY The degrees of Y rotation.
9855     *
9856     * @see #getRotationY()
9857     * @see #getPivotX()
9858     * @see #getPivotY()
9859     * @see #setRotation(float)
9860     * @see #setRotationX(float)
9861     * @see #setCameraDistance(float)
9862     *
9863     * @attr ref android.R.styleable#View_rotationY
9864     */
9865    public void setRotationY(float rotationY) {
9866        if (rotationY != getRotationY()) {
9867            invalidateViewProperty(true, false);
9868            mRenderNode.setRotationY(rotationY);
9869            invalidateViewProperty(false, true);
9870
9871            invalidateParentIfNeededAndWasQuickRejected();
9872            notifySubtreeAccessibilityStateChangedIfNeeded();
9873        }
9874    }
9875
9876    /**
9877     * The degrees that the view is rotated around the horizontal axis through the pivot point.
9878     *
9879     * @see #getPivotX()
9880     * @see #getPivotY()
9881     * @see #setRotationX(float)
9882     *
9883     * @return The degrees of X rotation.
9884     */
9885    @ViewDebug.ExportedProperty(category = "drawing")
9886    public float getRotationX() {
9887        return mRenderNode.getRotationX();
9888    }
9889
9890    /**
9891     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
9892     * Increasing values result in clockwise rotation from the viewpoint of looking down the
9893     * x axis.
9894     *
9895     * When rotating large views, it is recommended to adjust the camera distance
9896     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
9897     *
9898     * @param rotationX The degrees of X rotation.
9899     *
9900     * @see #getRotationX()
9901     * @see #getPivotX()
9902     * @see #getPivotY()
9903     * @see #setRotation(float)
9904     * @see #setRotationY(float)
9905     * @see #setCameraDistance(float)
9906     *
9907     * @attr ref android.R.styleable#View_rotationX
9908     */
9909    public void setRotationX(float rotationX) {
9910        if (rotationX != getRotationX()) {
9911            invalidateViewProperty(true, false);
9912            mRenderNode.setRotationX(rotationX);
9913            invalidateViewProperty(false, true);
9914
9915            invalidateParentIfNeededAndWasQuickRejected();
9916            notifySubtreeAccessibilityStateChangedIfNeeded();
9917        }
9918    }
9919
9920    /**
9921     * The amount that the view is scaled in x around the pivot point, as a proportion of
9922     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
9923     *
9924     * <p>By default, this is 1.0f.
9925     *
9926     * @see #getPivotX()
9927     * @see #getPivotY()
9928     * @return The scaling factor.
9929     */
9930    @ViewDebug.ExportedProperty(category = "drawing")
9931    public float getScaleX() {
9932        return mRenderNode.getScaleX();
9933    }
9934
9935    /**
9936     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
9937     * the view's unscaled width. A value of 1 means that no scaling is applied.
9938     *
9939     * @param scaleX The scaling factor.
9940     * @see #getPivotX()
9941     * @see #getPivotY()
9942     *
9943     * @attr ref android.R.styleable#View_scaleX
9944     */
9945    public void setScaleX(float scaleX) {
9946        if (scaleX != getScaleX()) {
9947            invalidateViewProperty(true, false);
9948            mRenderNode.setScaleX(scaleX);
9949            invalidateViewProperty(false, true);
9950
9951            invalidateParentIfNeededAndWasQuickRejected();
9952            notifySubtreeAccessibilityStateChangedIfNeeded();
9953        }
9954    }
9955
9956    /**
9957     * The amount that the view is scaled in y around the pivot point, as a proportion of
9958     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
9959     *
9960     * <p>By default, this is 1.0f.
9961     *
9962     * @see #getPivotX()
9963     * @see #getPivotY()
9964     * @return The scaling factor.
9965     */
9966    @ViewDebug.ExportedProperty(category = "drawing")
9967    public float getScaleY() {
9968        return mRenderNode.getScaleY();
9969    }
9970
9971    /**
9972     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
9973     * the view's unscaled width. A value of 1 means that no scaling is applied.
9974     *
9975     * @param scaleY The scaling factor.
9976     * @see #getPivotX()
9977     * @see #getPivotY()
9978     *
9979     * @attr ref android.R.styleable#View_scaleY
9980     */
9981    public void setScaleY(float scaleY) {
9982        if (scaleY != getScaleY()) {
9983            invalidateViewProperty(true, false);
9984            mRenderNode.setScaleY(scaleY);
9985            invalidateViewProperty(false, true);
9986
9987            invalidateParentIfNeededAndWasQuickRejected();
9988            notifySubtreeAccessibilityStateChangedIfNeeded();
9989        }
9990    }
9991
9992    /**
9993     * The x location of the point around which the view is {@link #setRotation(float) rotated}
9994     * and {@link #setScaleX(float) scaled}.
9995     *
9996     * @see #getRotation()
9997     * @see #getScaleX()
9998     * @see #getScaleY()
9999     * @see #getPivotY()
10000     * @return The x location of the pivot point.
10001     *
10002     * @attr ref android.R.styleable#View_transformPivotX
10003     */
10004    @ViewDebug.ExportedProperty(category = "drawing")
10005    public float getPivotX() {
10006        return mRenderNode.getPivotX();
10007    }
10008
10009    /**
10010     * Sets the x location of the point around which the view is
10011     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
10012     * By default, the pivot point is centered on the object.
10013     * Setting this property disables this behavior and causes the view to use only the
10014     * explicitly set pivotX and pivotY values.
10015     *
10016     * @param pivotX The x location of the pivot point.
10017     * @see #getRotation()
10018     * @see #getScaleX()
10019     * @see #getScaleY()
10020     * @see #getPivotY()
10021     *
10022     * @attr ref android.R.styleable#View_transformPivotX
10023     */
10024    public void setPivotX(float pivotX) {
10025        if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) {
10026            invalidateViewProperty(true, false);
10027            mRenderNode.setPivotX(pivotX);
10028            invalidateViewProperty(false, true);
10029
10030            invalidateParentIfNeededAndWasQuickRejected();
10031        }
10032    }
10033
10034    /**
10035     * The y location of the point around which the view is {@link #setRotation(float) rotated}
10036     * and {@link #setScaleY(float) scaled}.
10037     *
10038     * @see #getRotation()
10039     * @see #getScaleX()
10040     * @see #getScaleY()
10041     * @see #getPivotY()
10042     * @return The y location of the pivot point.
10043     *
10044     * @attr ref android.R.styleable#View_transformPivotY
10045     */
10046    @ViewDebug.ExportedProperty(category = "drawing")
10047    public float getPivotY() {
10048        return mRenderNode.getPivotY();
10049    }
10050
10051    /**
10052     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
10053     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
10054     * Setting this property disables this behavior and causes the view to use only the
10055     * explicitly set pivotX and pivotY values.
10056     *
10057     * @param pivotY The y location of the pivot point.
10058     * @see #getRotation()
10059     * @see #getScaleX()
10060     * @see #getScaleY()
10061     * @see #getPivotY()
10062     *
10063     * @attr ref android.R.styleable#View_transformPivotY
10064     */
10065    public void setPivotY(float pivotY) {
10066        if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) {
10067            invalidateViewProperty(true, false);
10068            mRenderNode.setPivotY(pivotY);
10069            invalidateViewProperty(false, true);
10070
10071            invalidateParentIfNeededAndWasQuickRejected();
10072        }
10073    }
10074
10075    /**
10076     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
10077     * completely transparent and 1 means the view is completely opaque.
10078     *
10079     * <p>By default this is 1.0f.
10080     * @return The opacity of the view.
10081     */
10082    @ViewDebug.ExportedProperty(category = "drawing")
10083    public float getAlpha() {
10084        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
10085    }
10086
10087    /**
10088     * Returns whether this View has content which overlaps.
10089     *
10090     * <p>This function, intended to be overridden by specific View types, is an optimization when
10091     * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to
10092     * an offscreen buffer and then composited into place, which can be expensive. If the view has
10093     * no overlapping rendering, the view can draw each primitive with the appropriate alpha value
10094     * directly. An example of overlapping rendering is a TextView with a background image, such as
10095     * a Button. An example of non-overlapping rendering is a TextView with no background, or an
10096     * ImageView with only the foreground image. The default implementation returns true; subclasses
10097     * should override if they have cases which can be optimized.</p>
10098     *
10099     * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas}
10100     * necessitates that a View return true if it uses the methods internally without passing the
10101     * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p>
10102     *
10103     * @return true if the content in this view might overlap, false otherwise.
10104     */
10105    public boolean hasOverlappingRendering() {
10106        return true;
10107    }
10108
10109    /**
10110     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
10111     * completely transparent and 1 means the view is completely opaque.</p>
10112     *
10113     * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant
10114     * performance implications, especially for large views. It is best to use the alpha property
10115     * sparingly and transiently, as in the case of fading animations.</p>
10116     *
10117     * <p>For a view with a frequently changing alpha, such as during a fading animation, it is
10118     * strongly recommended for performance reasons to either override
10119     * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a
10120     * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p>
10121     *
10122     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
10123     * responsible for applying the opacity itself.</p>
10124     *
10125     * <p>Note that if the view is backed by a
10126     * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a
10127     * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than
10128     * 1.0 will supercede the alpha of the layer paint.</p>
10129     *
10130     * @param alpha The opacity of the view.
10131     *
10132     * @see #hasOverlappingRendering()
10133     * @see #setLayerType(int, android.graphics.Paint)
10134     *
10135     * @attr ref android.R.styleable#View_alpha
10136     */
10137    public void setAlpha(float alpha) {
10138        ensureTransformationInfo();
10139        if (mTransformationInfo.mAlpha != alpha) {
10140            mTransformationInfo.mAlpha = alpha;
10141            if (onSetAlpha((int) (alpha * 255))) {
10142                mPrivateFlags |= PFLAG_ALPHA_SET;
10143                // subclass is handling alpha - don't optimize rendering cache invalidation
10144                invalidateParentCaches();
10145                invalidate(true);
10146            } else {
10147                mPrivateFlags &= ~PFLAG_ALPHA_SET;
10148                invalidateViewProperty(true, false);
10149                mRenderNode.setAlpha(getFinalAlpha());
10150                notifyViewAccessibilityStateChangedIfNeeded(
10151                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
10152            }
10153        }
10154    }
10155
10156    /**
10157     * Faster version of setAlpha() which performs the same steps except there are
10158     * no calls to invalidate(). The caller of this function should perform proper invalidation
10159     * on the parent and this object. The return value indicates whether the subclass handles
10160     * alpha (the return value for onSetAlpha()).
10161     *
10162     * @param alpha The new value for the alpha property
10163     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
10164     *         the new value for the alpha property is different from the old value
10165     */
10166    boolean setAlphaNoInvalidation(float alpha) {
10167        ensureTransformationInfo();
10168        if (mTransformationInfo.mAlpha != alpha) {
10169            mTransformationInfo.mAlpha = alpha;
10170            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
10171            if (subclassHandlesAlpha) {
10172                mPrivateFlags |= PFLAG_ALPHA_SET;
10173                return true;
10174            } else {
10175                mPrivateFlags &= ~PFLAG_ALPHA_SET;
10176                mRenderNode.setAlpha(getFinalAlpha());
10177            }
10178        }
10179        return false;
10180    }
10181
10182    /**
10183     * This property is hidden and intended only for use by the Fade transition, which
10184     * animates it to produce a visual translucency that does not side-effect (or get
10185     * affected by) the real alpha property. This value is composited with the other
10186     * alpha value (and the AlphaAnimation value, when that is present) to produce
10187     * a final visual translucency result, which is what is passed into the DisplayList.
10188     *
10189     * @hide
10190     */
10191    public void setTransitionAlpha(float alpha) {
10192        ensureTransformationInfo();
10193        if (mTransformationInfo.mTransitionAlpha != alpha) {
10194            mTransformationInfo.mTransitionAlpha = alpha;
10195            mPrivateFlags &= ~PFLAG_ALPHA_SET;
10196            invalidateViewProperty(true, false);
10197            mRenderNode.setAlpha(getFinalAlpha());
10198        }
10199    }
10200
10201    /**
10202     * Calculates the visual alpha of this view, which is a combination of the actual
10203     * alpha value and the transitionAlpha value (if set).
10204     */
10205    private float getFinalAlpha() {
10206        if (mTransformationInfo != null) {
10207            return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha;
10208        }
10209        return 1;
10210    }
10211
10212    /**
10213     * This property is hidden and intended only for use by the Fade transition, which
10214     * animates it to produce a visual translucency that does not side-effect (or get
10215     * affected by) the real alpha property. This value is composited with the other
10216     * alpha value (and the AlphaAnimation value, when that is present) to produce
10217     * a final visual translucency result, which is what is passed into the DisplayList.
10218     *
10219     * @hide
10220     */
10221    public float getTransitionAlpha() {
10222        return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1;
10223    }
10224
10225    /**
10226     * Top position of this view relative to its parent.
10227     *
10228     * @return The top of this view, in pixels.
10229     */
10230    @ViewDebug.CapturedViewProperty
10231    public final int getTop() {
10232        return mTop;
10233    }
10234
10235    /**
10236     * Sets the top position of this view relative to its parent. This method is meant to be called
10237     * by the layout system and should not generally be called otherwise, because the property
10238     * may be changed at any time by the layout.
10239     *
10240     * @param top The top of this view, in pixels.
10241     */
10242    public final void setTop(int top) {
10243        if (top != mTop) {
10244            final boolean matrixIsIdentity = hasIdentityMatrix();
10245            if (matrixIsIdentity) {
10246                if (mAttachInfo != null) {
10247                    int minTop;
10248                    int yLoc;
10249                    if (top < mTop) {
10250                        minTop = top;
10251                        yLoc = top - mTop;
10252                    } else {
10253                        minTop = mTop;
10254                        yLoc = 0;
10255                    }
10256                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
10257                }
10258            } else {
10259                // Double-invalidation is necessary to capture view's old and new areas
10260                invalidate(true);
10261            }
10262
10263            int width = mRight - mLeft;
10264            int oldHeight = mBottom - mTop;
10265
10266            mTop = top;
10267            mRenderNode.setTop(mTop);
10268
10269            sizeChange(width, mBottom - mTop, width, oldHeight);
10270
10271            if (!matrixIsIdentity) {
10272                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10273                invalidate(true);
10274            }
10275            mBackgroundSizeChanged = true;
10276            invalidateParentIfNeeded();
10277            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10278                // View was rejected last time it was drawn by its parent; this may have changed
10279                invalidateParentIfNeeded();
10280            }
10281        }
10282    }
10283
10284    /**
10285     * Bottom position of this view relative to its parent.
10286     *
10287     * @return The bottom of this view, in pixels.
10288     */
10289    @ViewDebug.CapturedViewProperty
10290    public final int getBottom() {
10291        return mBottom;
10292    }
10293
10294    /**
10295     * True if this view has changed since the last time being drawn.
10296     *
10297     * @return The dirty state of this view.
10298     */
10299    public boolean isDirty() {
10300        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
10301    }
10302
10303    /**
10304     * Sets the bottom position of this view relative to its parent. This method is meant to be
10305     * called by the layout system and should not generally be called otherwise, because the
10306     * property may be changed at any time by the layout.
10307     *
10308     * @param bottom The bottom of this view, in pixels.
10309     */
10310    public final void setBottom(int bottom) {
10311        if (bottom != mBottom) {
10312            final boolean matrixIsIdentity = hasIdentityMatrix();
10313            if (matrixIsIdentity) {
10314                if (mAttachInfo != null) {
10315                    int maxBottom;
10316                    if (bottom < mBottom) {
10317                        maxBottom = mBottom;
10318                    } else {
10319                        maxBottom = bottom;
10320                    }
10321                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
10322                }
10323            } else {
10324                // Double-invalidation is necessary to capture view's old and new areas
10325                invalidate(true);
10326            }
10327
10328            int width = mRight - mLeft;
10329            int oldHeight = mBottom - mTop;
10330
10331            mBottom = bottom;
10332            mRenderNode.setBottom(mBottom);
10333
10334            sizeChange(width, mBottom - mTop, width, oldHeight);
10335
10336            if (!matrixIsIdentity) {
10337                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10338                invalidate(true);
10339            }
10340            mBackgroundSizeChanged = true;
10341            invalidateParentIfNeeded();
10342            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10343                // View was rejected last time it was drawn by its parent; this may have changed
10344                invalidateParentIfNeeded();
10345            }
10346        }
10347    }
10348
10349    /**
10350     * Left position of this view relative to its parent.
10351     *
10352     * @return The left edge of this view, in pixels.
10353     */
10354    @ViewDebug.CapturedViewProperty
10355    public final int getLeft() {
10356        return mLeft;
10357    }
10358
10359    /**
10360     * Sets the left position of this view relative to its parent. This method is meant to be called
10361     * by the layout system and should not generally be called otherwise, because the property
10362     * may be changed at any time by the layout.
10363     *
10364     * @param left The left of this view, in pixels.
10365     */
10366    public final void setLeft(int left) {
10367        if (left != mLeft) {
10368            final boolean matrixIsIdentity = hasIdentityMatrix();
10369            if (matrixIsIdentity) {
10370                if (mAttachInfo != null) {
10371                    int minLeft;
10372                    int xLoc;
10373                    if (left < mLeft) {
10374                        minLeft = left;
10375                        xLoc = left - mLeft;
10376                    } else {
10377                        minLeft = mLeft;
10378                        xLoc = 0;
10379                    }
10380                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
10381                }
10382            } else {
10383                // Double-invalidation is necessary to capture view's old and new areas
10384                invalidate(true);
10385            }
10386
10387            int oldWidth = mRight - mLeft;
10388            int height = mBottom - mTop;
10389
10390            mLeft = left;
10391            mRenderNode.setLeft(left);
10392
10393            sizeChange(mRight - mLeft, height, oldWidth, height);
10394
10395            if (!matrixIsIdentity) {
10396                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10397                invalidate(true);
10398            }
10399            mBackgroundSizeChanged = true;
10400            invalidateParentIfNeeded();
10401            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10402                // View was rejected last time it was drawn by its parent; this may have changed
10403                invalidateParentIfNeeded();
10404            }
10405        }
10406    }
10407
10408    /**
10409     * Right position of this view relative to its parent.
10410     *
10411     * @return The right edge of this view, in pixels.
10412     */
10413    @ViewDebug.CapturedViewProperty
10414    public final int getRight() {
10415        return mRight;
10416    }
10417
10418    /**
10419     * Sets the right position of this view relative to its parent. This method is meant to be called
10420     * by the layout system and should not generally be called otherwise, because the property
10421     * may be changed at any time by the layout.
10422     *
10423     * @param right The right of this view, in pixels.
10424     */
10425    public final void setRight(int right) {
10426        if (right != mRight) {
10427            final boolean matrixIsIdentity = hasIdentityMatrix();
10428            if (matrixIsIdentity) {
10429                if (mAttachInfo != null) {
10430                    int maxRight;
10431                    if (right < mRight) {
10432                        maxRight = mRight;
10433                    } else {
10434                        maxRight = right;
10435                    }
10436                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
10437                }
10438            } else {
10439                // Double-invalidation is necessary to capture view's old and new areas
10440                invalidate(true);
10441            }
10442
10443            int oldWidth = mRight - mLeft;
10444            int height = mBottom - mTop;
10445
10446            mRight = right;
10447            mRenderNode.setRight(mRight);
10448
10449            sizeChange(mRight - mLeft, height, oldWidth, height);
10450
10451            if (!matrixIsIdentity) {
10452                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10453                invalidate(true);
10454            }
10455            mBackgroundSizeChanged = true;
10456            invalidateParentIfNeeded();
10457            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10458                // View was rejected last time it was drawn by its parent; this may have changed
10459                invalidateParentIfNeeded();
10460            }
10461        }
10462    }
10463
10464    /**
10465     * The visual x position of this view, in pixels. This is equivalent to the
10466     * {@link #setTranslationX(float) translationX} property plus the current
10467     * {@link #getLeft() left} property.
10468     *
10469     * @return The visual x position of this view, in pixels.
10470     */
10471    @ViewDebug.ExportedProperty(category = "drawing")
10472    public float getX() {
10473        return mLeft + getTranslationX();
10474    }
10475
10476    /**
10477     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
10478     * {@link #setTranslationX(float) translationX} property to be the difference between
10479     * the x value passed in and the current {@link #getLeft() left} property.
10480     *
10481     * @param x The visual x position of this view, in pixels.
10482     */
10483    public void setX(float x) {
10484        setTranslationX(x - mLeft);
10485    }
10486
10487    /**
10488     * The visual y position of this view, in pixels. This is equivalent to the
10489     * {@link #setTranslationY(float) translationY} property plus the current
10490     * {@link #getTop() top} property.
10491     *
10492     * @return The visual y position of this view, in pixels.
10493     */
10494    @ViewDebug.ExportedProperty(category = "drawing")
10495    public float getY() {
10496        return mTop + getTranslationY();
10497    }
10498
10499    /**
10500     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
10501     * {@link #setTranslationY(float) translationY} property to be the difference between
10502     * the y value passed in and the current {@link #getTop() top} property.
10503     *
10504     * @param y The visual y position of this view, in pixels.
10505     */
10506    public void setY(float y) {
10507        setTranslationY(y - mTop);
10508    }
10509
10510    /**
10511     * The visual z position of this view, in pixels. This is equivalent to the
10512     * {@link #setTranslationZ(float) translationZ} property plus the current
10513     * {@link #getElevation() elevation} property.
10514     *
10515     * @return The visual z position of this view, in pixels.
10516     */
10517    @ViewDebug.ExportedProperty(category = "drawing")
10518    public float getZ() {
10519        return getElevation() + getTranslationZ();
10520    }
10521
10522    /**
10523     * Sets the visual z position of this view, in pixels. This is equivalent to setting the
10524     * {@link #setTranslationZ(float) translationZ} property to be the difference between
10525     * the x value passed in and the current {@link #getElevation() elevation} property.
10526     *
10527     * @param z The visual z position of this view, in pixels.
10528     */
10529    public void setZ(float z) {
10530        setTranslationZ(z - getElevation());
10531    }
10532
10533    /**
10534     * The base elevation of this view relative to its parent, in pixels.
10535     *
10536     * @return The base depth position of the view, in pixels.
10537     */
10538    @ViewDebug.ExportedProperty(category = "drawing")
10539    public float getElevation() {
10540        return mRenderNode.getElevation();
10541    }
10542
10543    /**
10544     * Sets the base elevation of this view, in pixels.
10545     *
10546     * @attr ref android.R.styleable#View_elevation
10547     */
10548    public void setElevation(float elevation) {
10549        if (elevation != getElevation()) {
10550            invalidateViewProperty(true, false);
10551            mRenderNode.setElevation(elevation);
10552            invalidateViewProperty(false, true);
10553
10554            invalidateParentIfNeededAndWasQuickRejected();
10555        }
10556    }
10557
10558    /**
10559     * The horizontal location of this view relative to its {@link #getLeft() left} position.
10560     * This position is post-layout, in addition to wherever the object's
10561     * layout placed it.
10562     *
10563     * @return The horizontal position of this view relative to its left position, in pixels.
10564     */
10565    @ViewDebug.ExportedProperty(category = "drawing")
10566    public float getTranslationX() {
10567        return mRenderNode.getTranslationX();
10568    }
10569
10570    /**
10571     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
10572     * This effectively positions the object post-layout, in addition to wherever the object's
10573     * layout placed it.
10574     *
10575     * @param translationX The horizontal position of this view relative to its left position,
10576     * in pixels.
10577     *
10578     * @attr ref android.R.styleable#View_translationX
10579     */
10580    public void setTranslationX(float translationX) {
10581        if (translationX != getTranslationX()) {
10582            invalidateViewProperty(true, false);
10583            mRenderNode.setTranslationX(translationX);
10584            invalidateViewProperty(false, true);
10585
10586            invalidateParentIfNeededAndWasQuickRejected();
10587            notifySubtreeAccessibilityStateChangedIfNeeded();
10588        }
10589    }
10590
10591    /**
10592     * The vertical location of this view relative to its {@link #getTop() top} position.
10593     * This position is post-layout, in addition to wherever the object's
10594     * layout placed it.
10595     *
10596     * @return The vertical position of this view relative to its top position,
10597     * in pixels.
10598     */
10599    @ViewDebug.ExportedProperty(category = "drawing")
10600    public float getTranslationY() {
10601        return mRenderNode.getTranslationY();
10602    }
10603
10604    /**
10605     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
10606     * This effectively positions the object post-layout, in addition to wherever the object's
10607     * layout placed it.
10608     *
10609     * @param translationY The vertical position of this view relative to its top position,
10610     * in pixels.
10611     *
10612     * @attr ref android.R.styleable#View_translationY
10613     */
10614    public void setTranslationY(float translationY) {
10615        if (translationY != getTranslationY()) {
10616            invalidateViewProperty(true, false);
10617            mRenderNode.setTranslationY(translationY);
10618            invalidateViewProperty(false, true);
10619
10620            invalidateParentIfNeededAndWasQuickRejected();
10621        }
10622    }
10623
10624    /**
10625     * The depth location of this view relative to its {@link #getElevation() elevation}.
10626     *
10627     * @return The depth of this view relative to its elevation.
10628     */
10629    @ViewDebug.ExportedProperty(category = "drawing")
10630    public float getTranslationZ() {
10631        return mRenderNode.getTranslationZ();
10632    }
10633
10634    /**
10635     * Sets the depth location of this view relative to its {@link #getElevation() elevation}.
10636     *
10637     * @attr ref android.R.styleable#View_translationZ
10638     */
10639    public void setTranslationZ(float translationZ) {
10640        if (translationZ != getTranslationZ()) {
10641            invalidateViewProperty(true, false);
10642            mRenderNode.setTranslationZ(translationZ);
10643            invalidateViewProperty(false, true);
10644
10645            invalidateParentIfNeededAndWasQuickRejected();
10646        }
10647    }
10648
10649    /**
10650     * Returns a ValueAnimator which can animate a clearing circle.
10651     * <p>
10652     * The View is prevented from drawing within the circle, so the content
10653     * behind the View shows through.
10654     *
10655     * @param centerX The x coordinate of the center of the animating circle.
10656     * @param centerY The y coordinate of the center of the animating circle.
10657     * @param startRadius The starting radius of the animating circle.
10658     * @param endRadius The ending radius of the animating circle.
10659     *
10660     * @hide
10661     */
10662    public final ValueAnimator createClearCircleAnimator(int centerX,  int centerY,
10663            float startRadius, float endRadius) {
10664        return RevealAnimator.ofRevealCircle(this, centerX, centerY,
10665                startRadius, endRadius, true);
10666    }
10667
10668    /**
10669     * Returns the current StateListAnimator if exists.
10670     *
10671     * @return StateListAnimator or null if it does not exists
10672     * @see    #setStateListAnimator(android.animation.StateListAnimator)
10673     */
10674    public StateListAnimator getStateListAnimator() {
10675        return mStateListAnimator;
10676    }
10677
10678    /**
10679     * Attaches the provided StateListAnimator to this View.
10680     * <p>
10681     * Any previously attached StateListAnimator will be detached.
10682     *
10683     * @param stateListAnimator The StateListAnimator to update the view
10684     * @see {@link android.animation.StateListAnimator}
10685     */
10686    public void setStateListAnimator(StateListAnimator stateListAnimator) {
10687        if (mStateListAnimator == stateListAnimator) {
10688            return;
10689        }
10690        if (mStateListAnimator != null) {
10691            mStateListAnimator.setTarget(null);
10692        }
10693        mStateListAnimator = stateListAnimator;
10694        if (stateListAnimator != null) {
10695            stateListAnimator.setTarget(this);
10696            if (isAttachedToWindow()) {
10697                stateListAnimator.setState(getDrawableState());
10698            }
10699        }
10700    }
10701
10702    /**
10703     * Sets the {@link Outline} of the view, which defines the shape of the shadow it
10704     * casts, and enables outline clipping.
10705     * <p>
10706     * By default, a View queries its Outline from its background drawable, via
10707     * {@link Drawable#getOutline(Outline)}. Manually setting the Outline with this method allows
10708     * this behavior to be overridden.
10709     * <p>
10710     * If the outline is {@link Outline#isEmpty()} or is <code>null</code>,
10711     * shadows will not be cast.
10712     * <p>
10713     * Only outlines that return true from {@link Outline#canClip()} may be used for clipping.
10714     *
10715     * @param outline The new outline of the view.
10716     *
10717     * @see #setClipToOutline(boolean)
10718     * @see #getClipToOutline()
10719     */
10720    public void setOutline(@Nullable Outline outline) {
10721        mPrivateFlags3 |= PFLAG3_OUTLINE_DEFINED;
10722
10723        if (outline == null || outline.isEmpty()) {
10724            if (mOutline != null) {
10725                mOutline.setEmpty();
10726            }
10727        } else {
10728            // always copy the path since caller may reuse
10729            if (mOutline == null) {
10730                mOutline = new Outline();
10731            }
10732            mOutline.set(outline);
10733        }
10734        mRenderNode.setOutline(mOutline);
10735    }
10736
10737    /**
10738     * Returns whether the Outline should be used to clip the contents of the View.
10739     * <p>
10740     * Note that this flag will only be respected if the View's Outline returns true from
10741     * {@link Outline#canClip()}.
10742     *
10743     * @see #setOutline(Outline)
10744     * @see #setClipToOutline(boolean)
10745     */
10746    public final boolean getClipToOutline() {
10747        return mRenderNode.getClipToOutline();
10748    }
10749
10750    /**
10751     * Sets whether the View's Outline should be used to clip the contents of the View.
10752     * <p>
10753     * Note that this flag will only be respected if the View's Outline returns true from
10754     * {@link Outline#canClip()}.
10755     *
10756     * @see #setOutline(Outline)
10757     * @see #getClipToOutline()
10758     */
10759    public void setClipToOutline(boolean clipToOutline) {
10760        damageInParent();
10761        if (getClipToOutline() != clipToOutline) {
10762            mRenderNode.setClipToOutline(clipToOutline);
10763        }
10764    }
10765
10766    private void queryOutlineFromBackgroundIfUndefined() {
10767        if ((mPrivateFlags3 & PFLAG3_OUTLINE_DEFINED) == 0) {
10768            // Outline not currently defined, query from background
10769            if (mOutline == null) {
10770                mOutline = new Outline();
10771            } else {
10772                //invalidate outline, to ensure background calculates it
10773                mOutline.setEmpty();
10774            }
10775            if (mBackground.getOutline(mOutline)) {
10776                if (mOutline.isEmpty()) {
10777                    throw new IllegalStateException("Background drawable failed to build outline");
10778                }
10779                mRenderNode.setOutline(mOutline);
10780            } else {
10781                mRenderNode.setOutline(null);
10782            }
10783            notifySubtreeAccessibilityStateChangedIfNeeded();
10784        }
10785    }
10786
10787    /**
10788     * Private API to be used for reveal animation
10789     *
10790     * @hide
10791     */
10792    public void setRevealClip(boolean shouldClip, boolean inverseClip,
10793            float x, float y, float radius) {
10794        mRenderNode.setRevealClip(shouldClip, inverseClip, x, y, radius);
10795        // TODO: Handle this invalidate in a better way, or purely in native.
10796        invalidate();
10797    }
10798
10799    /**
10800     * Hit rectangle in parent's coordinates
10801     *
10802     * @param outRect The hit rectangle of the view.
10803     */
10804    public void getHitRect(Rect outRect) {
10805        if (hasIdentityMatrix() || mAttachInfo == null) {
10806            outRect.set(mLeft, mTop, mRight, mBottom);
10807        } else {
10808            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
10809            tmpRect.set(0, 0, getWidth(), getHeight());
10810            getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect)
10811            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
10812                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
10813        }
10814    }
10815
10816    /**
10817     * Determines whether the given point, in local coordinates is inside the view.
10818     */
10819    /*package*/ final boolean pointInView(float localX, float localY) {
10820        return localX >= 0 && localX < (mRight - mLeft)
10821                && localY >= 0 && localY < (mBottom - mTop);
10822    }
10823
10824    /**
10825     * Utility method to determine whether the given point, in local coordinates,
10826     * is inside the view, where the area of the view is expanded by the slop factor.
10827     * This method is called while processing touch-move events to determine if the event
10828     * is still within the view.
10829     *
10830     * @hide
10831     */
10832    public boolean pointInView(float localX, float localY, float slop) {
10833        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
10834                localY < ((mBottom - mTop) + slop);
10835    }
10836
10837    /**
10838     * When a view has focus and the user navigates away from it, the next view is searched for
10839     * starting from the rectangle filled in by this method.
10840     *
10841     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
10842     * of the view.  However, if your view maintains some idea of internal selection,
10843     * such as a cursor, or a selected row or column, you should override this method and
10844     * fill in a more specific rectangle.
10845     *
10846     * @param r The rectangle to fill in, in this view's coordinates.
10847     */
10848    public void getFocusedRect(Rect r) {
10849        getDrawingRect(r);
10850    }
10851
10852    /**
10853     * If some part of this view is not clipped by any of its parents, then
10854     * return that area in r in global (root) coordinates. To convert r to local
10855     * coordinates (without taking possible View rotations into account), offset
10856     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
10857     * If the view is completely clipped or translated out, return false.
10858     *
10859     * @param r If true is returned, r holds the global coordinates of the
10860     *        visible portion of this view.
10861     * @param globalOffset If true is returned, globalOffset holds the dx,dy
10862     *        between this view and its root. globalOffet may be null.
10863     * @return true if r is non-empty (i.e. part of the view is visible at the
10864     *         root level.
10865     */
10866    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
10867        int width = mRight - mLeft;
10868        int height = mBottom - mTop;
10869        if (width > 0 && height > 0) {
10870            r.set(0, 0, width, height);
10871            if (globalOffset != null) {
10872                globalOffset.set(-mScrollX, -mScrollY);
10873            }
10874            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
10875        }
10876        return false;
10877    }
10878
10879    public final boolean getGlobalVisibleRect(Rect r) {
10880        return getGlobalVisibleRect(r, null);
10881    }
10882
10883    public final boolean getLocalVisibleRect(Rect r) {
10884        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
10885        if (getGlobalVisibleRect(r, offset)) {
10886            r.offset(-offset.x, -offset.y); // make r local
10887            return true;
10888        }
10889        return false;
10890    }
10891
10892    /**
10893     * Offset this view's vertical location by the specified number of pixels.
10894     *
10895     * @param offset the number of pixels to offset the view by
10896     */
10897    public void offsetTopAndBottom(int offset) {
10898        if (offset != 0) {
10899            final boolean matrixIsIdentity = hasIdentityMatrix();
10900            if (matrixIsIdentity) {
10901                if (isHardwareAccelerated()) {
10902                    invalidateViewProperty(false, false);
10903                } else {
10904                    final ViewParent p = mParent;
10905                    if (p != null && mAttachInfo != null) {
10906                        final Rect r = mAttachInfo.mTmpInvalRect;
10907                        int minTop;
10908                        int maxBottom;
10909                        int yLoc;
10910                        if (offset < 0) {
10911                            minTop = mTop + offset;
10912                            maxBottom = mBottom;
10913                            yLoc = offset;
10914                        } else {
10915                            minTop = mTop;
10916                            maxBottom = mBottom + offset;
10917                            yLoc = 0;
10918                        }
10919                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
10920                        p.invalidateChild(this, r);
10921                    }
10922                }
10923            } else {
10924                invalidateViewProperty(false, false);
10925            }
10926
10927            mTop += offset;
10928            mBottom += offset;
10929            mRenderNode.offsetTopAndBottom(offset);
10930            if (isHardwareAccelerated()) {
10931                invalidateViewProperty(false, false);
10932            } else {
10933                if (!matrixIsIdentity) {
10934                    invalidateViewProperty(false, true);
10935                }
10936                invalidateParentIfNeeded();
10937            }
10938            notifySubtreeAccessibilityStateChangedIfNeeded();
10939        }
10940    }
10941
10942    /**
10943     * Offset this view's horizontal location by the specified amount of pixels.
10944     *
10945     * @param offset the number of pixels to offset the view by
10946     */
10947    public void offsetLeftAndRight(int offset) {
10948        if (offset != 0) {
10949            final boolean matrixIsIdentity = hasIdentityMatrix();
10950            if (matrixIsIdentity) {
10951                if (isHardwareAccelerated()) {
10952                    invalidateViewProperty(false, false);
10953                } else {
10954                    final ViewParent p = mParent;
10955                    if (p != null && mAttachInfo != null) {
10956                        final Rect r = mAttachInfo.mTmpInvalRect;
10957                        int minLeft;
10958                        int maxRight;
10959                        if (offset < 0) {
10960                            minLeft = mLeft + offset;
10961                            maxRight = mRight;
10962                        } else {
10963                            minLeft = mLeft;
10964                            maxRight = mRight + offset;
10965                        }
10966                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
10967                        p.invalidateChild(this, r);
10968                    }
10969                }
10970            } else {
10971                invalidateViewProperty(false, false);
10972            }
10973
10974            mLeft += offset;
10975            mRight += offset;
10976            mRenderNode.offsetLeftAndRight(offset);
10977            if (isHardwareAccelerated()) {
10978                invalidateViewProperty(false, false);
10979            } else {
10980                if (!matrixIsIdentity) {
10981                    invalidateViewProperty(false, true);
10982                }
10983                invalidateParentIfNeeded();
10984            }
10985            notifySubtreeAccessibilityStateChangedIfNeeded();
10986        }
10987    }
10988
10989    /**
10990     * Get the LayoutParams associated with this view. All views should have
10991     * layout parameters. These supply parameters to the <i>parent</i> of this
10992     * view specifying how it should be arranged. There are many subclasses of
10993     * ViewGroup.LayoutParams, and these correspond to the different subclasses
10994     * of ViewGroup that are responsible for arranging their children.
10995     *
10996     * This method may return null if this View is not attached to a parent
10997     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
10998     * was not invoked successfully. When a View is attached to a parent
10999     * ViewGroup, this method must not return null.
11000     *
11001     * @return The LayoutParams associated with this view, or null if no
11002     *         parameters have been set yet
11003     */
11004    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
11005    public ViewGroup.LayoutParams getLayoutParams() {
11006        return mLayoutParams;
11007    }
11008
11009    /**
11010     * Set the layout parameters associated with this view. These supply
11011     * parameters to the <i>parent</i> of this view specifying how it should be
11012     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
11013     * correspond to the different subclasses of ViewGroup that are responsible
11014     * for arranging their children.
11015     *
11016     * @param params The layout parameters for this view, cannot be null
11017     */
11018    public void setLayoutParams(ViewGroup.LayoutParams params) {
11019        if (params == null) {
11020            throw new NullPointerException("Layout parameters cannot be null");
11021        }
11022        mLayoutParams = params;
11023        resolveLayoutParams();
11024        if (mParent instanceof ViewGroup) {
11025            ((ViewGroup) mParent).onSetLayoutParams(this, params);
11026        }
11027        requestLayout();
11028    }
11029
11030    /**
11031     * Resolve the layout parameters depending on the resolved layout direction
11032     *
11033     * @hide
11034     */
11035    public void resolveLayoutParams() {
11036        if (mLayoutParams != null) {
11037            mLayoutParams.resolveLayoutDirection(getLayoutDirection());
11038        }
11039    }
11040
11041    /**
11042     * Set the scrolled position of your view. This will cause a call to
11043     * {@link #onScrollChanged(int, int, int, int)} and the view will be
11044     * invalidated.
11045     * @param x the x position to scroll to
11046     * @param y the y position to scroll to
11047     */
11048    public void scrollTo(int x, int y) {
11049        if (mScrollX != x || mScrollY != y) {
11050            int oldX = mScrollX;
11051            int oldY = mScrollY;
11052            mScrollX = x;
11053            mScrollY = y;
11054            invalidateParentCaches();
11055            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
11056            if (!awakenScrollBars()) {
11057                postInvalidateOnAnimation();
11058            }
11059        }
11060    }
11061
11062    /**
11063     * Move the scrolled position of your view. This will cause a call to
11064     * {@link #onScrollChanged(int, int, int, int)} and the view will be
11065     * invalidated.
11066     * @param x the amount of pixels to scroll by horizontally
11067     * @param y the amount of pixels to scroll by vertically
11068     */
11069    public void scrollBy(int x, int y) {
11070        scrollTo(mScrollX + x, mScrollY + y);
11071    }
11072
11073    /**
11074     * <p>Trigger the scrollbars to draw. When invoked this method starts an
11075     * animation to fade the scrollbars out after a default delay. If a subclass
11076     * provides animated scrolling, the start delay should equal the duration
11077     * of the scrolling animation.</p>
11078     *
11079     * <p>The animation starts only if at least one of the scrollbars is
11080     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
11081     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11082     * this method returns true, and false otherwise. If the animation is
11083     * started, this method calls {@link #invalidate()}; in that case the
11084     * caller should not call {@link #invalidate()}.</p>
11085     *
11086     * <p>This method should be invoked every time a subclass directly updates
11087     * the scroll parameters.</p>
11088     *
11089     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
11090     * and {@link #scrollTo(int, int)}.</p>
11091     *
11092     * @return true if the animation is played, false otherwise
11093     *
11094     * @see #awakenScrollBars(int)
11095     * @see #scrollBy(int, int)
11096     * @see #scrollTo(int, int)
11097     * @see #isHorizontalScrollBarEnabled()
11098     * @see #isVerticalScrollBarEnabled()
11099     * @see #setHorizontalScrollBarEnabled(boolean)
11100     * @see #setVerticalScrollBarEnabled(boolean)
11101     */
11102    protected boolean awakenScrollBars() {
11103        return mScrollCache != null &&
11104                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
11105    }
11106
11107    /**
11108     * Trigger the scrollbars to draw.
11109     * This method differs from awakenScrollBars() only in its default duration.
11110     * initialAwakenScrollBars() will show the scroll bars for longer than
11111     * usual to give the user more of a chance to notice them.
11112     *
11113     * @return true if the animation is played, false otherwise.
11114     */
11115    private boolean initialAwakenScrollBars() {
11116        return mScrollCache != null &&
11117                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
11118    }
11119
11120    /**
11121     * <p>
11122     * Trigger the scrollbars to draw. When invoked this method starts an
11123     * animation to fade the scrollbars out after a fixed delay. If a subclass
11124     * provides animated scrolling, the start delay should equal the duration of
11125     * the scrolling animation.
11126     * </p>
11127     *
11128     * <p>
11129     * The animation starts only if at least one of the scrollbars is enabled,
11130     * as specified by {@link #isHorizontalScrollBarEnabled()} and
11131     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11132     * this method returns true, and false otherwise. If the animation is
11133     * started, this method calls {@link #invalidate()}; in that case the caller
11134     * should not call {@link #invalidate()}.
11135     * </p>
11136     *
11137     * <p>
11138     * This method should be invoked everytime a subclass directly updates the
11139     * scroll parameters.
11140     * </p>
11141     *
11142     * @param startDelay the delay, in milliseconds, after which the animation
11143     *        should start; when the delay is 0, the animation starts
11144     *        immediately
11145     * @return true if the animation is played, false otherwise
11146     *
11147     * @see #scrollBy(int, int)
11148     * @see #scrollTo(int, int)
11149     * @see #isHorizontalScrollBarEnabled()
11150     * @see #isVerticalScrollBarEnabled()
11151     * @see #setHorizontalScrollBarEnabled(boolean)
11152     * @see #setVerticalScrollBarEnabled(boolean)
11153     */
11154    protected boolean awakenScrollBars(int startDelay) {
11155        return awakenScrollBars(startDelay, true);
11156    }
11157
11158    /**
11159     * <p>
11160     * Trigger the scrollbars to draw. When invoked this method starts an
11161     * animation to fade the scrollbars out after a fixed delay. If a subclass
11162     * provides animated scrolling, the start delay should equal the duration of
11163     * the scrolling animation.
11164     * </p>
11165     *
11166     * <p>
11167     * The animation starts only if at least one of the scrollbars is enabled,
11168     * as specified by {@link #isHorizontalScrollBarEnabled()} and
11169     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11170     * this method returns true, and false otherwise. If the animation is
11171     * started, this method calls {@link #invalidate()} if the invalidate parameter
11172     * is set to true; in that case the caller
11173     * should not call {@link #invalidate()}.
11174     * </p>
11175     *
11176     * <p>
11177     * This method should be invoked everytime a subclass directly updates the
11178     * scroll parameters.
11179     * </p>
11180     *
11181     * @param startDelay the delay, in milliseconds, after which the animation
11182     *        should start; when the delay is 0, the animation starts
11183     *        immediately
11184     *
11185     * @param invalidate Wheter this method should call invalidate
11186     *
11187     * @return true if the animation is played, false otherwise
11188     *
11189     * @see #scrollBy(int, int)
11190     * @see #scrollTo(int, int)
11191     * @see #isHorizontalScrollBarEnabled()
11192     * @see #isVerticalScrollBarEnabled()
11193     * @see #setHorizontalScrollBarEnabled(boolean)
11194     * @see #setVerticalScrollBarEnabled(boolean)
11195     */
11196    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
11197        final ScrollabilityCache scrollCache = mScrollCache;
11198
11199        if (scrollCache == null || !scrollCache.fadeScrollBars) {
11200            return false;
11201        }
11202
11203        if (scrollCache.scrollBar == null) {
11204            scrollCache.scrollBar = new ScrollBarDrawable();
11205        }
11206
11207        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
11208
11209            if (invalidate) {
11210                // Invalidate to show the scrollbars
11211                postInvalidateOnAnimation();
11212            }
11213
11214            if (scrollCache.state == ScrollabilityCache.OFF) {
11215                // FIXME: this is copied from WindowManagerService.
11216                // We should get this value from the system when it
11217                // is possible to do so.
11218                final int KEY_REPEAT_FIRST_DELAY = 750;
11219                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
11220            }
11221
11222            // Tell mScrollCache when we should start fading. This may
11223            // extend the fade start time if one was already scheduled
11224            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
11225            scrollCache.fadeStartTime = fadeStartTime;
11226            scrollCache.state = ScrollabilityCache.ON;
11227
11228            // Schedule our fader to run, unscheduling any old ones first
11229            if (mAttachInfo != null) {
11230                mAttachInfo.mHandler.removeCallbacks(scrollCache);
11231                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
11232            }
11233
11234            return true;
11235        }
11236
11237        return false;
11238    }
11239
11240    /**
11241     * Do not invalidate views which are not visible and which are not running an animation. They
11242     * will not get drawn and they should not set dirty flags as if they will be drawn
11243     */
11244    private boolean skipInvalidate() {
11245        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
11246                (!(mParent instanceof ViewGroup) ||
11247                        !((ViewGroup) mParent).isViewTransitioning(this));
11248    }
11249
11250    /**
11251     * Mark the area defined by dirty as needing to be drawn. If the view is
11252     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
11253     * point in the future.
11254     * <p>
11255     * This must be called from a UI thread. To call from a non-UI thread, call
11256     * {@link #postInvalidate()}.
11257     * <p>
11258     * <b>WARNING:</b> In API 19 and below, this method may be destructive to
11259     * {@code dirty}.
11260     *
11261     * @param dirty the rectangle representing the bounds of the dirty region
11262     */
11263    public void invalidate(Rect dirty) {
11264        final int scrollX = mScrollX;
11265        final int scrollY = mScrollY;
11266        invalidateInternal(dirty.left - scrollX, dirty.top - scrollY,
11267                dirty.right - scrollX, dirty.bottom - scrollY, true, false);
11268    }
11269
11270    /**
11271     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The
11272     * coordinates of the dirty rect are relative to the view. If the view is
11273     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
11274     * point in the future.
11275     * <p>
11276     * This must be called from a UI thread. To call from a non-UI thread, call
11277     * {@link #postInvalidate()}.
11278     *
11279     * @param l the left position of the dirty region
11280     * @param t the top position of the dirty region
11281     * @param r the right position of the dirty region
11282     * @param b the bottom position of the dirty region
11283     */
11284    public void invalidate(int l, int t, int r, int b) {
11285        final int scrollX = mScrollX;
11286        final int scrollY = mScrollY;
11287        invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false);
11288    }
11289
11290    /**
11291     * Invalidate the whole view. If the view is visible,
11292     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
11293     * the future.
11294     * <p>
11295     * This must be called from a UI thread. To call from a non-UI thread, call
11296     * {@link #postInvalidate()}.
11297     */
11298    public void invalidate() {
11299        invalidate(true);
11300    }
11301
11302    /**
11303     * This is where the invalidate() work actually happens. A full invalidate()
11304     * causes the drawing cache to be invalidated, but this function can be
11305     * called with invalidateCache set to false to skip that invalidation step
11306     * for cases that do not need it (for example, a component that remains at
11307     * the same dimensions with the same content).
11308     *
11309     * @param invalidateCache Whether the drawing cache for this view should be
11310     *            invalidated as well. This is usually true for a full
11311     *            invalidate, but may be set to false if the View's contents or
11312     *            dimensions have not changed.
11313     */
11314    void invalidate(boolean invalidateCache) {
11315        invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true);
11316    }
11317
11318    void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache,
11319            boolean fullInvalidate) {
11320        if (skipInvalidate()) {
11321            return;
11322        }
11323
11324        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)
11325                || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID)
11326                || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED
11327                || (fullInvalidate && isOpaque() != mLastIsOpaque)) {
11328            if (fullInvalidate) {
11329                mLastIsOpaque = isOpaque();
11330                mPrivateFlags &= ~PFLAG_DRAWN;
11331            }
11332
11333            mPrivateFlags |= PFLAG_DIRTY;
11334
11335            if (invalidateCache) {
11336                mPrivateFlags |= PFLAG_INVALIDATED;
11337                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
11338            }
11339
11340            // Propagate the damage rectangle to the parent view.
11341            final AttachInfo ai = mAttachInfo;
11342            final ViewParent p = mParent;
11343            if (p != null && ai != null && l < r && t < b) {
11344                final Rect damage = ai.mTmpInvalRect;
11345                damage.set(l, t, r, b);
11346                p.invalidateChild(this, damage);
11347            }
11348
11349            // Damage the entire projection receiver, if necessary.
11350            if (mBackground != null && mBackground.isProjected()) {
11351                final View receiver = getProjectionReceiver();
11352                if (receiver != null) {
11353                    receiver.damageInParent();
11354                }
11355            }
11356
11357            // Damage the entire IsolatedZVolume recieving this view's shadow.
11358            if (isHardwareAccelerated() && getZ() != 0) {
11359                damageShadowReceiver();
11360            }
11361        }
11362    }
11363
11364    /**
11365     * @return this view's projection receiver, or {@code null} if none exists
11366     */
11367    private View getProjectionReceiver() {
11368        ViewParent p = getParent();
11369        while (p != null && p instanceof View) {
11370            final View v = (View) p;
11371            if (v.isProjectionReceiver()) {
11372                return v;
11373            }
11374            p = p.getParent();
11375        }
11376
11377        return null;
11378    }
11379
11380    /**
11381     * @return whether the view is a projection receiver
11382     */
11383    private boolean isProjectionReceiver() {
11384        return mBackground != null;
11385    }
11386
11387    /**
11388     * Damage area of the screen that can be covered by this View's shadow.
11389     *
11390     * This method will guarantee that any changes to shadows cast by a View
11391     * are damaged on the screen for future redraw.
11392     */
11393    private void damageShadowReceiver() {
11394        final AttachInfo ai = mAttachInfo;
11395        if (ai != null) {
11396            ViewParent p = getParent();
11397            if (p != null && p instanceof ViewGroup) {
11398                final ViewGroup vg = (ViewGroup) p;
11399                vg.damageInParent();
11400            }
11401        }
11402    }
11403
11404    /**
11405     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
11406     * set any flags or handle all of the cases handled by the default invalidation methods.
11407     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
11408     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
11409     * walk up the hierarchy, transforming the dirty rect as necessary.
11410     *
11411     * The method also handles normal invalidation logic if display list properties are not
11412     * being used in this view. The invalidateParent and forceRedraw flags are used by that
11413     * backup approach, to handle these cases used in the various property-setting methods.
11414     *
11415     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
11416     * are not being used in this view
11417     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
11418     * list properties are not being used in this view
11419     */
11420    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
11421        if (!isHardwareAccelerated()
11422                || !mRenderNode.isValid()
11423                || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) {
11424            if (invalidateParent) {
11425                invalidateParentCaches();
11426            }
11427            if (forceRedraw) {
11428                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
11429            }
11430            invalidate(false);
11431        } else {
11432            damageInParent();
11433        }
11434        if (isHardwareAccelerated() && invalidateParent && getZ() != 0) {
11435            damageShadowReceiver();
11436        }
11437    }
11438
11439    /**
11440     * Tells the parent view to damage this view's bounds.
11441     *
11442     * @hide
11443     */
11444    protected void damageInParent() {
11445        final AttachInfo ai = mAttachInfo;
11446        final ViewParent p = mParent;
11447        if (p != null && ai != null) {
11448            final Rect r = ai.mTmpInvalRect;
11449            r.set(0, 0, mRight - mLeft, mBottom - mTop);
11450            if (mParent instanceof ViewGroup) {
11451                ((ViewGroup) mParent).damageChild(this, r);
11452            } else {
11453                mParent.invalidateChild(this, r);
11454            }
11455        }
11456    }
11457
11458    /**
11459     * Utility method to transform a given Rect by the current matrix of this view.
11460     */
11461    void transformRect(final Rect rect) {
11462        if (!getMatrix().isIdentity()) {
11463            RectF boundingRect = mAttachInfo.mTmpTransformRect;
11464            boundingRect.set(rect);
11465            getMatrix().mapRect(boundingRect);
11466            rect.set((int) Math.floor(boundingRect.left),
11467                    (int) Math.floor(boundingRect.top),
11468                    (int) Math.ceil(boundingRect.right),
11469                    (int) Math.ceil(boundingRect.bottom));
11470        }
11471    }
11472
11473    /**
11474     * Used to indicate that the parent of this view should clear its caches. This functionality
11475     * is used to force the parent to rebuild its display list (when hardware-accelerated),
11476     * which is necessary when various parent-managed properties of the view change, such as
11477     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
11478     * clears the parent caches and does not causes an invalidate event.
11479     *
11480     * @hide
11481     */
11482    protected void invalidateParentCaches() {
11483        if (mParent instanceof View) {
11484            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
11485        }
11486    }
11487
11488    /**
11489     * Used to indicate that the parent of this view should be invalidated. This functionality
11490     * is used to force the parent to rebuild its display list (when hardware-accelerated),
11491     * which is necessary when various parent-managed properties of the view change, such as
11492     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
11493     * an invalidation event to the parent.
11494     *
11495     * @hide
11496     */
11497    protected void invalidateParentIfNeeded() {
11498        if (isHardwareAccelerated() && mParent instanceof View) {
11499            ((View) mParent).invalidate(true);
11500        }
11501    }
11502
11503    /**
11504     * @hide
11505     */
11506    protected void invalidateParentIfNeededAndWasQuickRejected() {
11507        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) {
11508            // View was rejected last time it was drawn by its parent; this may have changed
11509            invalidateParentIfNeeded();
11510        }
11511    }
11512
11513    /**
11514     * Indicates whether this View is opaque. An opaque View guarantees that it will
11515     * draw all the pixels overlapping its bounds using a fully opaque color.
11516     *
11517     * Subclasses of View should override this method whenever possible to indicate
11518     * whether an instance is opaque. Opaque Views are treated in a special way by
11519     * the View hierarchy, possibly allowing it to perform optimizations during
11520     * invalidate/draw passes.
11521     *
11522     * @return True if this View is guaranteed to be fully opaque, false otherwise.
11523     */
11524    @ViewDebug.ExportedProperty(category = "drawing")
11525    public boolean isOpaque() {
11526        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
11527                getFinalAlpha() >= 1.0f;
11528    }
11529
11530    /**
11531     * @hide
11532     */
11533    protected void computeOpaqueFlags() {
11534        // Opaque if:
11535        //   - Has a background
11536        //   - Background is opaque
11537        //   - Doesn't have scrollbars or scrollbars overlay
11538
11539        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
11540            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
11541        } else {
11542            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
11543        }
11544
11545        final int flags = mViewFlags;
11546        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
11547                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY ||
11548                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) {
11549            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
11550        } else {
11551            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
11552        }
11553    }
11554
11555    /**
11556     * @hide
11557     */
11558    protected boolean hasOpaqueScrollbars() {
11559        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
11560    }
11561
11562    /**
11563     * @return A handler associated with the thread running the View. This
11564     * handler can be used to pump events in the UI events queue.
11565     */
11566    public Handler getHandler() {
11567        final AttachInfo attachInfo = mAttachInfo;
11568        if (attachInfo != null) {
11569            return attachInfo.mHandler;
11570        }
11571        return null;
11572    }
11573
11574    /**
11575     * Gets the view root associated with the View.
11576     * @return The view root, or null if none.
11577     * @hide
11578     */
11579    public ViewRootImpl getViewRootImpl() {
11580        if (mAttachInfo != null) {
11581            return mAttachInfo.mViewRootImpl;
11582        }
11583        return null;
11584    }
11585
11586    /**
11587     * @hide
11588     */
11589    public HardwareRenderer getHardwareRenderer() {
11590        return mAttachInfo != null ? mAttachInfo.mHardwareRenderer : null;
11591    }
11592
11593    /**
11594     * <p>Causes the Runnable to be added to the message queue.
11595     * The runnable will be run on the user interface thread.</p>
11596     *
11597     * @param action The Runnable that will be executed.
11598     *
11599     * @return Returns true if the Runnable was successfully placed in to the
11600     *         message queue.  Returns false on failure, usually because the
11601     *         looper processing the message queue is exiting.
11602     *
11603     * @see #postDelayed
11604     * @see #removeCallbacks
11605     */
11606    public boolean post(Runnable action) {
11607        final AttachInfo attachInfo = mAttachInfo;
11608        if (attachInfo != null) {
11609            return attachInfo.mHandler.post(action);
11610        }
11611        // Assume that post will succeed later
11612        ViewRootImpl.getRunQueue().post(action);
11613        return true;
11614    }
11615
11616    /**
11617     * <p>Causes the Runnable to be added to the message queue, to be run
11618     * after the specified amount of time elapses.
11619     * The runnable will be run on the user interface thread.</p>
11620     *
11621     * @param action The Runnable that will be executed.
11622     * @param delayMillis The delay (in milliseconds) until the Runnable
11623     *        will be executed.
11624     *
11625     * @return true if the Runnable was successfully placed in to the
11626     *         message queue.  Returns false on failure, usually because the
11627     *         looper processing the message queue is exiting.  Note that a
11628     *         result of true does not mean the Runnable will be processed --
11629     *         if the looper is quit before the delivery time of the message
11630     *         occurs then the message will be dropped.
11631     *
11632     * @see #post
11633     * @see #removeCallbacks
11634     */
11635    public boolean postDelayed(Runnable action, long delayMillis) {
11636        final AttachInfo attachInfo = mAttachInfo;
11637        if (attachInfo != null) {
11638            return attachInfo.mHandler.postDelayed(action, delayMillis);
11639        }
11640        // Assume that post will succeed later
11641        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
11642        return true;
11643    }
11644
11645    /**
11646     * <p>Causes the Runnable to execute on the next animation time step.
11647     * The runnable will be run on the user interface thread.</p>
11648     *
11649     * @param action The Runnable that will be executed.
11650     *
11651     * @see #postOnAnimationDelayed
11652     * @see #removeCallbacks
11653     */
11654    public void postOnAnimation(Runnable action) {
11655        final AttachInfo attachInfo = mAttachInfo;
11656        if (attachInfo != null) {
11657            attachInfo.mViewRootImpl.mChoreographer.postCallback(
11658                    Choreographer.CALLBACK_ANIMATION, action, null);
11659        } else {
11660            // Assume that post will succeed later
11661            ViewRootImpl.getRunQueue().post(action);
11662        }
11663    }
11664
11665    /**
11666     * <p>Causes the Runnable to execute on the next animation time step,
11667     * after the specified amount of time elapses.
11668     * The runnable will be run on the user interface thread.</p>
11669     *
11670     * @param action The Runnable that will be executed.
11671     * @param delayMillis The delay (in milliseconds) until the Runnable
11672     *        will be executed.
11673     *
11674     * @see #postOnAnimation
11675     * @see #removeCallbacks
11676     */
11677    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
11678        final AttachInfo attachInfo = mAttachInfo;
11679        if (attachInfo != null) {
11680            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
11681                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
11682        } else {
11683            // Assume that post will succeed later
11684            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
11685        }
11686    }
11687
11688    /**
11689     * <p>Removes the specified Runnable from the message queue.</p>
11690     *
11691     * @param action The Runnable to remove from the message handling queue
11692     *
11693     * @return true if this view could ask the Handler to remove the Runnable,
11694     *         false otherwise. When the returned value is true, the Runnable
11695     *         may or may not have been actually removed from the message queue
11696     *         (for instance, if the Runnable was not in the queue already.)
11697     *
11698     * @see #post
11699     * @see #postDelayed
11700     * @see #postOnAnimation
11701     * @see #postOnAnimationDelayed
11702     */
11703    public boolean removeCallbacks(Runnable action) {
11704        if (action != null) {
11705            final AttachInfo attachInfo = mAttachInfo;
11706            if (attachInfo != null) {
11707                attachInfo.mHandler.removeCallbacks(action);
11708                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
11709                        Choreographer.CALLBACK_ANIMATION, action, null);
11710            }
11711            // Assume that post will succeed later
11712            ViewRootImpl.getRunQueue().removeCallbacks(action);
11713        }
11714        return true;
11715    }
11716
11717    /**
11718     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
11719     * Use this to invalidate the View from a non-UI thread.</p>
11720     *
11721     * <p>This method can be invoked from outside of the UI thread
11722     * only when this View is attached to a window.</p>
11723     *
11724     * @see #invalidate()
11725     * @see #postInvalidateDelayed(long)
11726     */
11727    public void postInvalidate() {
11728        postInvalidateDelayed(0);
11729    }
11730
11731    /**
11732     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
11733     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
11734     *
11735     * <p>This method can be invoked from outside of the UI thread
11736     * only when this View is attached to a window.</p>
11737     *
11738     * @param left The left coordinate of the rectangle to invalidate.
11739     * @param top The top coordinate of the rectangle to invalidate.
11740     * @param right The right coordinate of the rectangle to invalidate.
11741     * @param bottom The bottom coordinate of the rectangle to invalidate.
11742     *
11743     * @see #invalidate(int, int, int, int)
11744     * @see #invalidate(Rect)
11745     * @see #postInvalidateDelayed(long, int, int, int, int)
11746     */
11747    public void postInvalidate(int left, int top, int right, int bottom) {
11748        postInvalidateDelayed(0, left, top, right, bottom);
11749    }
11750
11751    /**
11752     * <p>Cause an invalidate to happen on a subsequent cycle through the event
11753     * loop. Waits for the specified amount of time.</p>
11754     *
11755     * <p>This method can be invoked from outside of the UI thread
11756     * only when this View is attached to a window.</p>
11757     *
11758     * @param delayMilliseconds the duration in milliseconds to delay the
11759     *         invalidation by
11760     *
11761     * @see #invalidate()
11762     * @see #postInvalidate()
11763     */
11764    public void postInvalidateDelayed(long delayMilliseconds) {
11765        // We try only with the AttachInfo because there's no point in invalidating
11766        // if we are not attached to our window
11767        final AttachInfo attachInfo = mAttachInfo;
11768        if (attachInfo != null) {
11769            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
11770        }
11771    }
11772
11773    /**
11774     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
11775     * through the event loop. Waits for the specified amount of time.</p>
11776     *
11777     * <p>This method can be invoked from outside of the UI thread
11778     * only when this View is attached to a window.</p>
11779     *
11780     * @param delayMilliseconds the duration in milliseconds to delay the
11781     *         invalidation by
11782     * @param left The left coordinate of the rectangle to invalidate.
11783     * @param top The top coordinate of the rectangle to invalidate.
11784     * @param right The right coordinate of the rectangle to invalidate.
11785     * @param bottom The bottom coordinate of the rectangle to invalidate.
11786     *
11787     * @see #invalidate(int, int, int, int)
11788     * @see #invalidate(Rect)
11789     * @see #postInvalidate(int, int, int, int)
11790     */
11791    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
11792            int right, int bottom) {
11793
11794        // We try only with the AttachInfo because there's no point in invalidating
11795        // if we are not attached to our window
11796        final AttachInfo attachInfo = mAttachInfo;
11797        if (attachInfo != null) {
11798            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
11799            info.target = this;
11800            info.left = left;
11801            info.top = top;
11802            info.right = right;
11803            info.bottom = bottom;
11804
11805            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
11806        }
11807    }
11808
11809    /**
11810     * <p>Cause an invalidate to happen on the next animation time step, typically the
11811     * next display frame.</p>
11812     *
11813     * <p>This method can be invoked from outside of the UI thread
11814     * only when this View is attached to a window.</p>
11815     *
11816     * @see #invalidate()
11817     */
11818    public void postInvalidateOnAnimation() {
11819        // We try only with the AttachInfo because there's no point in invalidating
11820        // if we are not attached to our window
11821        final AttachInfo attachInfo = mAttachInfo;
11822        if (attachInfo != null) {
11823            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
11824        }
11825    }
11826
11827    /**
11828     * <p>Cause an invalidate of the specified area to happen on the next animation
11829     * time step, typically the next display frame.</p>
11830     *
11831     * <p>This method can be invoked from outside of the UI thread
11832     * only when this View is attached to a window.</p>
11833     *
11834     * @param left The left coordinate of the rectangle to invalidate.
11835     * @param top The top coordinate of the rectangle to invalidate.
11836     * @param right The right coordinate of the rectangle to invalidate.
11837     * @param bottom The bottom coordinate of the rectangle to invalidate.
11838     *
11839     * @see #invalidate(int, int, int, int)
11840     * @see #invalidate(Rect)
11841     */
11842    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
11843        // We try only with the AttachInfo because there's no point in invalidating
11844        // if we are not attached to our window
11845        final AttachInfo attachInfo = mAttachInfo;
11846        if (attachInfo != null) {
11847            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
11848            info.target = this;
11849            info.left = left;
11850            info.top = top;
11851            info.right = right;
11852            info.bottom = bottom;
11853
11854            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
11855        }
11856    }
11857
11858    /**
11859     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
11860     * This event is sent at most once every
11861     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
11862     */
11863    private void postSendViewScrolledAccessibilityEventCallback() {
11864        if (mSendViewScrolledAccessibilityEvent == null) {
11865            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
11866        }
11867        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
11868            mSendViewScrolledAccessibilityEvent.mIsPending = true;
11869            postDelayed(mSendViewScrolledAccessibilityEvent,
11870                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
11871        }
11872    }
11873
11874    /**
11875     * Called by a parent to request that a child update its values for mScrollX
11876     * and mScrollY if necessary. This will typically be done if the child is
11877     * animating a scroll using a {@link android.widget.Scroller Scroller}
11878     * object.
11879     */
11880    public void computeScroll() {
11881    }
11882
11883    /**
11884     * <p>Indicate whether the horizontal edges are faded when the view is
11885     * scrolled horizontally.</p>
11886     *
11887     * @return true if the horizontal edges should are faded on scroll, false
11888     *         otherwise
11889     *
11890     * @see #setHorizontalFadingEdgeEnabled(boolean)
11891     *
11892     * @attr ref android.R.styleable#View_requiresFadingEdge
11893     */
11894    public boolean isHorizontalFadingEdgeEnabled() {
11895        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
11896    }
11897
11898    /**
11899     * <p>Define whether the horizontal edges should be faded when this view
11900     * is scrolled horizontally.</p>
11901     *
11902     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
11903     *                                    be faded when the view is scrolled
11904     *                                    horizontally
11905     *
11906     * @see #isHorizontalFadingEdgeEnabled()
11907     *
11908     * @attr ref android.R.styleable#View_requiresFadingEdge
11909     */
11910    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
11911        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
11912            if (horizontalFadingEdgeEnabled) {
11913                initScrollCache();
11914            }
11915
11916            mViewFlags ^= FADING_EDGE_HORIZONTAL;
11917        }
11918    }
11919
11920    /**
11921     * <p>Indicate whether the vertical edges are faded when the view is
11922     * scrolled horizontally.</p>
11923     *
11924     * @return true if the vertical edges should are faded on scroll, false
11925     *         otherwise
11926     *
11927     * @see #setVerticalFadingEdgeEnabled(boolean)
11928     *
11929     * @attr ref android.R.styleable#View_requiresFadingEdge
11930     */
11931    public boolean isVerticalFadingEdgeEnabled() {
11932        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
11933    }
11934
11935    /**
11936     * <p>Define whether the vertical edges should be faded when this view
11937     * is scrolled vertically.</p>
11938     *
11939     * @param verticalFadingEdgeEnabled true if the vertical edges should
11940     *                                  be faded when the view is scrolled
11941     *                                  vertically
11942     *
11943     * @see #isVerticalFadingEdgeEnabled()
11944     *
11945     * @attr ref android.R.styleable#View_requiresFadingEdge
11946     */
11947    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
11948        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
11949            if (verticalFadingEdgeEnabled) {
11950                initScrollCache();
11951            }
11952
11953            mViewFlags ^= FADING_EDGE_VERTICAL;
11954        }
11955    }
11956
11957    /**
11958     * Returns the strength, or intensity, of the top faded edge. The strength is
11959     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11960     * returns 0.0 or 1.0 but no value in between.
11961     *
11962     * Subclasses should override this method to provide a smoother fade transition
11963     * when scrolling occurs.
11964     *
11965     * @return the intensity of the top fade as a float between 0.0f and 1.0f
11966     */
11967    protected float getTopFadingEdgeStrength() {
11968        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
11969    }
11970
11971    /**
11972     * Returns the strength, or intensity, of the bottom faded edge. The strength is
11973     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11974     * returns 0.0 or 1.0 but no value in between.
11975     *
11976     * Subclasses should override this method to provide a smoother fade transition
11977     * when scrolling occurs.
11978     *
11979     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
11980     */
11981    protected float getBottomFadingEdgeStrength() {
11982        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
11983                computeVerticalScrollRange() ? 1.0f : 0.0f;
11984    }
11985
11986    /**
11987     * Returns the strength, or intensity, of the left faded edge. The strength is
11988     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11989     * returns 0.0 or 1.0 but no value in between.
11990     *
11991     * Subclasses should override this method to provide a smoother fade transition
11992     * when scrolling occurs.
11993     *
11994     * @return the intensity of the left fade as a float between 0.0f and 1.0f
11995     */
11996    protected float getLeftFadingEdgeStrength() {
11997        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
11998    }
11999
12000    /**
12001     * Returns the strength, or intensity, of the right faded edge. The strength is
12002     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12003     * returns 0.0 or 1.0 but no value in between.
12004     *
12005     * Subclasses should override this method to provide a smoother fade transition
12006     * when scrolling occurs.
12007     *
12008     * @return the intensity of the right fade as a float between 0.0f and 1.0f
12009     */
12010    protected float getRightFadingEdgeStrength() {
12011        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
12012                computeHorizontalScrollRange() ? 1.0f : 0.0f;
12013    }
12014
12015    /**
12016     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
12017     * scrollbar is not drawn by default.</p>
12018     *
12019     * @return true if the horizontal scrollbar should be painted, false
12020     *         otherwise
12021     *
12022     * @see #setHorizontalScrollBarEnabled(boolean)
12023     */
12024    public boolean isHorizontalScrollBarEnabled() {
12025        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
12026    }
12027
12028    /**
12029     * <p>Define whether the horizontal scrollbar should be drawn or not. The
12030     * scrollbar is not drawn by default.</p>
12031     *
12032     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
12033     *                                   be painted
12034     *
12035     * @see #isHorizontalScrollBarEnabled()
12036     */
12037    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
12038        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
12039            mViewFlags ^= SCROLLBARS_HORIZONTAL;
12040            computeOpaqueFlags();
12041            resolvePadding();
12042        }
12043    }
12044
12045    /**
12046     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
12047     * scrollbar is not drawn by default.</p>
12048     *
12049     * @return true if the vertical scrollbar should be painted, false
12050     *         otherwise
12051     *
12052     * @see #setVerticalScrollBarEnabled(boolean)
12053     */
12054    public boolean isVerticalScrollBarEnabled() {
12055        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
12056    }
12057
12058    /**
12059     * <p>Define whether the vertical scrollbar should be drawn or not. The
12060     * scrollbar is not drawn by default.</p>
12061     *
12062     * @param verticalScrollBarEnabled true if the vertical scrollbar should
12063     *                                 be painted
12064     *
12065     * @see #isVerticalScrollBarEnabled()
12066     */
12067    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
12068        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
12069            mViewFlags ^= SCROLLBARS_VERTICAL;
12070            computeOpaqueFlags();
12071            resolvePadding();
12072        }
12073    }
12074
12075    /**
12076     * @hide
12077     */
12078    protected void recomputePadding() {
12079        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
12080    }
12081
12082    /**
12083     * Define whether scrollbars will fade when the view is not scrolling.
12084     *
12085     * @param fadeScrollbars wheter to enable fading
12086     *
12087     * @attr ref android.R.styleable#View_fadeScrollbars
12088     */
12089    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
12090        initScrollCache();
12091        final ScrollabilityCache scrollabilityCache = mScrollCache;
12092        scrollabilityCache.fadeScrollBars = fadeScrollbars;
12093        if (fadeScrollbars) {
12094            scrollabilityCache.state = ScrollabilityCache.OFF;
12095        } else {
12096            scrollabilityCache.state = ScrollabilityCache.ON;
12097        }
12098    }
12099
12100    /**
12101     *
12102     * Returns true if scrollbars will fade when this view is not scrolling
12103     *
12104     * @return true if scrollbar fading is enabled
12105     *
12106     * @attr ref android.R.styleable#View_fadeScrollbars
12107     */
12108    public boolean isScrollbarFadingEnabled() {
12109        return mScrollCache != null && mScrollCache.fadeScrollBars;
12110    }
12111
12112    /**
12113     *
12114     * Returns the delay before scrollbars fade.
12115     *
12116     * @return the delay before scrollbars fade
12117     *
12118     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
12119     */
12120    public int getScrollBarDefaultDelayBeforeFade() {
12121        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
12122                mScrollCache.scrollBarDefaultDelayBeforeFade;
12123    }
12124
12125    /**
12126     * Define the delay before scrollbars fade.
12127     *
12128     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
12129     *
12130     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
12131     */
12132    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
12133        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
12134    }
12135
12136    /**
12137     *
12138     * Returns the scrollbar fade duration.
12139     *
12140     * @return the scrollbar fade duration
12141     *
12142     * @attr ref android.R.styleable#View_scrollbarFadeDuration
12143     */
12144    public int getScrollBarFadeDuration() {
12145        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
12146                mScrollCache.scrollBarFadeDuration;
12147    }
12148
12149    /**
12150     * Define the scrollbar fade duration.
12151     *
12152     * @param scrollBarFadeDuration - the scrollbar fade duration
12153     *
12154     * @attr ref android.R.styleable#View_scrollbarFadeDuration
12155     */
12156    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
12157        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
12158    }
12159
12160    /**
12161     *
12162     * Returns the scrollbar size.
12163     *
12164     * @return the scrollbar size
12165     *
12166     * @attr ref android.R.styleable#View_scrollbarSize
12167     */
12168    public int getScrollBarSize() {
12169        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
12170                mScrollCache.scrollBarSize;
12171    }
12172
12173    /**
12174     * Define the scrollbar size.
12175     *
12176     * @param scrollBarSize - the scrollbar size
12177     *
12178     * @attr ref android.R.styleable#View_scrollbarSize
12179     */
12180    public void setScrollBarSize(int scrollBarSize) {
12181        getScrollCache().scrollBarSize = scrollBarSize;
12182    }
12183
12184    /**
12185     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
12186     * inset. When inset, they add to the padding of the view. And the scrollbars
12187     * can be drawn inside the padding area or on the edge of the view. For example,
12188     * if a view has a background drawable and you want to draw the scrollbars
12189     * inside the padding specified by the drawable, you can use
12190     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
12191     * appear at the edge of the view, ignoring the padding, then you can use
12192     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
12193     * @param style the style of the scrollbars. Should be one of
12194     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
12195     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
12196     * @see #SCROLLBARS_INSIDE_OVERLAY
12197     * @see #SCROLLBARS_INSIDE_INSET
12198     * @see #SCROLLBARS_OUTSIDE_OVERLAY
12199     * @see #SCROLLBARS_OUTSIDE_INSET
12200     *
12201     * @attr ref android.R.styleable#View_scrollbarStyle
12202     */
12203    public void setScrollBarStyle(@ScrollBarStyle int style) {
12204        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
12205            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
12206            computeOpaqueFlags();
12207            resolvePadding();
12208        }
12209    }
12210
12211    /**
12212     * <p>Returns the current scrollbar style.</p>
12213     * @return the current scrollbar style
12214     * @see #SCROLLBARS_INSIDE_OVERLAY
12215     * @see #SCROLLBARS_INSIDE_INSET
12216     * @see #SCROLLBARS_OUTSIDE_OVERLAY
12217     * @see #SCROLLBARS_OUTSIDE_INSET
12218     *
12219     * @attr ref android.R.styleable#View_scrollbarStyle
12220     */
12221    @ViewDebug.ExportedProperty(mapping = {
12222            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
12223            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
12224            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
12225            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
12226    })
12227    @ScrollBarStyle
12228    public int getScrollBarStyle() {
12229        return mViewFlags & SCROLLBARS_STYLE_MASK;
12230    }
12231
12232    /**
12233     * <p>Compute the horizontal range that the horizontal scrollbar
12234     * represents.</p>
12235     *
12236     * <p>The range is expressed in arbitrary units that must be the same as the
12237     * units used by {@link #computeHorizontalScrollExtent()} and
12238     * {@link #computeHorizontalScrollOffset()}.</p>
12239     *
12240     * <p>The default range is the drawing width of this view.</p>
12241     *
12242     * @return the total horizontal range represented by the horizontal
12243     *         scrollbar
12244     *
12245     * @see #computeHorizontalScrollExtent()
12246     * @see #computeHorizontalScrollOffset()
12247     * @see android.widget.ScrollBarDrawable
12248     */
12249    protected int computeHorizontalScrollRange() {
12250        return getWidth();
12251    }
12252
12253    /**
12254     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
12255     * within the horizontal range. This value is used to compute the position
12256     * of the thumb within the scrollbar's track.</p>
12257     *
12258     * <p>The range is expressed in arbitrary units that must be the same as the
12259     * units used by {@link #computeHorizontalScrollRange()} and
12260     * {@link #computeHorizontalScrollExtent()}.</p>
12261     *
12262     * <p>The default offset is the scroll offset of this view.</p>
12263     *
12264     * @return the horizontal offset of the scrollbar's thumb
12265     *
12266     * @see #computeHorizontalScrollRange()
12267     * @see #computeHorizontalScrollExtent()
12268     * @see android.widget.ScrollBarDrawable
12269     */
12270    protected int computeHorizontalScrollOffset() {
12271        return mScrollX;
12272    }
12273
12274    /**
12275     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
12276     * within the horizontal range. This value is used to compute the length
12277     * of the thumb within the scrollbar's track.</p>
12278     *
12279     * <p>The range is expressed in arbitrary units that must be the same as the
12280     * units used by {@link #computeHorizontalScrollRange()} and
12281     * {@link #computeHorizontalScrollOffset()}.</p>
12282     *
12283     * <p>The default extent is the drawing width of this view.</p>
12284     *
12285     * @return the horizontal extent of the scrollbar's thumb
12286     *
12287     * @see #computeHorizontalScrollRange()
12288     * @see #computeHorizontalScrollOffset()
12289     * @see android.widget.ScrollBarDrawable
12290     */
12291    protected int computeHorizontalScrollExtent() {
12292        return getWidth();
12293    }
12294
12295    /**
12296     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
12297     *
12298     * <p>The range is expressed in arbitrary units that must be the same as the
12299     * units used by {@link #computeVerticalScrollExtent()} and
12300     * {@link #computeVerticalScrollOffset()}.</p>
12301     *
12302     * @return the total vertical range represented by the vertical scrollbar
12303     *
12304     * <p>The default range is the drawing height of this view.</p>
12305     *
12306     * @see #computeVerticalScrollExtent()
12307     * @see #computeVerticalScrollOffset()
12308     * @see android.widget.ScrollBarDrawable
12309     */
12310    protected int computeVerticalScrollRange() {
12311        return getHeight();
12312    }
12313
12314    /**
12315     * <p>Compute the vertical offset of the vertical scrollbar's thumb
12316     * within the horizontal range. This value is used to compute the position
12317     * of the thumb within the scrollbar's track.</p>
12318     *
12319     * <p>The range is expressed in arbitrary units that must be the same as the
12320     * units used by {@link #computeVerticalScrollRange()} and
12321     * {@link #computeVerticalScrollExtent()}.</p>
12322     *
12323     * <p>The default offset is the scroll offset of this view.</p>
12324     *
12325     * @return the vertical offset of the scrollbar's thumb
12326     *
12327     * @see #computeVerticalScrollRange()
12328     * @see #computeVerticalScrollExtent()
12329     * @see android.widget.ScrollBarDrawable
12330     */
12331    protected int computeVerticalScrollOffset() {
12332        return mScrollY;
12333    }
12334
12335    /**
12336     * <p>Compute the vertical extent of the vertical scrollbar's thumb
12337     * within the vertical range. This value is used to compute the length
12338     * of the thumb within the scrollbar's track.</p>
12339     *
12340     * <p>The range is expressed in arbitrary units that must be the same as the
12341     * units used by {@link #computeVerticalScrollRange()} and
12342     * {@link #computeVerticalScrollOffset()}.</p>
12343     *
12344     * <p>The default extent is the drawing height of this view.</p>
12345     *
12346     * @return the vertical extent of the scrollbar's thumb
12347     *
12348     * @see #computeVerticalScrollRange()
12349     * @see #computeVerticalScrollOffset()
12350     * @see android.widget.ScrollBarDrawable
12351     */
12352    protected int computeVerticalScrollExtent() {
12353        return getHeight();
12354    }
12355
12356    /**
12357     * Check if this view can be scrolled horizontally in a certain direction.
12358     *
12359     * @param direction Negative to check scrolling left, positive to check scrolling right.
12360     * @return true if this view can be scrolled in the specified direction, false otherwise.
12361     */
12362    public boolean canScrollHorizontally(int direction) {
12363        final int offset = computeHorizontalScrollOffset();
12364        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
12365        if (range == 0) return false;
12366        if (direction < 0) {
12367            return offset > 0;
12368        } else {
12369            return offset < range - 1;
12370        }
12371    }
12372
12373    /**
12374     * Check if this view can be scrolled vertically in a certain direction.
12375     *
12376     * @param direction Negative to check scrolling up, positive to check scrolling down.
12377     * @return true if this view can be scrolled in the specified direction, false otherwise.
12378     */
12379    public boolean canScrollVertically(int direction) {
12380        final int offset = computeVerticalScrollOffset();
12381        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
12382        if (range == 0) return false;
12383        if (direction < 0) {
12384            return offset > 0;
12385        } else {
12386            return offset < range - 1;
12387        }
12388    }
12389
12390    /**
12391     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
12392     * scrollbars are painted only if they have been awakened first.</p>
12393     *
12394     * @param canvas the canvas on which to draw the scrollbars
12395     *
12396     * @see #awakenScrollBars(int)
12397     */
12398    protected final void onDrawScrollBars(Canvas canvas) {
12399        // scrollbars are drawn only when the animation is running
12400        final ScrollabilityCache cache = mScrollCache;
12401        if (cache != null) {
12402
12403            int state = cache.state;
12404
12405            if (state == ScrollabilityCache.OFF) {
12406                return;
12407            }
12408
12409            boolean invalidate = false;
12410
12411            if (state == ScrollabilityCache.FADING) {
12412                // We're fading -- get our fade interpolation
12413                if (cache.interpolatorValues == null) {
12414                    cache.interpolatorValues = new float[1];
12415                }
12416
12417                float[] values = cache.interpolatorValues;
12418
12419                // Stops the animation if we're done
12420                if (cache.scrollBarInterpolator.timeToValues(values) ==
12421                        Interpolator.Result.FREEZE_END) {
12422                    cache.state = ScrollabilityCache.OFF;
12423                } else {
12424                    cache.scrollBar.setAlpha(Math.round(values[0]));
12425                }
12426
12427                // This will make the scroll bars inval themselves after
12428                // drawing. We only want this when we're fading so that
12429                // we prevent excessive redraws
12430                invalidate = true;
12431            } else {
12432                // We're just on -- but we may have been fading before so
12433                // reset alpha
12434                cache.scrollBar.setAlpha(255);
12435            }
12436
12437
12438            final int viewFlags = mViewFlags;
12439
12440            final boolean drawHorizontalScrollBar =
12441                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
12442            final boolean drawVerticalScrollBar =
12443                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
12444                && !isVerticalScrollBarHidden();
12445
12446            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
12447                final int width = mRight - mLeft;
12448                final int height = mBottom - mTop;
12449
12450                final ScrollBarDrawable scrollBar = cache.scrollBar;
12451
12452                final int scrollX = mScrollX;
12453                final int scrollY = mScrollY;
12454                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
12455
12456                int left;
12457                int top;
12458                int right;
12459                int bottom;
12460
12461                if (drawHorizontalScrollBar) {
12462                    int size = scrollBar.getSize(false);
12463                    if (size <= 0) {
12464                        size = cache.scrollBarSize;
12465                    }
12466
12467                    scrollBar.setParameters(computeHorizontalScrollRange(),
12468                                            computeHorizontalScrollOffset(),
12469                                            computeHorizontalScrollExtent(), false);
12470                    final int verticalScrollBarGap = drawVerticalScrollBar ?
12471                            getVerticalScrollbarWidth() : 0;
12472                    top = scrollY + height - size - (mUserPaddingBottom & inside);
12473                    left = scrollX + (mPaddingLeft & inside);
12474                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
12475                    bottom = top + size;
12476                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
12477                    if (invalidate) {
12478                        invalidate(left, top, right, bottom);
12479                    }
12480                }
12481
12482                if (drawVerticalScrollBar) {
12483                    int size = scrollBar.getSize(true);
12484                    if (size <= 0) {
12485                        size = cache.scrollBarSize;
12486                    }
12487
12488                    scrollBar.setParameters(computeVerticalScrollRange(),
12489                                            computeVerticalScrollOffset(),
12490                                            computeVerticalScrollExtent(), true);
12491                    int verticalScrollbarPosition = mVerticalScrollbarPosition;
12492                    if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
12493                        verticalScrollbarPosition = isLayoutRtl() ?
12494                                SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
12495                    }
12496                    switch (verticalScrollbarPosition) {
12497                        default:
12498                        case SCROLLBAR_POSITION_RIGHT:
12499                            left = scrollX + width - size - (mUserPaddingRight & inside);
12500                            break;
12501                        case SCROLLBAR_POSITION_LEFT:
12502                            left = scrollX + (mUserPaddingLeft & inside);
12503                            break;
12504                    }
12505                    top = scrollY + (mPaddingTop & inside);
12506                    right = left + size;
12507                    bottom = scrollY + height - (mUserPaddingBottom & inside);
12508                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
12509                    if (invalidate) {
12510                        invalidate(left, top, right, bottom);
12511                    }
12512                }
12513            }
12514        }
12515    }
12516
12517    /**
12518     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
12519     * FastScroller is visible.
12520     * @return whether to temporarily hide the vertical scrollbar
12521     * @hide
12522     */
12523    protected boolean isVerticalScrollBarHidden() {
12524        return false;
12525    }
12526
12527    /**
12528     * <p>Draw the horizontal scrollbar if
12529     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
12530     *
12531     * @param canvas the canvas on which to draw the scrollbar
12532     * @param scrollBar the scrollbar's drawable
12533     *
12534     * @see #isHorizontalScrollBarEnabled()
12535     * @see #computeHorizontalScrollRange()
12536     * @see #computeHorizontalScrollExtent()
12537     * @see #computeHorizontalScrollOffset()
12538     * @see android.widget.ScrollBarDrawable
12539     * @hide
12540     */
12541    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
12542            int l, int t, int r, int b) {
12543        scrollBar.setBounds(l, t, r, b);
12544        scrollBar.draw(canvas);
12545    }
12546
12547    /**
12548     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
12549     * returns true.</p>
12550     *
12551     * @param canvas the canvas on which to draw the scrollbar
12552     * @param scrollBar the scrollbar's drawable
12553     *
12554     * @see #isVerticalScrollBarEnabled()
12555     * @see #computeVerticalScrollRange()
12556     * @see #computeVerticalScrollExtent()
12557     * @see #computeVerticalScrollOffset()
12558     * @see android.widget.ScrollBarDrawable
12559     * @hide
12560     */
12561    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
12562            int l, int t, int r, int b) {
12563        scrollBar.setBounds(l, t, r, b);
12564        scrollBar.draw(canvas);
12565    }
12566
12567    /**
12568     * Implement this to do your drawing.
12569     *
12570     * @param canvas the canvas on which the background will be drawn
12571     */
12572    protected void onDraw(Canvas canvas) {
12573    }
12574
12575    /*
12576     * Caller is responsible for calling requestLayout if necessary.
12577     * (This allows addViewInLayout to not request a new layout.)
12578     */
12579    void assignParent(ViewParent parent) {
12580        if (mParent == null) {
12581            mParent = parent;
12582        } else if (parent == null) {
12583            mParent = null;
12584        } else {
12585            throw new RuntimeException("view " + this + " being added, but"
12586                    + " it already has a parent");
12587        }
12588    }
12589
12590    /**
12591     * This is called when the view is attached to a window.  At this point it
12592     * has a Surface and will start drawing.  Note that this function is
12593     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
12594     * however it may be called any time before the first onDraw -- including
12595     * before or after {@link #onMeasure(int, int)}.
12596     *
12597     * @see #onDetachedFromWindow()
12598     */
12599    protected void onAttachedToWindow() {
12600        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
12601            mParent.requestTransparentRegion(this);
12602        }
12603
12604        if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
12605            initialAwakenScrollBars();
12606            mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
12607        }
12608
12609        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
12610
12611        jumpDrawablesToCurrentState();
12612
12613        resetSubtreeAccessibilityStateChanged();
12614
12615        if (isFocused()) {
12616            InputMethodManager imm = InputMethodManager.peekInstance();
12617            imm.focusIn(this);
12618        }
12619    }
12620
12621    /**
12622     * Resolve all RTL related properties.
12623     *
12624     * @return true if resolution of RTL properties has been done
12625     *
12626     * @hide
12627     */
12628    public boolean resolveRtlPropertiesIfNeeded() {
12629        if (!needRtlPropertiesResolution()) return false;
12630
12631        // Order is important here: LayoutDirection MUST be resolved first
12632        if (!isLayoutDirectionResolved()) {
12633            resolveLayoutDirection();
12634            resolveLayoutParams();
12635        }
12636        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
12637        if (!isTextDirectionResolved()) {
12638            resolveTextDirection();
12639        }
12640        if (!isTextAlignmentResolved()) {
12641            resolveTextAlignment();
12642        }
12643        // Should resolve Drawables before Padding because we need the layout direction of the
12644        // Drawable to correctly resolve Padding.
12645        if (!isDrawablesResolved()) {
12646            resolveDrawables();
12647        }
12648        if (!isPaddingResolved()) {
12649            resolvePadding();
12650        }
12651        onRtlPropertiesChanged(getLayoutDirection());
12652        return true;
12653    }
12654
12655    /**
12656     * Reset resolution of all RTL related properties.
12657     *
12658     * @hide
12659     */
12660    public void resetRtlProperties() {
12661        resetResolvedLayoutDirection();
12662        resetResolvedTextDirection();
12663        resetResolvedTextAlignment();
12664        resetResolvedPadding();
12665        resetResolvedDrawables();
12666    }
12667
12668    /**
12669     * @see #onScreenStateChanged(int)
12670     */
12671    void dispatchScreenStateChanged(int screenState) {
12672        onScreenStateChanged(screenState);
12673    }
12674
12675    /**
12676     * This method is called whenever the state of the screen this view is
12677     * attached to changes. A state change will usually occurs when the screen
12678     * turns on or off (whether it happens automatically or the user does it
12679     * manually.)
12680     *
12681     * @param screenState The new state of the screen. Can be either
12682     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
12683     */
12684    public void onScreenStateChanged(int screenState) {
12685    }
12686
12687    /**
12688     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
12689     */
12690    private boolean hasRtlSupport() {
12691        return mContext.getApplicationInfo().hasRtlSupport();
12692    }
12693
12694    /**
12695     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
12696     * RTL not supported)
12697     */
12698    private boolean isRtlCompatibilityMode() {
12699        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
12700        return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport();
12701    }
12702
12703    /**
12704     * @return true if RTL properties need resolution.
12705     *
12706     */
12707    private boolean needRtlPropertiesResolution() {
12708        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
12709    }
12710
12711    /**
12712     * Called when any RTL property (layout direction or text direction or text alignment) has
12713     * been changed.
12714     *
12715     * Subclasses need to override this method to take care of cached information that depends on the
12716     * resolved layout direction, or to inform child views that inherit their layout direction.
12717     *
12718     * The default implementation does nothing.
12719     *
12720     * @param layoutDirection the direction of the layout
12721     *
12722     * @see #LAYOUT_DIRECTION_LTR
12723     * @see #LAYOUT_DIRECTION_RTL
12724     */
12725    public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) {
12726    }
12727
12728    /**
12729     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
12730     * that the parent directionality can and will be resolved before its children.
12731     *
12732     * @return true if resolution has been done, false otherwise.
12733     *
12734     * @hide
12735     */
12736    public boolean resolveLayoutDirection() {
12737        // Clear any previous layout direction resolution
12738        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
12739
12740        if (hasRtlSupport()) {
12741            // Set resolved depending on layout direction
12742            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
12743                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
12744                case LAYOUT_DIRECTION_INHERIT:
12745                    // We cannot resolve yet. LTR is by default and let the resolution happen again
12746                    // later to get the correct resolved value
12747                    if (!canResolveLayoutDirection()) return false;
12748
12749                    // Parent has not yet resolved, LTR is still the default
12750                    try {
12751                        if (!mParent.isLayoutDirectionResolved()) return false;
12752
12753                        if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
12754                            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12755                        }
12756                    } catch (AbstractMethodError e) {
12757                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
12758                                " does not fully implement ViewParent", e);
12759                    }
12760                    break;
12761                case LAYOUT_DIRECTION_RTL:
12762                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12763                    break;
12764                case LAYOUT_DIRECTION_LOCALE:
12765                    if((LAYOUT_DIRECTION_RTL ==
12766                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
12767                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12768                    }
12769                    break;
12770                default:
12771                    // Nothing to do, LTR by default
12772            }
12773        }
12774
12775        // Set to resolved
12776        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
12777        return true;
12778    }
12779
12780    /**
12781     * Check if layout direction resolution can be done.
12782     *
12783     * @return true if layout direction resolution can be done otherwise return false.
12784     */
12785    public boolean canResolveLayoutDirection() {
12786        switch (getRawLayoutDirection()) {
12787            case LAYOUT_DIRECTION_INHERIT:
12788                if (mParent != null) {
12789                    try {
12790                        return mParent.canResolveLayoutDirection();
12791                    } catch (AbstractMethodError e) {
12792                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
12793                                " does not fully implement ViewParent", e);
12794                    }
12795                }
12796                return false;
12797
12798            default:
12799                return true;
12800        }
12801    }
12802
12803    /**
12804     * Reset the resolved layout direction. Layout direction will be resolved during a call to
12805     * {@link #onMeasure(int, int)}.
12806     *
12807     * @hide
12808     */
12809    public void resetResolvedLayoutDirection() {
12810        // Reset the current resolved bits
12811        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
12812    }
12813
12814    /**
12815     * @return true if the layout direction is inherited.
12816     *
12817     * @hide
12818     */
12819    public boolean isLayoutDirectionInherited() {
12820        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
12821    }
12822
12823    /**
12824     * @return true if layout direction has been resolved.
12825     */
12826    public boolean isLayoutDirectionResolved() {
12827        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
12828    }
12829
12830    /**
12831     * Return if padding has been resolved
12832     *
12833     * @hide
12834     */
12835    boolean isPaddingResolved() {
12836        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
12837    }
12838
12839    /**
12840     * Resolves padding depending on layout direction, if applicable, and
12841     * recomputes internal padding values to adjust for scroll bars.
12842     *
12843     * @hide
12844     */
12845    public void resolvePadding() {
12846        final int resolvedLayoutDirection = getLayoutDirection();
12847
12848        if (!isRtlCompatibilityMode()) {
12849            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
12850            // If start / end padding are defined, they will be resolved (hence overriding) to
12851            // left / right or right / left depending on the resolved layout direction.
12852            // If start / end padding are not defined, use the left / right ones.
12853            if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) {
12854                Rect padding = sThreadLocal.get();
12855                if (padding == null) {
12856                    padding = new Rect();
12857                    sThreadLocal.set(padding);
12858                }
12859                mBackground.getPadding(padding);
12860                if (!mLeftPaddingDefined) {
12861                    mUserPaddingLeftInitial = padding.left;
12862                }
12863                if (!mRightPaddingDefined) {
12864                    mUserPaddingRightInitial = padding.right;
12865                }
12866            }
12867            switch (resolvedLayoutDirection) {
12868                case LAYOUT_DIRECTION_RTL:
12869                    if (mUserPaddingStart != UNDEFINED_PADDING) {
12870                        mUserPaddingRight = mUserPaddingStart;
12871                    } else {
12872                        mUserPaddingRight = mUserPaddingRightInitial;
12873                    }
12874                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
12875                        mUserPaddingLeft = mUserPaddingEnd;
12876                    } else {
12877                        mUserPaddingLeft = mUserPaddingLeftInitial;
12878                    }
12879                    break;
12880                case LAYOUT_DIRECTION_LTR:
12881                default:
12882                    if (mUserPaddingStart != UNDEFINED_PADDING) {
12883                        mUserPaddingLeft = mUserPaddingStart;
12884                    } else {
12885                        mUserPaddingLeft = mUserPaddingLeftInitial;
12886                    }
12887                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
12888                        mUserPaddingRight = mUserPaddingEnd;
12889                    } else {
12890                        mUserPaddingRight = mUserPaddingRightInitial;
12891                    }
12892            }
12893
12894            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
12895        }
12896
12897        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
12898        onRtlPropertiesChanged(resolvedLayoutDirection);
12899
12900        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
12901    }
12902
12903    /**
12904     * Reset the resolved layout direction.
12905     *
12906     * @hide
12907     */
12908    public void resetResolvedPadding() {
12909        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
12910    }
12911
12912    /**
12913     * This is called when the view is detached from a window.  At this point it
12914     * no longer has a surface for drawing.
12915     *
12916     * @see #onAttachedToWindow()
12917     */
12918    protected void onDetachedFromWindow() {
12919    }
12920
12921    /**
12922     * This is a framework-internal mirror of onDetachedFromWindow() that's called
12923     * after onDetachedFromWindow().
12924     *
12925     * If you override this you *MUST* call super.onDetachedFromWindowInternal()!
12926     * The super method should be called at the end of the overriden method to ensure
12927     * subclasses are destroyed first
12928     *
12929     * @hide
12930     */
12931    protected void onDetachedFromWindowInternal() {
12932        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
12933        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
12934
12935        removeUnsetPressCallback();
12936        removeLongPressCallback();
12937        removePerformClickCallback();
12938        removeSendViewScrolledAccessibilityEventCallback();
12939        stopNestedScroll();
12940
12941        destroyDrawingCache();
12942
12943        cleanupDraw();
12944        mCurrentAnimation = null;
12945    }
12946
12947    private void cleanupDraw() {
12948        resetDisplayList();
12949        if (mAttachInfo != null) {
12950            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
12951        }
12952    }
12953
12954    /**
12955     * This method ensures the hardware renderer is in a valid state
12956     * before executing the specified action.
12957     *
12958     * This method will attempt to set a valid state even if the window
12959     * the renderer is attached to was destroyed.
12960     *
12961     * This method is not guaranteed to work. If the hardware renderer
12962     * does not exist or cannot be put in a valid state, this method
12963     * will not executed the specified action.
12964     *
12965     * The specified action is executed synchronously.
12966     *
12967     * @param action The action to execute after the renderer is in a valid state
12968     *
12969     * @return True if the specified Runnable was executed, false otherwise
12970     *
12971     * @hide
12972     */
12973    public boolean executeHardwareAction(Runnable action) {
12974        //noinspection SimplifiableIfStatement
12975        if (mAttachInfo != null && mAttachInfo.mHardwareRenderer != null) {
12976            return mAttachInfo.mHardwareRenderer.safelyRun(action);
12977        }
12978        return false;
12979    }
12980
12981    void invalidateInheritedLayoutMode(int layoutModeOfRoot) {
12982    }
12983
12984    /**
12985     * @return The number of times this view has been attached to a window
12986     */
12987    protected int getWindowAttachCount() {
12988        return mWindowAttachCount;
12989    }
12990
12991    /**
12992     * Retrieve a unique token identifying the window this view is attached to.
12993     * @return Return the window's token for use in
12994     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
12995     */
12996    public IBinder getWindowToken() {
12997        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
12998    }
12999
13000    /**
13001     * Retrieve the {@link WindowId} for the window this view is
13002     * currently attached to.
13003     */
13004    public WindowId getWindowId() {
13005        if (mAttachInfo == null) {
13006            return null;
13007        }
13008        if (mAttachInfo.mWindowId == null) {
13009            try {
13010                mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId(
13011                        mAttachInfo.mWindowToken);
13012                mAttachInfo.mWindowId = new WindowId(
13013                        mAttachInfo.mIWindowId);
13014            } catch (RemoteException e) {
13015            }
13016        }
13017        return mAttachInfo.mWindowId;
13018    }
13019
13020    /**
13021     * Retrieve a unique token identifying the top-level "real" window of
13022     * the window that this view is attached to.  That is, this is like
13023     * {@link #getWindowToken}, except if the window this view in is a panel
13024     * window (attached to another containing window), then the token of
13025     * the containing window is returned instead.
13026     *
13027     * @return Returns the associated window token, either
13028     * {@link #getWindowToken()} or the containing window's token.
13029     */
13030    public IBinder getApplicationWindowToken() {
13031        AttachInfo ai = mAttachInfo;
13032        if (ai != null) {
13033            IBinder appWindowToken = ai.mPanelParentWindowToken;
13034            if (appWindowToken == null) {
13035                appWindowToken = ai.mWindowToken;
13036            }
13037            return appWindowToken;
13038        }
13039        return null;
13040    }
13041
13042    /**
13043     * Gets the logical display to which the view's window has been attached.
13044     *
13045     * @return The logical display, or null if the view is not currently attached to a window.
13046     */
13047    public Display getDisplay() {
13048        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
13049    }
13050
13051    /**
13052     * Retrieve private session object this view hierarchy is using to
13053     * communicate with the window manager.
13054     * @return the session object to communicate with the window manager
13055     */
13056    /*package*/ IWindowSession getWindowSession() {
13057        return mAttachInfo != null ? mAttachInfo.mSession : null;
13058    }
13059
13060    /**
13061     * @param info the {@link android.view.View.AttachInfo} to associated with
13062     *        this view
13063     */
13064    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
13065        //System.out.println("Attached! " + this);
13066        mAttachInfo = info;
13067        if (mOverlay != null) {
13068            mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
13069        }
13070        mWindowAttachCount++;
13071        // We will need to evaluate the drawable state at least once.
13072        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
13073        if (mFloatingTreeObserver != null) {
13074            info.mTreeObserver.merge(mFloatingTreeObserver);
13075            mFloatingTreeObserver = null;
13076        }
13077        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
13078            mAttachInfo.mScrollContainers.add(this);
13079            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
13080        }
13081        performCollectViewAttributes(mAttachInfo, visibility);
13082        onAttachedToWindow();
13083
13084        ListenerInfo li = mListenerInfo;
13085        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
13086                li != null ? li.mOnAttachStateChangeListeners : null;
13087        if (listeners != null && listeners.size() > 0) {
13088            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
13089            // perform the dispatching. The iterator is a safe guard against listeners that
13090            // could mutate the list by calling the various add/remove methods. This prevents
13091            // the array from being modified while we iterate it.
13092            for (OnAttachStateChangeListener listener : listeners) {
13093                listener.onViewAttachedToWindow(this);
13094            }
13095        }
13096
13097        int vis = info.mWindowVisibility;
13098        if (vis != GONE) {
13099            onWindowVisibilityChanged(vis);
13100        }
13101        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
13102            // If nobody has evaluated the drawable state yet, then do it now.
13103            refreshDrawableState();
13104        }
13105        needGlobalAttributesUpdate(false);
13106    }
13107
13108    void dispatchDetachedFromWindow() {
13109        AttachInfo info = mAttachInfo;
13110        if (info != null) {
13111            int vis = info.mWindowVisibility;
13112            if (vis != GONE) {
13113                onWindowVisibilityChanged(GONE);
13114            }
13115        }
13116
13117        onDetachedFromWindow();
13118        onDetachedFromWindowInternal();
13119
13120        ListenerInfo li = mListenerInfo;
13121        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
13122                li != null ? li.mOnAttachStateChangeListeners : null;
13123        if (listeners != null && listeners.size() > 0) {
13124            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
13125            // perform the dispatching. The iterator is a safe guard against listeners that
13126            // could mutate the list by calling the various add/remove methods. This prevents
13127            // the array from being modified while we iterate it.
13128            for (OnAttachStateChangeListener listener : listeners) {
13129                listener.onViewDetachedFromWindow(this);
13130            }
13131        }
13132
13133        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
13134            mAttachInfo.mScrollContainers.remove(this);
13135            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
13136        }
13137
13138        mAttachInfo = null;
13139        if (mOverlay != null) {
13140            mOverlay.getOverlayView().dispatchDetachedFromWindow();
13141        }
13142    }
13143
13144    /**
13145     * Cancel any deferred high-level input events that were previously posted to the event queue.
13146     *
13147     * <p>Many views post high-level events such as click handlers to the event queue
13148     * to run deferred in order to preserve a desired user experience - clearing visible
13149     * pressed states before executing, etc. This method will abort any events of this nature
13150     * that are currently in flight.</p>
13151     *
13152     * <p>Custom views that generate their own high-level deferred input events should override
13153     * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p>
13154     *
13155     * <p>This will also cancel pending input events for any child views.</p>
13156     *
13157     * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases.
13158     * This will not impact newer events posted after this call that may occur as a result of
13159     * lower-level input events still waiting in the queue. If you are trying to prevent
13160     * double-submitted  events for the duration of some sort of asynchronous transaction
13161     * you should also take other steps to protect against unexpected double inputs e.g. calling
13162     * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when
13163     * the transaction completes, tracking already submitted transaction IDs, etc.</p>
13164     */
13165    public final void cancelPendingInputEvents() {
13166        dispatchCancelPendingInputEvents();
13167    }
13168
13169    /**
13170     * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight.
13171     * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling.
13172     */
13173    void dispatchCancelPendingInputEvents() {
13174        mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER;
13175        onCancelPendingInputEvents();
13176        if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) {
13177            throw new SuperNotCalledException("View " + getClass().getSimpleName() +
13178                    " did not call through to super.onCancelPendingInputEvents()");
13179        }
13180    }
13181
13182    /**
13183     * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or
13184     * a parent view.
13185     *
13186     * <p>This method is responsible for removing any pending high-level input events that were
13187     * posted to the event queue to run later. Custom view classes that post their own deferred
13188     * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or
13189     * {@link android.os.Handler} should override this method, call
13190     * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate.
13191     * </p>
13192     */
13193    public void onCancelPendingInputEvents() {
13194        removePerformClickCallback();
13195        cancelLongPress();
13196        mPrivateFlags3 |= PFLAG3_CALLED_SUPER;
13197    }
13198
13199    /**
13200     * Store this view hierarchy's frozen state into the given container.
13201     *
13202     * @param container The SparseArray in which to save the view's state.
13203     *
13204     * @see #restoreHierarchyState(android.util.SparseArray)
13205     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13206     * @see #onSaveInstanceState()
13207     */
13208    public void saveHierarchyState(SparseArray<Parcelable> container) {
13209        dispatchSaveInstanceState(container);
13210    }
13211
13212    /**
13213     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
13214     * this view and its children. May be overridden to modify how freezing happens to a
13215     * view's children; for example, some views may want to not store state for their children.
13216     *
13217     * @param container The SparseArray in which to save the view's state.
13218     *
13219     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13220     * @see #saveHierarchyState(android.util.SparseArray)
13221     * @see #onSaveInstanceState()
13222     */
13223    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
13224        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
13225            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
13226            Parcelable state = onSaveInstanceState();
13227            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
13228                throw new IllegalStateException(
13229                        "Derived class did not call super.onSaveInstanceState()");
13230            }
13231            if (state != null) {
13232                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
13233                // + ": " + state);
13234                container.put(mID, state);
13235            }
13236        }
13237    }
13238
13239    /**
13240     * Hook allowing a view to generate a representation of its internal state
13241     * that can later be used to create a new instance with that same state.
13242     * This state should only contain information that is not persistent or can
13243     * not be reconstructed later. For example, you will never store your
13244     * current position on screen because that will be computed again when a
13245     * new instance of the view is placed in its view hierarchy.
13246     * <p>
13247     * Some examples of things you may store here: the current cursor position
13248     * in a text view (but usually not the text itself since that is stored in a
13249     * content provider or other persistent storage), the currently selected
13250     * item in a list view.
13251     *
13252     * @return Returns a Parcelable object containing the view's current dynamic
13253     *         state, or null if there is nothing interesting to save. The
13254     *         default implementation returns null.
13255     * @see #onRestoreInstanceState(android.os.Parcelable)
13256     * @see #saveHierarchyState(android.util.SparseArray)
13257     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13258     * @see #setSaveEnabled(boolean)
13259     */
13260    protected Parcelable onSaveInstanceState() {
13261        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
13262        return BaseSavedState.EMPTY_STATE;
13263    }
13264
13265    /**
13266     * Restore this view hierarchy's frozen state from the given container.
13267     *
13268     * @param container The SparseArray which holds previously frozen states.
13269     *
13270     * @see #saveHierarchyState(android.util.SparseArray)
13271     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13272     * @see #onRestoreInstanceState(android.os.Parcelable)
13273     */
13274    public void restoreHierarchyState(SparseArray<Parcelable> container) {
13275        dispatchRestoreInstanceState(container);
13276    }
13277
13278    /**
13279     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
13280     * state for this view and its children. May be overridden to modify how restoring
13281     * happens to a view's children; for example, some views may want to not store state
13282     * for their children.
13283     *
13284     * @param container The SparseArray which holds previously saved state.
13285     *
13286     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13287     * @see #restoreHierarchyState(android.util.SparseArray)
13288     * @see #onRestoreInstanceState(android.os.Parcelable)
13289     */
13290    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
13291        if (mID != NO_ID) {
13292            Parcelable state = container.get(mID);
13293            if (state != null) {
13294                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
13295                // + ": " + state);
13296                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
13297                onRestoreInstanceState(state);
13298                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
13299                    throw new IllegalStateException(
13300                            "Derived class did not call super.onRestoreInstanceState()");
13301                }
13302            }
13303        }
13304    }
13305
13306    /**
13307     * Hook allowing a view to re-apply a representation of its internal state that had previously
13308     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
13309     * null state.
13310     *
13311     * @param state The frozen state that had previously been returned by
13312     *        {@link #onSaveInstanceState}.
13313     *
13314     * @see #onSaveInstanceState()
13315     * @see #restoreHierarchyState(android.util.SparseArray)
13316     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13317     */
13318    protected void onRestoreInstanceState(Parcelable state) {
13319        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
13320        if (state != BaseSavedState.EMPTY_STATE && state != null) {
13321            throw new IllegalArgumentException("Wrong state class, expecting View State but "
13322                    + "received " + state.getClass().toString() + " instead. This usually happens "
13323                    + "when two views of different type have the same id in the same hierarchy. "
13324                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
13325                    + "other views do not use the same id.");
13326        }
13327    }
13328
13329    /**
13330     * <p>Return the time at which the drawing of the view hierarchy started.</p>
13331     *
13332     * @return the drawing start time in milliseconds
13333     */
13334    public long getDrawingTime() {
13335        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
13336    }
13337
13338    /**
13339     * <p>Enables or disables the duplication of the parent's state into this view. When
13340     * duplication is enabled, this view gets its drawable state from its parent rather
13341     * than from its own internal properties.</p>
13342     *
13343     * <p>Note: in the current implementation, setting this property to true after the
13344     * view was added to a ViewGroup might have no effect at all. This property should
13345     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
13346     *
13347     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
13348     * property is enabled, an exception will be thrown.</p>
13349     *
13350     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
13351     * parent, these states should not be affected by this method.</p>
13352     *
13353     * @param enabled True to enable duplication of the parent's drawable state, false
13354     *                to disable it.
13355     *
13356     * @see #getDrawableState()
13357     * @see #isDuplicateParentStateEnabled()
13358     */
13359    public void setDuplicateParentStateEnabled(boolean enabled) {
13360        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
13361    }
13362
13363    /**
13364     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
13365     *
13366     * @return True if this view's drawable state is duplicated from the parent,
13367     *         false otherwise
13368     *
13369     * @see #getDrawableState()
13370     * @see #setDuplicateParentStateEnabled(boolean)
13371     */
13372    public boolean isDuplicateParentStateEnabled() {
13373        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
13374    }
13375
13376    /**
13377     * <p>Specifies the type of layer backing this view. The layer can be
13378     * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13379     * {@link #LAYER_TYPE_HARDWARE}.</p>
13380     *
13381     * <p>A layer is associated with an optional {@link android.graphics.Paint}
13382     * instance that controls how the layer is composed on screen. The following
13383     * properties of the paint are taken into account when composing the layer:</p>
13384     * <ul>
13385     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
13386     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
13387     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
13388     * </ul>
13389     *
13390     * <p>If this view has an alpha value set to < 1.0 by calling
13391     * {@link #setAlpha(float)}, the alpha value of the layer's paint is superceded
13392     * by this view's alpha value.</p>
13393     *
13394     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE},
13395     * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE}
13396     * for more information on when and how to use layers.</p>
13397     *
13398     * @param layerType The type of layer to use with this view, must be one of
13399     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13400     *        {@link #LAYER_TYPE_HARDWARE}
13401     * @param paint The paint used to compose the layer. This argument is optional
13402     *        and can be null. It is ignored when the layer type is
13403     *        {@link #LAYER_TYPE_NONE}
13404     *
13405     * @see #getLayerType()
13406     * @see #LAYER_TYPE_NONE
13407     * @see #LAYER_TYPE_SOFTWARE
13408     * @see #LAYER_TYPE_HARDWARE
13409     * @see #setAlpha(float)
13410     *
13411     * @attr ref android.R.styleable#View_layerType
13412     */
13413    public void setLayerType(int layerType, Paint paint) {
13414        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
13415            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
13416                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
13417        }
13418
13419        boolean typeChanged = mRenderNode.setLayerType(layerType);
13420
13421        if (!typeChanged) {
13422            setLayerPaint(paint);
13423            return;
13424        }
13425
13426        // Destroy any previous software drawing cache if needed
13427        if (mLayerType == LAYER_TYPE_SOFTWARE) {
13428            destroyDrawingCache();
13429            invalidateParentCaches();
13430            invalidate(true);
13431        }
13432
13433        mLayerType = layerType;
13434        final boolean layerDisabled = (mLayerType == LAYER_TYPE_NONE);
13435        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
13436        mRenderNode.setLayerPaint(mLayerPaint);
13437
13438        if (mLayerType == LAYER_TYPE_SOFTWARE) {
13439            // LAYER_TYPE_SOFTWARE is handled by View:draw(), so need to invalidate()
13440            invalidateParentCaches();
13441            invalidate(true);
13442        } else {
13443            invalidateViewProperty(false, false);
13444        }
13445    }
13446
13447    /**
13448     * Updates the {@link Paint} object used with the current layer (used only if the current
13449     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
13450     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
13451     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
13452     * ensure that the view gets redrawn immediately.
13453     *
13454     * <p>A layer is associated with an optional {@link android.graphics.Paint}
13455     * instance that controls how the layer is composed on screen. The following
13456     * properties of the paint are taken into account when composing the layer:</p>
13457     * <ul>
13458     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
13459     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
13460     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
13461     * </ul>
13462     *
13463     * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the
13464     * alpha value of the layer's paint is superceded by this view's alpha value.</p>
13465     *
13466     * @param paint The paint used to compose the layer. This argument is optional
13467     *        and can be null. It is ignored when the layer type is
13468     *        {@link #LAYER_TYPE_NONE}
13469     *
13470     * @see #setLayerType(int, android.graphics.Paint)
13471     */
13472    public void setLayerPaint(Paint paint) {
13473        int layerType = getLayerType();
13474        if (layerType != LAYER_TYPE_NONE) {
13475            mLayerPaint = paint == null ? new Paint() : paint;
13476            if (layerType == LAYER_TYPE_HARDWARE) {
13477                if (mRenderNode.setLayerPaint(mLayerPaint)) {
13478                    invalidateViewProperty(false, false);
13479                }
13480            } else {
13481                invalidate();
13482            }
13483        }
13484    }
13485
13486    /**
13487     * Indicates whether this view has a static layer. A view with layer type
13488     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
13489     * dynamic.
13490     */
13491    boolean hasStaticLayer() {
13492        return true;
13493    }
13494
13495    /**
13496     * Indicates what type of layer is currently associated with this view. By default
13497     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
13498     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
13499     * for more information on the different types of layers.
13500     *
13501     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13502     *         {@link #LAYER_TYPE_HARDWARE}
13503     *
13504     * @see #setLayerType(int, android.graphics.Paint)
13505     * @see #buildLayer()
13506     * @see #LAYER_TYPE_NONE
13507     * @see #LAYER_TYPE_SOFTWARE
13508     * @see #LAYER_TYPE_HARDWARE
13509     */
13510    public int getLayerType() {
13511        return mLayerType;
13512    }
13513
13514    /**
13515     * Forces this view's layer to be created and this view to be rendered
13516     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
13517     * invoking this method will have no effect.
13518     *
13519     * This method can for instance be used to render a view into its layer before
13520     * starting an animation. If this view is complex, rendering into the layer
13521     * before starting the animation will avoid skipping frames.
13522     *
13523     * @throws IllegalStateException If this view is not attached to a window
13524     *
13525     * @see #setLayerType(int, android.graphics.Paint)
13526     */
13527    public void buildLayer() {
13528        if (mLayerType == LAYER_TYPE_NONE) return;
13529
13530        final AttachInfo attachInfo = mAttachInfo;
13531        if (attachInfo == null) {
13532            throw new IllegalStateException("This view must be attached to a window first");
13533        }
13534
13535        if (getWidth() == 0 || getHeight() == 0) {
13536            return;
13537        }
13538
13539        switch (mLayerType) {
13540            case LAYER_TYPE_HARDWARE:
13541                // The only part of a hardware layer we can build in response to
13542                // this call is to ensure the display list is up to date.
13543                // The actual rendering of the display list into the layer must
13544                // be done at playback time
13545                updateDisplayListIfDirty();
13546                break;
13547            case LAYER_TYPE_SOFTWARE:
13548                buildDrawingCache(true);
13549                break;
13550        }
13551    }
13552
13553    /**
13554     * If this View draws with a HardwareLayer, returns it.
13555     * Otherwise returns null
13556     *
13557     * TODO: Only TextureView uses this, can we eliminate it?
13558     */
13559    HardwareLayer getHardwareLayer() {
13560        return null;
13561    }
13562
13563    /**
13564     * Destroys all hardware rendering resources. This method is invoked
13565     * when the system needs to reclaim resources. Upon execution of this
13566     * method, you should free any OpenGL resources created by the view.
13567     *
13568     * Note: you <strong>must</strong> call
13569     * <code>super.destroyHardwareResources()</code> when overriding
13570     * this method.
13571     *
13572     * @hide
13573     */
13574    protected void destroyHardwareResources() {
13575        resetDisplayList();
13576    }
13577
13578    /**
13579     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
13580     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
13581     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
13582     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
13583     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
13584     * null.</p>
13585     *
13586     * <p>Enabling the drawing cache is similar to
13587     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
13588     * acceleration is turned off. When hardware acceleration is turned on, enabling the
13589     * drawing cache has no effect on rendering because the system uses a different mechanism
13590     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
13591     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
13592     * for information on how to enable software and hardware layers.</p>
13593     *
13594     * <p>This API can be used to manually generate
13595     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
13596     * {@link #getDrawingCache()}.</p>
13597     *
13598     * @param enabled true to enable the drawing cache, false otherwise
13599     *
13600     * @see #isDrawingCacheEnabled()
13601     * @see #getDrawingCache()
13602     * @see #buildDrawingCache()
13603     * @see #setLayerType(int, android.graphics.Paint)
13604     */
13605    public void setDrawingCacheEnabled(boolean enabled) {
13606        mCachingFailed = false;
13607        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
13608    }
13609
13610    /**
13611     * <p>Indicates whether the drawing cache is enabled for this view.</p>
13612     *
13613     * @return true if the drawing cache is enabled
13614     *
13615     * @see #setDrawingCacheEnabled(boolean)
13616     * @see #getDrawingCache()
13617     */
13618    @ViewDebug.ExportedProperty(category = "drawing")
13619    public boolean isDrawingCacheEnabled() {
13620        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
13621    }
13622
13623    /**
13624     * Debugging utility which recursively outputs the dirty state of a view and its
13625     * descendants.
13626     *
13627     * @hide
13628     */
13629    @SuppressWarnings({"UnusedDeclaration"})
13630    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
13631        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
13632                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
13633                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
13634                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
13635        if (clear) {
13636            mPrivateFlags &= clearMask;
13637        }
13638        if (this instanceof ViewGroup) {
13639            ViewGroup parent = (ViewGroup) this;
13640            final int count = parent.getChildCount();
13641            for (int i = 0; i < count; i++) {
13642                final View child = parent.getChildAt(i);
13643                child.outputDirtyFlags(indent + "  ", clear, clearMask);
13644            }
13645        }
13646    }
13647
13648    /**
13649     * This method is used by ViewGroup to cause its children to restore or recreate their
13650     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
13651     * to recreate its own display list, which would happen if it went through the normal
13652     * draw/dispatchDraw mechanisms.
13653     *
13654     * @hide
13655     */
13656    protected void dispatchGetDisplayList() {}
13657
13658    /**
13659     * A view that is not attached or hardware accelerated cannot create a display list.
13660     * This method checks these conditions and returns the appropriate result.
13661     *
13662     * @return true if view has the ability to create a display list, false otherwise.
13663     *
13664     * @hide
13665     */
13666    public boolean canHaveDisplayList() {
13667        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
13668    }
13669
13670    private void updateDisplayListIfDirty() {
13671        final RenderNode renderNode = mRenderNode;
13672        if (!canHaveDisplayList()) {
13673            // can't populate RenderNode, don't try
13674            return;
13675        }
13676
13677        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0
13678                || !renderNode.isValid()
13679                || (mRecreateDisplayList)) {
13680            // Don't need to recreate the display list, just need to tell our
13681            // children to restore/recreate theirs
13682            if (renderNode.isValid()
13683                    && !mRecreateDisplayList) {
13684                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13685                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13686                dispatchGetDisplayList();
13687
13688                return; // no work needed
13689            }
13690
13691            // If we got here, we're recreating it. Mark it as such to ensure that
13692            // we copy in child display lists into ours in drawChild()
13693            mRecreateDisplayList = true;
13694
13695            int width = mRight - mLeft;
13696            int height = mBottom - mTop;
13697            int layerType = getLayerType();
13698
13699            final HardwareCanvas canvas = renderNode.start(width, height);
13700
13701            try {
13702                final HardwareLayer layer = getHardwareLayer();
13703                if (layer != null && layer.isValid()) {
13704                    canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
13705                } else if (layerType == LAYER_TYPE_SOFTWARE) {
13706                    buildDrawingCache(true);
13707                    Bitmap cache = getDrawingCache(true);
13708                    if (cache != null) {
13709                        canvas.drawBitmap(cache, 0, 0, mLayerPaint);
13710                    }
13711                } else {
13712                    computeScroll();
13713
13714                    canvas.translate(-mScrollX, -mScrollY);
13715                    mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13716                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13717
13718                    // Fast path for layouts with no backgrounds
13719                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13720                        dispatchDraw(canvas);
13721                        if (mOverlay != null && !mOverlay.isEmpty()) {
13722                            mOverlay.getOverlayView().draw(canvas);
13723                        }
13724                    } else {
13725                        draw(canvas);
13726                    }
13727                }
13728            } finally {
13729                renderNode.end(canvas);
13730                setDisplayListProperties(renderNode);
13731            }
13732        } else {
13733            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13734            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13735        }
13736    }
13737
13738    /**
13739     * Returns a RenderNode with View draw content recorded, which can be
13740     * used to draw this view again without executing its draw method.
13741     *
13742     * @return A RenderNode ready to replay, or null if caching is not enabled.
13743     *
13744     * @hide
13745     */
13746    public RenderNode getDisplayList() {
13747        updateDisplayListIfDirty();
13748        return mRenderNode;
13749    }
13750
13751    private void resetDisplayList() {
13752        if (mRenderNode.isValid()) {
13753            mRenderNode.destroyDisplayListData();
13754        }
13755
13756        if (mBackgroundDisplayList != null && mBackgroundDisplayList.isValid()) {
13757            mBackgroundDisplayList.destroyDisplayListData();
13758        }
13759    }
13760
13761    /**
13762     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
13763     *
13764     * @return A non-scaled bitmap representing this view or null if cache is disabled.
13765     *
13766     * @see #getDrawingCache(boolean)
13767     */
13768    public Bitmap getDrawingCache() {
13769        return getDrawingCache(false);
13770    }
13771
13772    /**
13773     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
13774     * is null when caching is disabled. If caching is enabled and the cache is not ready,
13775     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
13776     * draw from the cache when the cache is enabled. To benefit from the cache, you must
13777     * request the drawing cache by calling this method and draw it on screen if the
13778     * returned bitmap is not null.</p>
13779     *
13780     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
13781     * this method will create a bitmap of the same size as this view. Because this bitmap
13782     * will be drawn scaled by the parent ViewGroup, the result on screen might show
13783     * scaling artifacts. To avoid such artifacts, you should call this method by setting
13784     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
13785     * size than the view. This implies that your application must be able to handle this
13786     * size.</p>
13787     *
13788     * @param autoScale Indicates whether the generated bitmap should be scaled based on
13789     *        the current density of the screen when the application is in compatibility
13790     *        mode.
13791     *
13792     * @return A bitmap representing this view or null if cache is disabled.
13793     *
13794     * @see #setDrawingCacheEnabled(boolean)
13795     * @see #isDrawingCacheEnabled()
13796     * @see #buildDrawingCache(boolean)
13797     * @see #destroyDrawingCache()
13798     */
13799    public Bitmap getDrawingCache(boolean autoScale) {
13800        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
13801            return null;
13802        }
13803        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
13804            buildDrawingCache(autoScale);
13805        }
13806        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
13807    }
13808
13809    /**
13810     * <p>Frees the resources used by the drawing cache. If you call
13811     * {@link #buildDrawingCache()} manually without calling
13812     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
13813     * should cleanup the cache with this method afterwards.</p>
13814     *
13815     * @see #setDrawingCacheEnabled(boolean)
13816     * @see #buildDrawingCache()
13817     * @see #getDrawingCache()
13818     */
13819    public void destroyDrawingCache() {
13820        if (mDrawingCache != null) {
13821            mDrawingCache.recycle();
13822            mDrawingCache = null;
13823        }
13824        if (mUnscaledDrawingCache != null) {
13825            mUnscaledDrawingCache.recycle();
13826            mUnscaledDrawingCache = null;
13827        }
13828    }
13829
13830    /**
13831     * Setting a solid background color for the drawing cache's bitmaps will improve
13832     * performance and memory usage. Note, though that this should only be used if this
13833     * view will always be drawn on top of a solid color.
13834     *
13835     * @param color The background color to use for the drawing cache's bitmap
13836     *
13837     * @see #setDrawingCacheEnabled(boolean)
13838     * @see #buildDrawingCache()
13839     * @see #getDrawingCache()
13840     */
13841    public void setDrawingCacheBackgroundColor(int color) {
13842        if (color != mDrawingCacheBackgroundColor) {
13843            mDrawingCacheBackgroundColor = color;
13844            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
13845        }
13846    }
13847
13848    /**
13849     * @see #setDrawingCacheBackgroundColor(int)
13850     *
13851     * @return The background color to used for the drawing cache's bitmap
13852     */
13853    public int getDrawingCacheBackgroundColor() {
13854        return mDrawingCacheBackgroundColor;
13855    }
13856
13857    /**
13858     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
13859     *
13860     * @see #buildDrawingCache(boolean)
13861     */
13862    public void buildDrawingCache() {
13863        buildDrawingCache(false);
13864    }
13865
13866    /**
13867     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
13868     *
13869     * <p>If you call {@link #buildDrawingCache()} manually without calling
13870     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
13871     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
13872     *
13873     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
13874     * this method will create a bitmap of the same size as this view. Because this bitmap
13875     * will be drawn scaled by the parent ViewGroup, the result on screen might show
13876     * scaling artifacts. To avoid such artifacts, you should call this method by setting
13877     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
13878     * size than the view. This implies that your application must be able to handle this
13879     * size.</p>
13880     *
13881     * <p>You should avoid calling this method when hardware acceleration is enabled. If
13882     * you do not need the drawing cache bitmap, calling this method will increase memory
13883     * usage and cause the view to be rendered in software once, thus negatively impacting
13884     * performance.</p>
13885     *
13886     * @see #getDrawingCache()
13887     * @see #destroyDrawingCache()
13888     */
13889    public void buildDrawingCache(boolean autoScale) {
13890        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
13891                mDrawingCache == null : mUnscaledDrawingCache == null)) {
13892            mCachingFailed = false;
13893
13894            int width = mRight - mLeft;
13895            int height = mBottom - mTop;
13896
13897            final AttachInfo attachInfo = mAttachInfo;
13898            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
13899
13900            if (autoScale && scalingRequired) {
13901                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
13902                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
13903            }
13904
13905            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
13906            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
13907            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
13908
13909            final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
13910            final long drawingCacheSize =
13911                    ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
13912            if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
13913                if (width > 0 && height > 0) {
13914                    Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs "
13915                            + projectedBitmapSize + " bytes, only "
13916                            + drawingCacheSize + " available");
13917                }
13918                destroyDrawingCache();
13919                mCachingFailed = true;
13920                return;
13921            }
13922
13923            boolean clear = true;
13924            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
13925
13926            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
13927                Bitmap.Config quality;
13928                if (!opaque) {
13929                    // Never pick ARGB_4444 because it looks awful
13930                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
13931                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
13932                        case DRAWING_CACHE_QUALITY_AUTO:
13933                        case DRAWING_CACHE_QUALITY_LOW:
13934                        case DRAWING_CACHE_QUALITY_HIGH:
13935                        default:
13936                            quality = Bitmap.Config.ARGB_8888;
13937                            break;
13938                    }
13939                } else {
13940                    // Optimization for translucent windows
13941                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
13942                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
13943                }
13944
13945                // Try to cleanup memory
13946                if (bitmap != null) bitmap.recycle();
13947
13948                try {
13949                    bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
13950                            width, height, quality);
13951                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
13952                    if (autoScale) {
13953                        mDrawingCache = bitmap;
13954                    } else {
13955                        mUnscaledDrawingCache = bitmap;
13956                    }
13957                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
13958                } catch (OutOfMemoryError e) {
13959                    // If there is not enough memory to create the bitmap cache, just
13960                    // ignore the issue as bitmap caches are not required to draw the
13961                    // view hierarchy
13962                    if (autoScale) {
13963                        mDrawingCache = null;
13964                    } else {
13965                        mUnscaledDrawingCache = null;
13966                    }
13967                    mCachingFailed = true;
13968                    return;
13969                }
13970
13971                clear = drawingCacheBackgroundColor != 0;
13972            }
13973
13974            Canvas canvas;
13975            if (attachInfo != null) {
13976                canvas = attachInfo.mCanvas;
13977                if (canvas == null) {
13978                    canvas = new Canvas();
13979                }
13980                canvas.setBitmap(bitmap);
13981                // Temporarily clobber the cached Canvas in case one of our children
13982                // is also using a drawing cache. Without this, the children would
13983                // steal the canvas by attaching their own bitmap to it and bad, bad
13984                // thing would happen (invisible views, corrupted drawings, etc.)
13985                attachInfo.mCanvas = null;
13986            } else {
13987                // This case should hopefully never or seldom happen
13988                canvas = new Canvas(bitmap);
13989            }
13990
13991            if (clear) {
13992                bitmap.eraseColor(drawingCacheBackgroundColor);
13993            }
13994
13995            computeScroll();
13996            final int restoreCount = canvas.save();
13997
13998            if (autoScale && scalingRequired) {
13999                final float scale = attachInfo.mApplicationScale;
14000                canvas.scale(scale, scale);
14001            }
14002
14003            canvas.translate(-mScrollX, -mScrollY);
14004
14005            mPrivateFlags |= PFLAG_DRAWN;
14006            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
14007                    mLayerType != LAYER_TYPE_NONE) {
14008                mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
14009            }
14010
14011            // Fast path for layouts with no backgrounds
14012            if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14013                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14014                dispatchDraw(canvas);
14015                if (mOverlay != null && !mOverlay.isEmpty()) {
14016                    mOverlay.getOverlayView().draw(canvas);
14017                }
14018            } else {
14019                draw(canvas);
14020            }
14021
14022            canvas.restoreToCount(restoreCount);
14023            canvas.setBitmap(null);
14024
14025            if (attachInfo != null) {
14026                // Restore the cached Canvas for our siblings
14027                attachInfo.mCanvas = canvas;
14028            }
14029        }
14030    }
14031
14032    /**
14033     * Create a snapshot of the view into a bitmap.  We should probably make
14034     * some form of this public, but should think about the API.
14035     */
14036    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
14037        int width = mRight - mLeft;
14038        int height = mBottom - mTop;
14039
14040        final AttachInfo attachInfo = mAttachInfo;
14041        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
14042        width = (int) ((width * scale) + 0.5f);
14043        height = (int) ((height * scale) + 0.5f);
14044
14045        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
14046                width > 0 ? width : 1, height > 0 ? height : 1, quality);
14047        if (bitmap == null) {
14048            throw new OutOfMemoryError();
14049        }
14050
14051        Resources resources = getResources();
14052        if (resources != null) {
14053            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
14054        }
14055
14056        Canvas canvas;
14057        if (attachInfo != null) {
14058            canvas = attachInfo.mCanvas;
14059            if (canvas == null) {
14060                canvas = new Canvas();
14061            }
14062            canvas.setBitmap(bitmap);
14063            // Temporarily clobber the cached Canvas in case one of our children
14064            // is also using a drawing cache. Without this, the children would
14065            // steal the canvas by attaching their own bitmap to it and bad, bad
14066            // things would happen (invisible views, corrupted drawings, etc.)
14067            attachInfo.mCanvas = null;
14068        } else {
14069            // This case should hopefully never or seldom happen
14070            canvas = new Canvas(bitmap);
14071        }
14072
14073        if ((backgroundColor & 0xff000000) != 0) {
14074            bitmap.eraseColor(backgroundColor);
14075        }
14076
14077        computeScroll();
14078        final int restoreCount = canvas.save();
14079        canvas.scale(scale, scale);
14080        canvas.translate(-mScrollX, -mScrollY);
14081
14082        // Temporarily remove the dirty mask
14083        int flags = mPrivateFlags;
14084        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14085
14086        // Fast path for layouts with no backgrounds
14087        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14088            dispatchDraw(canvas);
14089            if (mOverlay != null && !mOverlay.isEmpty()) {
14090                mOverlay.getOverlayView().draw(canvas);
14091            }
14092        } else {
14093            draw(canvas);
14094        }
14095
14096        mPrivateFlags = flags;
14097
14098        canvas.restoreToCount(restoreCount);
14099        canvas.setBitmap(null);
14100
14101        if (attachInfo != null) {
14102            // Restore the cached Canvas for our siblings
14103            attachInfo.mCanvas = canvas;
14104        }
14105
14106        return bitmap;
14107    }
14108
14109    /**
14110     * Indicates whether this View is currently in edit mode. A View is usually
14111     * in edit mode when displayed within a developer tool. For instance, if
14112     * this View is being drawn by a visual user interface builder, this method
14113     * should return true.
14114     *
14115     * Subclasses should check the return value of this method to provide
14116     * different behaviors if their normal behavior might interfere with the
14117     * host environment. For instance: the class spawns a thread in its
14118     * constructor, the drawing code relies on device-specific features, etc.
14119     *
14120     * This method is usually checked in the drawing code of custom widgets.
14121     *
14122     * @return True if this View is in edit mode, false otherwise.
14123     */
14124    public boolean isInEditMode() {
14125        return false;
14126    }
14127
14128    /**
14129     * If the View draws content inside its padding and enables fading edges,
14130     * it needs to support padding offsets. Padding offsets are added to the
14131     * fading edges to extend the length of the fade so that it covers pixels
14132     * drawn inside the padding.
14133     *
14134     * Subclasses of this class should override this method if they need
14135     * to draw content inside the padding.
14136     *
14137     * @return True if padding offset must be applied, false otherwise.
14138     *
14139     * @see #getLeftPaddingOffset()
14140     * @see #getRightPaddingOffset()
14141     * @see #getTopPaddingOffset()
14142     * @see #getBottomPaddingOffset()
14143     *
14144     * @since CURRENT
14145     */
14146    protected boolean isPaddingOffsetRequired() {
14147        return false;
14148    }
14149
14150    /**
14151     * Amount by which to extend the left fading region. Called only when
14152     * {@link #isPaddingOffsetRequired()} returns true.
14153     *
14154     * @return The left padding offset in pixels.
14155     *
14156     * @see #isPaddingOffsetRequired()
14157     *
14158     * @since CURRENT
14159     */
14160    protected int getLeftPaddingOffset() {
14161        return 0;
14162    }
14163
14164    /**
14165     * Amount by which to extend the right fading region. Called only when
14166     * {@link #isPaddingOffsetRequired()} returns true.
14167     *
14168     * @return The right padding offset in pixels.
14169     *
14170     * @see #isPaddingOffsetRequired()
14171     *
14172     * @since CURRENT
14173     */
14174    protected int getRightPaddingOffset() {
14175        return 0;
14176    }
14177
14178    /**
14179     * Amount by which to extend the top fading region. Called only when
14180     * {@link #isPaddingOffsetRequired()} returns true.
14181     *
14182     * @return The top padding offset in pixels.
14183     *
14184     * @see #isPaddingOffsetRequired()
14185     *
14186     * @since CURRENT
14187     */
14188    protected int getTopPaddingOffset() {
14189        return 0;
14190    }
14191
14192    /**
14193     * Amount by which to extend the bottom fading region. Called only when
14194     * {@link #isPaddingOffsetRequired()} returns true.
14195     *
14196     * @return The bottom padding offset in pixels.
14197     *
14198     * @see #isPaddingOffsetRequired()
14199     *
14200     * @since CURRENT
14201     */
14202    protected int getBottomPaddingOffset() {
14203        return 0;
14204    }
14205
14206    /**
14207     * @hide
14208     * @param offsetRequired
14209     */
14210    protected int getFadeTop(boolean offsetRequired) {
14211        int top = mPaddingTop;
14212        if (offsetRequired) top += getTopPaddingOffset();
14213        return top;
14214    }
14215
14216    /**
14217     * @hide
14218     * @param offsetRequired
14219     */
14220    protected int getFadeHeight(boolean offsetRequired) {
14221        int padding = mPaddingTop;
14222        if (offsetRequired) padding += getTopPaddingOffset();
14223        return mBottom - mTop - mPaddingBottom - padding;
14224    }
14225
14226    /**
14227     * <p>Indicates whether this view is attached to a hardware accelerated
14228     * window or not.</p>
14229     *
14230     * <p>Even if this method returns true, it does not mean that every call
14231     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
14232     * accelerated {@link android.graphics.Canvas}. For instance, if this view
14233     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
14234     * window is hardware accelerated,
14235     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
14236     * return false, and this method will return true.</p>
14237     *
14238     * @return True if the view is attached to a window and the window is
14239     *         hardware accelerated; false in any other case.
14240     */
14241    public boolean isHardwareAccelerated() {
14242        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
14243    }
14244
14245    /**
14246     * Sets a rectangular area on this view to which the view will be clipped
14247     * when it is drawn. Setting the value to null will remove the clip bounds
14248     * and the view will draw normally, using its full bounds.
14249     *
14250     * @param clipBounds The rectangular area, in the local coordinates of
14251     * this view, to which future drawing operations will be clipped.
14252     */
14253    public void setClipBounds(Rect clipBounds) {
14254        if (clipBounds != null) {
14255            if (clipBounds.equals(mClipBounds)) {
14256                return;
14257            }
14258            if (mClipBounds == null) {
14259                invalidate();
14260                mClipBounds = new Rect(clipBounds);
14261            } else {
14262                invalidate(Math.min(mClipBounds.left, clipBounds.left),
14263                        Math.min(mClipBounds.top, clipBounds.top),
14264                        Math.max(mClipBounds.right, clipBounds.right),
14265                        Math.max(mClipBounds.bottom, clipBounds.bottom));
14266                mClipBounds.set(clipBounds);
14267            }
14268        } else {
14269            if (mClipBounds != null) {
14270                invalidate();
14271                mClipBounds = null;
14272            }
14273        }
14274    }
14275
14276    /**
14277     * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}.
14278     *
14279     * @return A copy of the current clip bounds if clip bounds are set,
14280     * otherwise null.
14281     */
14282    public Rect getClipBounds() {
14283        return (mClipBounds != null) ? new Rect(mClipBounds) : null;
14284    }
14285
14286    /**
14287     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
14288     * case of an active Animation being run on the view.
14289     */
14290    private boolean drawAnimation(ViewGroup parent, long drawingTime,
14291            Animation a, boolean scalingRequired) {
14292        Transformation invalidationTransform;
14293        final int flags = parent.mGroupFlags;
14294        final boolean initialized = a.isInitialized();
14295        if (!initialized) {
14296            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
14297            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
14298            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
14299            onAnimationStart();
14300        }
14301
14302        final Transformation t = parent.getChildTransformation();
14303        boolean more = a.getTransformation(drawingTime, t, 1f);
14304        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
14305            if (parent.mInvalidationTransformation == null) {
14306                parent.mInvalidationTransformation = new Transformation();
14307            }
14308            invalidationTransform = parent.mInvalidationTransformation;
14309            a.getTransformation(drawingTime, invalidationTransform, 1f);
14310        } else {
14311            invalidationTransform = t;
14312        }
14313
14314        if (more) {
14315            if (!a.willChangeBounds()) {
14316                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
14317                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
14318                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
14319                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
14320                    // The child need to draw an animation, potentially offscreen, so
14321                    // make sure we do not cancel invalidate requests
14322                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
14323                    parent.invalidate(mLeft, mTop, mRight, mBottom);
14324                }
14325            } else {
14326                if (parent.mInvalidateRegion == null) {
14327                    parent.mInvalidateRegion = new RectF();
14328                }
14329                final RectF region = parent.mInvalidateRegion;
14330                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
14331                        invalidationTransform);
14332
14333                // The child need to draw an animation, potentially offscreen, so
14334                // make sure we do not cancel invalidate requests
14335                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
14336
14337                final int left = mLeft + (int) region.left;
14338                final int top = mTop + (int) region.top;
14339                parent.invalidate(left, top, left + (int) (region.width() + .5f),
14340                        top + (int) (region.height() + .5f));
14341            }
14342        }
14343        return more;
14344    }
14345
14346    /**
14347     * This method is called by getDisplayList() when a display list is recorded for a View.
14348     * It pushes any properties to the RenderNode that aren't managed by the RenderNode.
14349     */
14350    void setDisplayListProperties(RenderNode renderNode) {
14351        if (renderNode != null) {
14352            renderNode.setHasOverlappingRendering(hasOverlappingRendering());
14353            if (mParent instanceof ViewGroup) {
14354                renderNode.setClipToBounds(
14355                        (((ViewGroup) mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0);
14356            }
14357            float alpha = 1;
14358            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
14359                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
14360                ViewGroup parentVG = (ViewGroup) mParent;
14361                final Transformation t = parentVG.getChildTransformation();
14362                if (parentVG.getChildStaticTransformation(this, t)) {
14363                    final int transformType = t.getTransformationType();
14364                    if (transformType != Transformation.TYPE_IDENTITY) {
14365                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
14366                            alpha = t.getAlpha();
14367                        }
14368                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
14369                            renderNode.setStaticMatrix(t.getMatrix());
14370                        }
14371                    }
14372                }
14373            }
14374            if (mTransformationInfo != null) {
14375                alpha *= getFinalAlpha();
14376                if (alpha < 1) {
14377                    final int multipliedAlpha = (int) (255 * alpha);
14378                    if (onSetAlpha(multipliedAlpha)) {
14379                        alpha = 1;
14380                    }
14381                }
14382                renderNode.setAlpha(alpha);
14383            } else if (alpha < 1) {
14384                renderNode.setAlpha(alpha);
14385            }
14386        }
14387    }
14388
14389    /**
14390     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
14391     * This draw() method is an implementation detail and is not intended to be overridden or
14392     * to be called from anywhere else other than ViewGroup.drawChild().
14393     */
14394    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
14395        boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
14396        boolean more = false;
14397        final boolean childHasIdentityMatrix = hasIdentityMatrix();
14398        final int flags = parent.mGroupFlags;
14399
14400        if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) {
14401            parent.getChildTransformation().clear();
14402            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14403        }
14404
14405        Transformation transformToApply = null;
14406        boolean concatMatrix = false;
14407
14408        boolean scalingRequired = false;
14409        boolean caching;
14410        int layerType = getLayerType();
14411
14412        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
14413        if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 ||
14414                (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) {
14415            caching = true;
14416            // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList
14417            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
14418        } else {
14419            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
14420        }
14421
14422        final Animation a = getAnimation();
14423        if (a != null) {
14424            more = drawAnimation(parent, drawingTime, a, scalingRequired);
14425            concatMatrix = a.willChangeTransformationMatrix();
14426            if (concatMatrix) {
14427                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
14428            }
14429            transformToApply = parent.getChildTransformation();
14430        } else {
14431            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) {
14432                // No longer animating: clear out old animation matrix
14433                mRenderNode.setAnimationMatrix(null);
14434                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
14435            }
14436            if (!useDisplayListProperties &&
14437                    (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
14438                final Transformation t = parent.getChildTransformation();
14439                final boolean hasTransform = parent.getChildStaticTransformation(this, t);
14440                if (hasTransform) {
14441                    final int transformType = t.getTransformationType();
14442                    transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null;
14443                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
14444                }
14445            }
14446        }
14447
14448        concatMatrix |= !childHasIdentityMatrix;
14449
14450        // Sets the flag as early as possible to allow draw() implementations
14451        // to call invalidate() successfully when doing animations
14452        mPrivateFlags |= PFLAG_DRAWN;
14453
14454        if (!concatMatrix &&
14455                (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
14456                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
14457                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
14458                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
14459            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
14460            return more;
14461        }
14462        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
14463
14464        if (hardwareAccelerated) {
14465            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
14466            // retain the flag's value temporarily in the mRecreateDisplayList flag
14467            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED;
14468            mPrivateFlags &= ~PFLAG_INVALIDATED;
14469        }
14470
14471        RenderNode displayList = null;
14472        Bitmap cache = null;
14473        boolean hasDisplayList = false;
14474        if (caching) {
14475            if (!hardwareAccelerated) {
14476                if (layerType != LAYER_TYPE_NONE) {
14477                    layerType = LAYER_TYPE_SOFTWARE;
14478                    buildDrawingCache(true);
14479                }
14480                cache = getDrawingCache(true);
14481            } else {
14482                switch (layerType) {
14483                    case LAYER_TYPE_SOFTWARE:
14484                        if (useDisplayListProperties) {
14485                            hasDisplayList = canHaveDisplayList();
14486                        } else {
14487                            buildDrawingCache(true);
14488                            cache = getDrawingCache(true);
14489                        }
14490                        break;
14491                    case LAYER_TYPE_HARDWARE:
14492                        if (useDisplayListProperties) {
14493                            hasDisplayList = canHaveDisplayList();
14494                        }
14495                        break;
14496                    case LAYER_TYPE_NONE:
14497                        // Delay getting the display list until animation-driven alpha values are
14498                        // set up and possibly passed on to the view
14499                        hasDisplayList = canHaveDisplayList();
14500                        break;
14501                }
14502            }
14503        }
14504        useDisplayListProperties &= hasDisplayList;
14505        if (useDisplayListProperties) {
14506            displayList = getDisplayList();
14507            if (!displayList.isValid()) {
14508                // Uncommon, but possible. If a view is removed from the hierarchy during the call
14509                // to getDisplayList(), the display list will be marked invalid and we should not
14510                // try to use it again.
14511                displayList = null;
14512                hasDisplayList = false;
14513                useDisplayListProperties = false;
14514            }
14515        }
14516
14517        int sx = 0;
14518        int sy = 0;
14519        if (!hasDisplayList) {
14520            computeScroll();
14521            sx = mScrollX;
14522            sy = mScrollY;
14523        }
14524
14525        final boolean hasNoCache = cache == null || hasDisplayList;
14526        final boolean offsetForScroll = cache == null && !hasDisplayList &&
14527                layerType != LAYER_TYPE_HARDWARE;
14528
14529        int restoreTo = -1;
14530        if (!useDisplayListProperties || transformToApply != null) {
14531            restoreTo = canvas.save();
14532        }
14533        if (offsetForScroll) {
14534            canvas.translate(mLeft - sx, mTop - sy);
14535        } else {
14536            if (!useDisplayListProperties) {
14537                canvas.translate(mLeft, mTop);
14538            }
14539            if (scalingRequired) {
14540                if (useDisplayListProperties) {
14541                    // TODO: Might not need this if we put everything inside the DL
14542                    restoreTo = canvas.save();
14543                }
14544                // mAttachInfo cannot be null, otherwise scalingRequired == false
14545                final float scale = 1.0f / mAttachInfo.mApplicationScale;
14546                canvas.scale(scale, scale);
14547            }
14548        }
14549
14550        float alpha = useDisplayListProperties ? 1 : (getAlpha() * getTransitionAlpha());
14551        if (transformToApply != null || alpha < 1 ||  !hasIdentityMatrix() ||
14552                (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
14553            if (transformToApply != null || !childHasIdentityMatrix) {
14554                int transX = 0;
14555                int transY = 0;
14556
14557                if (offsetForScroll) {
14558                    transX = -sx;
14559                    transY = -sy;
14560                }
14561
14562                if (transformToApply != null) {
14563                    if (concatMatrix) {
14564                        if (useDisplayListProperties) {
14565                            displayList.setAnimationMatrix(transformToApply.getMatrix());
14566                        } else {
14567                            // Undo the scroll translation, apply the transformation matrix,
14568                            // then redo the scroll translate to get the correct result.
14569                            canvas.translate(-transX, -transY);
14570                            canvas.concat(transformToApply.getMatrix());
14571                            canvas.translate(transX, transY);
14572                        }
14573                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14574                    }
14575
14576                    float transformAlpha = transformToApply.getAlpha();
14577                    if (transformAlpha < 1) {
14578                        alpha *= transformAlpha;
14579                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14580                    }
14581                }
14582
14583                if (!childHasIdentityMatrix && !useDisplayListProperties) {
14584                    canvas.translate(-transX, -transY);
14585                    canvas.concat(getMatrix());
14586                    canvas.translate(transX, transY);
14587                }
14588            }
14589
14590            // Deal with alpha if it is or used to be <1
14591            if (alpha < 1 ||
14592                    (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
14593                if (alpha < 1) {
14594                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
14595                } else {
14596                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
14597                }
14598                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14599                if (hasNoCache) {
14600                    final int multipliedAlpha = (int) (255 * alpha);
14601                    if (!onSetAlpha(multipliedAlpha)) {
14602                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
14603                        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 ||
14604                                layerType != LAYER_TYPE_NONE) {
14605                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
14606                        }
14607                        if (useDisplayListProperties) {
14608                            displayList.setAlpha(alpha * getAlpha() * getTransitionAlpha());
14609                        } else  if (layerType == LAYER_TYPE_NONE) {
14610                            final int scrollX = hasDisplayList ? 0 : sx;
14611                            final int scrollY = hasDisplayList ? 0 : sy;
14612                            canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft,
14613                                    scrollY + mBottom - mTop, multipliedAlpha, layerFlags);
14614                        }
14615                    } else {
14616                        // Alpha is handled by the child directly, clobber the layer's alpha
14617                        mPrivateFlags |= PFLAG_ALPHA_SET;
14618                    }
14619                }
14620            }
14621        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
14622            onSetAlpha(255);
14623            mPrivateFlags &= ~PFLAG_ALPHA_SET;
14624        }
14625
14626        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN &&
14627                !useDisplayListProperties && cache == null) {
14628            if (offsetForScroll) {
14629                canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
14630            } else {
14631                if (!scalingRequired || cache == null) {
14632                    canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
14633                } else {
14634                    canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
14635                }
14636            }
14637        }
14638
14639        if (!useDisplayListProperties && hasDisplayList) {
14640            displayList = getDisplayList();
14641            if (!displayList.isValid()) {
14642                // Uncommon, but possible. If a view is removed from the hierarchy during the call
14643                // to getDisplayList(), the display list will be marked invalid and we should not
14644                // try to use it again.
14645                displayList = null;
14646                hasDisplayList = false;
14647            }
14648        }
14649
14650        if (hasNoCache) {
14651            boolean layerRendered = false;
14652            if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) {
14653                final HardwareLayer layer = getHardwareLayer();
14654                if (layer != null && layer.isValid()) {
14655                    mLayerPaint.setAlpha((int) (alpha * 255));
14656                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
14657                    layerRendered = true;
14658                } else {
14659                    final int scrollX = hasDisplayList ? 0 : sx;
14660                    final int scrollY = hasDisplayList ? 0 : sy;
14661                    canvas.saveLayer(scrollX, scrollY,
14662                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
14663                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
14664                }
14665            }
14666
14667            if (!layerRendered) {
14668                if (!hasDisplayList) {
14669                    // Fast path for layouts with no backgrounds
14670                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14671                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14672                        dispatchDraw(canvas);
14673                    } else {
14674                        draw(canvas);
14675                    }
14676                } else {
14677                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14678                    ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags);
14679                }
14680            }
14681        } else if (cache != null) {
14682            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14683            Paint cachePaint;
14684
14685            if (layerType == LAYER_TYPE_NONE) {
14686                cachePaint = parent.mCachePaint;
14687                if (cachePaint == null) {
14688                    cachePaint = new Paint();
14689                    cachePaint.setDither(false);
14690                    parent.mCachePaint = cachePaint;
14691                }
14692                if (alpha < 1) {
14693                    cachePaint.setAlpha((int) (alpha * 255));
14694                    parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
14695                } else if  ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) {
14696                    cachePaint.setAlpha(255);
14697                    parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
14698                }
14699            } else {
14700                cachePaint = mLayerPaint;
14701                cachePaint.setAlpha((int) (alpha * 255));
14702            }
14703            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
14704        }
14705
14706        if (restoreTo >= 0) {
14707            canvas.restoreToCount(restoreTo);
14708        }
14709
14710        if (a != null && !more) {
14711            if (!hardwareAccelerated && !a.getFillAfter()) {
14712                onSetAlpha(255);
14713            }
14714            parent.finishAnimatingView(this, a);
14715        }
14716
14717        if (more && hardwareAccelerated) {
14718            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
14719                // alpha animations should cause the child to recreate its display list
14720                invalidate(true);
14721            }
14722        }
14723
14724        mRecreateDisplayList = false;
14725
14726        return more;
14727    }
14728
14729    /**
14730     * Manually render this view (and all of its children) to the given Canvas.
14731     * The view must have already done a full layout before this function is
14732     * called.  When implementing a view, implement
14733     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
14734     * If you do need to override this method, call the superclass version.
14735     *
14736     * @param canvas The Canvas to which the View is rendered.
14737     */
14738    public void draw(Canvas canvas) {
14739        if (mClipBounds != null) {
14740            canvas.clipRect(mClipBounds);
14741        }
14742        final int privateFlags = mPrivateFlags;
14743        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
14744                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
14745        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
14746
14747        /*
14748         * Draw traversal performs several drawing steps which must be executed
14749         * in the appropriate order:
14750         *
14751         *      1. Draw the background
14752         *      2. If necessary, save the canvas' layers to prepare for fading
14753         *      3. Draw view's content
14754         *      4. Draw children
14755         *      5. If necessary, draw the fading edges and restore layers
14756         *      6. Draw decorations (scrollbars for instance)
14757         */
14758
14759        // Step 1, draw the background, if needed
14760        int saveCount;
14761
14762        if (!dirtyOpaque) {
14763            drawBackground(canvas);
14764        }
14765
14766        // skip step 2 & 5 if possible (common case)
14767        final int viewFlags = mViewFlags;
14768        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
14769        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
14770        if (!verticalEdges && !horizontalEdges) {
14771            // Step 3, draw the content
14772            if (!dirtyOpaque) onDraw(canvas);
14773
14774            // Step 4, draw the children
14775            dispatchDraw(canvas);
14776
14777            // Step 6, draw decorations (scrollbars)
14778            onDrawScrollBars(canvas);
14779
14780            if (mOverlay != null && !mOverlay.isEmpty()) {
14781                mOverlay.getOverlayView().dispatchDraw(canvas);
14782            }
14783
14784            // we're done...
14785            return;
14786        }
14787
14788        /*
14789         * Here we do the full fledged routine...
14790         * (this is an uncommon case where speed matters less,
14791         * this is why we repeat some of the tests that have been
14792         * done above)
14793         */
14794
14795        boolean drawTop = false;
14796        boolean drawBottom = false;
14797        boolean drawLeft = false;
14798        boolean drawRight = false;
14799
14800        float topFadeStrength = 0.0f;
14801        float bottomFadeStrength = 0.0f;
14802        float leftFadeStrength = 0.0f;
14803        float rightFadeStrength = 0.0f;
14804
14805        // Step 2, save the canvas' layers
14806        int paddingLeft = mPaddingLeft;
14807
14808        final boolean offsetRequired = isPaddingOffsetRequired();
14809        if (offsetRequired) {
14810            paddingLeft += getLeftPaddingOffset();
14811        }
14812
14813        int left = mScrollX + paddingLeft;
14814        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
14815        int top = mScrollY + getFadeTop(offsetRequired);
14816        int bottom = top + getFadeHeight(offsetRequired);
14817
14818        if (offsetRequired) {
14819            right += getRightPaddingOffset();
14820            bottom += getBottomPaddingOffset();
14821        }
14822
14823        final ScrollabilityCache scrollabilityCache = mScrollCache;
14824        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
14825        int length = (int) fadeHeight;
14826
14827        // clip the fade length if top and bottom fades overlap
14828        // overlapping fades produce odd-looking artifacts
14829        if (verticalEdges && (top + length > bottom - length)) {
14830            length = (bottom - top) / 2;
14831        }
14832
14833        // also clip horizontal fades if necessary
14834        if (horizontalEdges && (left + length > right - length)) {
14835            length = (right - left) / 2;
14836        }
14837
14838        if (verticalEdges) {
14839            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
14840            drawTop = topFadeStrength * fadeHeight > 1.0f;
14841            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
14842            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
14843        }
14844
14845        if (horizontalEdges) {
14846            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
14847            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
14848            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
14849            drawRight = rightFadeStrength * fadeHeight > 1.0f;
14850        }
14851
14852        saveCount = canvas.getSaveCount();
14853
14854        int solidColor = getSolidColor();
14855        if (solidColor == 0) {
14856            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
14857
14858            if (drawTop) {
14859                canvas.saveLayer(left, top, right, top + length, null, flags);
14860            }
14861
14862            if (drawBottom) {
14863                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
14864            }
14865
14866            if (drawLeft) {
14867                canvas.saveLayer(left, top, left + length, bottom, null, flags);
14868            }
14869
14870            if (drawRight) {
14871                canvas.saveLayer(right - length, top, right, bottom, null, flags);
14872            }
14873        } else {
14874            scrollabilityCache.setFadeColor(solidColor);
14875        }
14876
14877        // Step 3, draw the content
14878        if (!dirtyOpaque) onDraw(canvas);
14879
14880        // Step 4, draw the children
14881        dispatchDraw(canvas);
14882
14883        // Step 5, draw the fade effect and restore layers
14884        final Paint p = scrollabilityCache.paint;
14885        final Matrix matrix = scrollabilityCache.matrix;
14886        final Shader fade = scrollabilityCache.shader;
14887
14888        if (drawTop) {
14889            matrix.setScale(1, fadeHeight * topFadeStrength);
14890            matrix.postTranslate(left, top);
14891            fade.setLocalMatrix(matrix);
14892            canvas.drawRect(left, top, right, top + length, p);
14893        }
14894
14895        if (drawBottom) {
14896            matrix.setScale(1, fadeHeight * bottomFadeStrength);
14897            matrix.postRotate(180);
14898            matrix.postTranslate(left, bottom);
14899            fade.setLocalMatrix(matrix);
14900            canvas.drawRect(left, bottom - length, right, bottom, p);
14901        }
14902
14903        if (drawLeft) {
14904            matrix.setScale(1, fadeHeight * leftFadeStrength);
14905            matrix.postRotate(-90);
14906            matrix.postTranslate(left, top);
14907            fade.setLocalMatrix(matrix);
14908            canvas.drawRect(left, top, left + length, bottom, p);
14909        }
14910
14911        if (drawRight) {
14912            matrix.setScale(1, fadeHeight * rightFadeStrength);
14913            matrix.postRotate(90);
14914            matrix.postTranslate(right, top);
14915            fade.setLocalMatrix(matrix);
14916            canvas.drawRect(right - length, top, right, bottom, p);
14917        }
14918
14919        canvas.restoreToCount(saveCount);
14920
14921        // Step 6, draw decorations (scrollbars)
14922        onDrawScrollBars(canvas);
14923
14924        if (mOverlay != null && !mOverlay.isEmpty()) {
14925            mOverlay.getOverlayView().dispatchDraw(canvas);
14926        }
14927    }
14928
14929    /**
14930     * Draws the background onto the specified canvas.
14931     *
14932     * @param canvas Canvas on which to draw the background
14933     */
14934    private void drawBackground(Canvas canvas) {
14935        final Drawable background = mBackground;
14936        if (background == null) {
14937            return;
14938        }
14939
14940        if (mBackgroundSizeChanged) {
14941            background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
14942            mBackgroundSizeChanged = false;
14943            queryOutlineFromBackgroundIfUndefined();
14944        }
14945
14946        // Attempt to use a display list if requested.
14947        if (canvas.isHardwareAccelerated() && mAttachInfo != null
14948                && mAttachInfo.mHardwareRenderer != null) {
14949            mBackgroundDisplayList = getDrawableDisplayList(background, mBackgroundDisplayList);
14950
14951            final RenderNode displayList = mBackgroundDisplayList;
14952            if (displayList != null && displayList.isValid()) {
14953                setBackgroundDisplayListProperties(displayList);
14954                ((HardwareCanvas) canvas).drawDisplayList(displayList);
14955                return;
14956            }
14957        }
14958
14959        final int scrollX = mScrollX;
14960        final int scrollY = mScrollY;
14961        if ((scrollX | scrollY) == 0) {
14962            background.draw(canvas);
14963        } else {
14964            canvas.translate(scrollX, scrollY);
14965            background.draw(canvas);
14966            canvas.translate(-scrollX, -scrollY);
14967        }
14968    }
14969
14970    /**
14971     * Set up background drawable display list properties.
14972     *
14973     * @param displayList Valid display list for the background drawable
14974     */
14975    private void setBackgroundDisplayListProperties(RenderNode displayList) {
14976        displayList.setTranslationX(mScrollX);
14977        displayList.setTranslationY(mScrollY);
14978    }
14979
14980    /**
14981     * Creates a new display list or updates the existing display list for the
14982     * specified Drawable.
14983     *
14984     * @param drawable Drawable for which to create a display list
14985     * @param displayList Existing display list, or {@code null}
14986     * @return A valid display list for the specified drawable
14987     */
14988    private RenderNode getDrawableDisplayList(Drawable drawable, RenderNode displayList) {
14989        if (displayList == null) {
14990            displayList = RenderNode.create(drawable.getClass().getName());
14991        }
14992
14993        final Rect bounds = drawable.getBounds();
14994        final int width = bounds.width();
14995        final int height = bounds.height();
14996        final HardwareCanvas canvas = displayList.start(width, height);
14997        try {
14998            drawable.draw(canvas);
14999        } finally {
15000            displayList.end(canvas);
15001        }
15002
15003        // Set up drawable properties that are view-independent.
15004        displayList.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom);
15005        displayList.setProjectBackwards(drawable.isProjected());
15006        displayList.setProjectionReceiver(true);
15007        displayList.setClipToBounds(false);
15008        return displayList;
15009    }
15010
15011    /**
15012     * Returns the overlay for this view, creating it if it does not yet exist.
15013     * Adding drawables to the overlay will cause them to be displayed whenever
15014     * the view itself is redrawn. Objects in the overlay should be actively
15015     * managed: remove them when they should not be displayed anymore. The
15016     * overlay will always have the same size as its host view.
15017     *
15018     * <p>Note: Overlays do not currently work correctly with {@link
15019     * SurfaceView} or {@link TextureView}; contents in overlays for these
15020     * types of views may not display correctly.</p>
15021     *
15022     * @return The ViewOverlay object for this view.
15023     * @see ViewOverlay
15024     */
15025    public ViewOverlay getOverlay() {
15026        if (mOverlay == null) {
15027            mOverlay = new ViewOverlay(mContext, this);
15028        }
15029        return mOverlay;
15030    }
15031
15032    /**
15033     * Override this if your view is known to always be drawn on top of a solid color background,
15034     * and needs to draw fading edges. Returning a non-zero color enables the view system to
15035     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
15036     * should be set to 0xFF.
15037     *
15038     * @see #setVerticalFadingEdgeEnabled(boolean)
15039     * @see #setHorizontalFadingEdgeEnabled(boolean)
15040     *
15041     * @return The known solid color background for this view, or 0 if the color may vary
15042     */
15043    @ViewDebug.ExportedProperty(category = "drawing")
15044    public int getSolidColor() {
15045        return 0;
15046    }
15047
15048    /**
15049     * Build a human readable string representation of the specified view flags.
15050     *
15051     * @param flags the view flags to convert to a string
15052     * @return a String representing the supplied flags
15053     */
15054    private static String printFlags(int flags) {
15055        String output = "";
15056        int numFlags = 0;
15057        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
15058            output += "TAKES_FOCUS";
15059            numFlags++;
15060        }
15061
15062        switch (flags & VISIBILITY_MASK) {
15063        case INVISIBLE:
15064            if (numFlags > 0) {
15065                output += " ";
15066            }
15067            output += "INVISIBLE";
15068            // USELESS HERE numFlags++;
15069            break;
15070        case GONE:
15071            if (numFlags > 0) {
15072                output += " ";
15073            }
15074            output += "GONE";
15075            // USELESS HERE numFlags++;
15076            break;
15077        default:
15078            break;
15079        }
15080        return output;
15081    }
15082
15083    /**
15084     * Build a human readable string representation of the specified private
15085     * view flags.
15086     *
15087     * @param privateFlags the private view flags to convert to a string
15088     * @return a String representing the supplied flags
15089     */
15090    private static String printPrivateFlags(int privateFlags) {
15091        String output = "";
15092        int numFlags = 0;
15093
15094        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
15095            output += "WANTS_FOCUS";
15096            numFlags++;
15097        }
15098
15099        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
15100            if (numFlags > 0) {
15101                output += " ";
15102            }
15103            output += "FOCUSED";
15104            numFlags++;
15105        }
15106
15107        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
15108            if (numFlags > 0) {
15109                output += " ";
15110            }
15111            output += "SELECTED";
15112            numFlags++;
15113        }
15114
15115        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
15116            if (numFlags > 0) {
15117                output += " ";
15118            }
15119            output += "IS_ROOT_NAMESPACE";
15120            numFlags++;
15121        }
15122
15123        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
15124            if (numFlags > 0) {
15125                output += " ";
15126            }
15127            output += "HAS_BOUNDS";
15128            numFlags++;
15129        }
15130
15131        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
15132            if (numFlags > 0) {
15133                output += " ";
15134            }
15135            output += "DRAWN";
15136            // USELESS HERE numFlags++;
15137        }
15138        return output;
15139    }
15140
15141    /**
15142     * <p>Indicates whether or not this view's layout will be requested during
15143     * the next hierarchy layout pass.</p>
15144     *
15145     * @return true if the layout will be forced during next layout pass
15146     */
15147    public boolean isLayoutRequested() {
15148        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
15149    }
15150
15151    /**
15152     * Return true if o is a ViewGroup that is laying out using optical bounds.
15153     * @hide
15154     */
15155    public static boolean isLayoutModeOptical(Object o) {
15156        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
15157    }
15158
15159    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
15160        Insets parentInsets = mParent instanceof View ?
15161                ((View) mParent).getOpticalInsets() : Insets.NONE;
15162        Insets childInsets = getOpticalInsets();
15163        return setFrame(
15164                left   + parentInsets.left - childInsets.left,
15165                top    + parentInsets.top  - childInsets.top,
15166                right  + parentInsets.left + childInsets.right,
15167                bottom + parentInsets.top  + childInsets.bottom);
15168    }
15169
15170    /**
15171     * Assign a size and position to a view and all of its
15172     * descendants
15173     *
15174     * <p>This is the second phase of the layout mechanism.
15175     * (The first is measuring). In this phase, each parent calls
15176     * layout on all of its children to position them.
15177     * This is typically done using the child measurements
15178     * that were stored in the measure pass().</p>
15179     *
15180     * <p>Derived classes should not override this method.
15181     * Derived classes with children should override
15182     * onLayout. In that method, they should
15183     * call layout on each of their children.</p>
15184     *
15185     * @param l Left position, relative to parent
15186     * @param t Top position, relative to parent
15187     * @param r Right position, relative to parent
15188     * @param b Bottom position, relative to parent
15189     */
15190    @SuppressWarnings({"unchecked"})
15191    public void layout(int l, int t, int r, int b) {
15192        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
15193            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
15194            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
15195        }
15196
15197        int oldL = mLeft;
15198        int oldT = mTop;
15199        int oldB = mBottom;
15200        int oldR = mRight;
15201
15202        boolean changed = isLayoutModeOptical(mParent) ?
15203                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
15204
15205        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
15206            onLayout(changed, l, t, r, b);
15207            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
15208
15209            ListenerInfo li = mListenerInfo;
15210            if (li != null && li.mOnLayoutChangeListeners != null) {
15211                ArrayList<OnLayoutChangeListener> listenersCopy =
15212                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
15213                int numListeners = listenersCopy.size();
15214                for (int i = 0; i < numListeners; ++i) {
15215                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
15216                }
15217            }
15218        }
15219
15220        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
15221        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
15222    }
15223
15224    /**
15225     * Called from layout when this view should
15226     * assign a size and position to each of its children.
15227     *
15228     * Derived classes with children should override
15229     * this method and call layout on each of
15230     * their children.
15231     * @param changed This is a new size or position for this view
15232     * @param left Left position, relative to parent
15233     * @param top Top position, relative to parent
15234     * @param right Right position, relative to parent
15235     * @param bottom Bottom position, relative to parent
15236     */
15237    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
15238    }
15239
15240    /**
15241     * Assign a size and position to this view.
15242     *
15243     * This is called from layout.
15244     *
15245     * @param left Left position, relative to parent
15246     * @param top Top position, relative to parent
15247     * @param right Right position, relative to parent
15248     * @param bottom Bottom position, relative to parent
15249     * @return true if the new size and position are different than the
15250     *         previous ones
15251     * {@hide}
15252     */
15253    protected boolean setFrame(int left, int top, int right, int bottom) {
15254        boolean changed = false;
15255
15256        if (DBG) {
15257            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
15258                    + right + "," + bottom + ")");
15259        }
15260
15261        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
15262            changed = true;
15263
15264            // Remember our drawn bit
15265            int drawn = mPrivateFlags & PFLAG_DRAWN;
15266
15267            int oldWidth = mRight - mLeft;
15268            int oldHeight = mBottom - mTop;
15269            int newWidth = right - left;
15270            int newHeight = bottom - top;
15271            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
15272
15273            // Invalidate our old position
15274            invalidate(sizeChanged);
15275
15276            mLeft = left;
15277            mTop = top;
15278            mRight = right;
15279            mBottom = bottom;
15280            mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
15281
15282            mPrivateFlags |= PFLAG_HAS_BOUNDS;
15283
15284
15285            if (sizeChanged) {
15286                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
15287            }
15288
15289            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
15290                // If we are visible, force the DRAWN bit to on so that
15291                // this invalidate will go through (at least to our parent).
15292                // This is because someone may have invalidated this view
15293                // before this call to setFrame came in, thereby clearing
15294                // the DRAWN bit.
15295                mPrivateFlags |= PFLAG_DRAWN;
15296                invalidate(sizeChanged);
15297                // parent display list may need to be recreated based on a change in the bounds
15298                // of any child
15299                invalidateParentCaches();
15300            }
15301
15302            // Reset drawn bit to original value (invalidate turns it off)
15303            mPrivateFlags |= drawn;
15304
15305            mBackgroundSizeChanged = true;
15306
15307            notifySubtreeAccessibilityStateChangedIfNeeded();
15308        }
15309        return changed;
15310    }
15311
15312    private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
15313        onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
15314        if (mOverlay != null) {
15315            mOverlay.getOverlayView().setRight(newWidth);
15316            mOverlay.getOverlayView().setBottom(newHeight);
15317        }
15318    }
15319
15320    /**
15321     * Finalize inflating a view from XML.  This is called as the last phase
15322     * of inflation, after all child views have been added.
15323     *
15324     * <p>Even if the subclass overrides onFinishInflate, they should always be
15325     * sure to call the super method, so that we get called.
15326     */
15327    protected void onFinishInflate() {
15328    }
15329
15330    /**
15331     * Returns the resources associated with this view.
15332     *
15333     * @return Resources object.
15334     */
15335    public Resources getResources() {
15336        return mResources;
15337    }
15338
15339    /**
15340     * Invalidates the specified Drawable.
15341     *
15342     * @param drawable the drawable to invalidate
15343     */
15344    @Override
15345    public void invalidateDrawable(@NonNull Drawable drawable) {
15346        if (verifyDrawable(drawable)) {
15347            final Rect dirty = drawable.getDirtyBounds();
15348            final int scrollX = mScrollX;
15349            final int scrollY = mScrollY;
15350
15351            invalidate(dirty.left + scrollX, dirty.top + scrollY,
15352                    dirty.right + scrollX, dirty.bottom + scrollY);
15353
15354            if (drawable == mBackground) {
15355                queryOutlineFromBackgroundIfUndefined();
15356            }
15357        }
15358    }
15359
15360    /**
15361     * Schedules an action on a drawable to occur at a specified time.
15362     *
15363     * @param who the recipient of the action
15364     * @param what the action to run on the drawable
15365     * @param when the time at which the action must occur. Uses the
15366     *        {@link SystemClock#uptimeMillis} timebase.
15367     */
15368    @Override
15369    public void scheduleDrawable(Drawable who, Runnable what, long when) {
15370        if (verifyDrawable(who) && what != null) {
15371            final long delay = when - SystemClock.uptimeMillis();
15372            if (mAttachInfo != null) {
15373                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
15374                        Choreographer.CALLBACK_ANIMATION, what, who,
15375                        Choreographer.subtractFrameDelay(delay));
15376            } else {
15377                ViewRootImpl.getRunQueue().postDelayed(what, delay);
15378            }
15379        }
15380    }
15381
15382    /**
15383     * Cancels a scheduled action on a drawable.
15384     *
15385     * @param who the recipient of the action
15386     * @param what the action to cancel
15387     */
15388    @Override
15389    public void unscheduleDrawable(Drawable who, Runnable what) {
15390        if (verifyDrawable(who) && what != null) {
15391            if (mAttachInfo != null) {
15392                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
15393                        Choreographer.CALLBACK_ANIMATION, what, who);
15394            }
15395            ViewRootImpl.getRunQueue().removeCallbacks(what);
15396        }
15397    }
15398
15399    /**
15400     * Unschedule any events associated with the given Drawable.  This can be
15401     * used when selecting a new Drawable into a view, so that the previous
15402     * one is completely unscheduled.
15403     *
15404     * @param who The Drawable to unschedule.
15405     *
15406     * @see #drawableStateChanged
15407     */
15408    public void unscheduleDrawable(Drawable who) {
15409        if (mAttachInfo != null && who != null) {
15410            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
15411                    Choreographer.CALLBACK_ANIMATION, null, who);
15412        }
15413    }
15414
15415    /**
15416     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
15417     * that the View directionality can and will be resolved before its Drawables.
15418     *
15419     * Will call {@link View#onResolveDrawables} when resolution is done.
15420     *
15421     * @hide
15422     */
15423    protected void resolveDrawables() {
15424        // Drawables resolution may need to happen before resolving the layout direction (which is
15425        // done only during the measure() call).
15426        // If the layout direction is not resolved yet, we cannot resolve the Drawables except in
15427        // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT.
15428        // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or
15429        // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout
15430        // direction to be resolved as its resolved value will be the same as its raw value.
15431        if (!isLayoutDirectionResolved() &&
15432                getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) {
15433            return;
15434        }
15435
15436        final int layoutDirection = isLayoutDirectionResolved() ?
15437                getLayoutDirection() : getRawLayoutDirection();
15438
15439        if (mBackground != null) {
15440            mBackground.setLayoutDirection(layoutDirection);
15441        }
15442        mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
15443        onResolveDrawables(layoutDirection);
15444    }
15445
15446    /**
15447     * Called when layout direction has been resolved.
15448     *
15449     * The default implementation does nothing.
15450     *
15451     * @param layoutDirection The resolved layout direction.
15452     *
15453     * @see #LAYOUT_DIRECTION_LTR
15454     * @see #LAYOUT_DIRECTION_RTL
15455     *
15456     * @hide
15457     */
15458    public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) {
15459    }
15460
15461    /**
15462     * @hide
15463     */
15464    protected void resetResolvedDrawables() {
15465        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
15466    }
15467
15468    private boolean isDrawablesResolved() {
15469        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
15470    }
15471
15472    /**
15473     * If your view subclass is displaying its own Drawable objects, it should
15474     * override this function and return true for any Drawable it is
15475     * displaying.  This allows animations for those drawables to be
15476     * scheduled.
15477     *
15478     * <p>Be sure to call through to the super class when overriding this
15479     * function.
15480     *
15481     * @param who The Drawable to verify.  Return true if it is one you are
15482     *            displaying, else return the result of calling through to the
15483     *            super class.
15484     *
15485     * @return boolean If true than the Drawable is being displayed in the
15486     *         view; else false and it is not allowed to animate.
15487     *
15488     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
15489     * @see #drawableStateChanged()
15490     */
15491    protected boolean verifyDrawable(Drawable who) {
15492        return who == mBackground;
15493    }
15494
15495    /**
15496     * This function is called whenever the state of the view changes in such
15497     * a way that it impacts the state of drawables being shown.
15498     * <p>
15499     * If the View has a StateListAnimator, it will also be called to run necessary state
15500     * change animations.
15501     * <p>
15502     * Be sure to call through to the superclass when overriding this function.
15503     *
15504     * @see Drawable#setState(int[])
15505     */
15506    protected void drawableStateChanged() {
15507        final Drawable d = mBackground;
15508        if (d != null && d.isStateful()) {
15509            d.setState(getDrawableState());
15510        }
15511
15512        if (mStateListAnimator != null) {
15513            mStateListAnimator.setState(getDrawableState());
15514        }
15515    }
15516
15517    /**
15518     * Call this to force a view to update its drawable state. This will cause
15519     * drawableStateChanged to be called on this view. Views that are interested
15520     * in the new state should call getDrawableState.
15521     *
15522     * @see #drawableStateChanged
15523     * @see #getDrawableState
15524     */
15525    public void refreshDrawableState() {
15526        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
15527        drawableStateChanged();
15528
15529        ViewParent parent = mParent;
15530        if (parent != null) {
15531            parent.childDrawableStateChanged(this);
15532        }
15533    }
15534
15535    /**
15536     * Return an array of resource IDs of the drawable states representing the
15537     * current state of the view.
15538     *
15539     * @return The current drawable state
15540     *
15541     * @see Drawable#setState(int[])
15542     * @see #drawableStateChanged()
15543     * @see #onCreateDrawableState(int)
15544     */
15545    public final int[] getDrawableState() {
15546        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
15547            return mDrawableState;
15548        } else {
15549            mDrawableState = onCreateDrawableState(0);
15550            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
15551            return mDrawableState;
15552        }
15553    }
15554
15555    /**
15556     * Generate the new {@link android.graphics.drawable.Drawable} state for
15557     * this view. This is called by the view
15558     * system when the cached Drawable state is determined to be invalid.  To
15559     * retrieve the current state, you should use {@link #getDrawableState}.
15560     *
15561     * @param extraSpace if non-zero, this is the number of extra entries you
15562     * would like in the returned array in which you can place your own
15563     * states.
15564     *
15565     * @return Returns an array holding the current {@link Drawable} state of
15566     * the view.
15567     *
15568     * @see #mergeDrawableStates(int[], int[])
15569     */
15570    protected int[] onCreateDrawableState(int extraSpace) {
15571        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
15572                mParent instanceof View) {
15573            return ((View) mParent).onCreateDrawableState(extraSpace);
15574        }
15575
15576        int[] drawableState;
15577
15578        int privateFlags = mPrivateFlags;
15579
15580        int viewStateIndex = 0;
15581        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
15582        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
15583        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
15584        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
15585        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
15586        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
15587        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
15588                HardwareRenderer.isAvailable()) {
15589            // This is set if HW acceleration is requested, even if the current
15590            // process doesn't allow it.  This is just to allow app preview
15591            // windows to better match their app.
15592            viewStateIndex |= VIEW_STATE_ACCELERATED;
15593        }
15594        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
15595
15596        final int privateFlags2 = mPrivateFlags2;
15597        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
15598        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
15599
15600        drawableState = VIEW_STATE_SETS[viewStateIndex];
15601
15602        //noinspection ConstantIfStatement
15603        if (false) {
15604            Log.i("View", "drawableStateIndex=" + viewStateIndex);
15605            Log.i("View", toString()
15606                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
15607                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
15608                    + " fo=" + hasFocus()
15609                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
15610                    + " wf=" + hasWindowFocus()
15611                    + ": " + Arrays.toString(drawableState));
15612        }
15613
15614        if (extraSpace == 0) {
15615            return drawableState;
15616        }
15617
15618        final int[] fullState;
15619        if (drawableState != null) {
15620            fullState = new int[drawableState.length + extraSpace];
15621            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
15622        } else {
15623            fullState = new int[extraSpace];
15624        }
15625
15626        return fullState;
15627    }
15628
15629    /**
15630     * Merge your own state values in <var>additionalState</var> into the base
15631     * state values <var>baseState</var> that were returned by
15632     * {@link #onCreateDrawableState(int)}.
15633     *
15634     * @param baseState The base state values returned by
15635     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
15636     * own additional state values.
15637     *
15638     * @param additionalState The additional state values you would like
15639     * added to <var>baseState</var>; this array is not modified.
15640     *
15641     * @return As a convenience, the <var>baseState</var> array you originally
15642     * passed into the function is returned.
15643     *
15644     * @see #onCreateDrawableState(int)
15645     */
15646    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
15647        final int N = baseState.length;
15648        int i = N - 1;
15649        while (i >= 0 && baseState[i] == 0) {
15650            i--;
15651        }
15652        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
15653        return baseState;
15654    }
15655
15656    /**
15657     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
15658     * on all Drawable objects associated with this view.
15659     * <p>
15660     * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator
15661     * attached to this view.
15662     */
15663    public void jumpDrawablesToCurrentState() {
15664        if (mBackground != null) {
15665            mBackground.jumpToCurrentState();
15666        }
15667        if (mStateListAnimator != null) {
15668            mStateListAnimator.jumpToCurrentState();
15669        }
15670    }
15671
15672    /**
15673     * Sets the background color for this view.
15674     * @param color the color of the background
15675     */
15676    @RemotableViewMethod
15677    public void setBackgroundColor(int color) {
15678        if (mBackground instanceof ColorDrawable) {
15679            ((ColorDrawable) mBackground.mutate()).setColor(color);
15680            computeOpaqueFlags();
15681            mBackgroundResource = 0;
15682        } else {
15683            setBackground(new ColorDrawable(color));
15684        }
15685    }
15686
15687    /**
15688     * Set the background to a given resource. The resource should refer to
15689     * a Drawable object or 0 to remove the background.
15690     * @param resid The identifier of the resource.
15691     *
15692     * @attr ref android.R.styleable#View_background
15693     */
15694    @RemotableViewMethod
15695    public void setBackgroundResource(int resid) {
15696        if (resid != 0 && resid == mBackgroundResource) {
15697            return;
15698        }
15699
15700        Drawable d= null;
15701        if (resid != 0) {
15702            d = mContext.getDrawable(resid);
15703        }
15704        setBackground(d);
15705
15706        mBackgroundResource = resid;
15707    }
15708
15709    /**
15710     * Set the background to a given Drawable, or remove the background. If the
15711     * background has padding, this View's padding is set to the background's
15712     * padding. However, when a background is removed, this View's padding isn't
15713     * touched. If setting the padding is desired, please use
15714     * {@link #setPadding(int, int, int, int)}.
15715     *
15716     * @param background The Drawable to use as the background, or null to remove the
15717     *        background
15718     */
15719    public void setBackground(Drawable background) {
15720        //noinspection deprecation
15721        setBackgroundDrawable(background);
15722    }
15723
15724    /**
15725     * @deprecated use {@link #setBackground(Drawable)} instead
15726     */
15727    @Deprecated
15728    public void setBackgroundDrawable(Drawable background) {
15729        computeOpaqueFlags();
15730
15731        if (background == mBackground) {
15732            return;
15733        }
15734
15735        boolean requestLayout = false;
15736
15737        mBackgroundResource = 0;
15738
15739        /*
15740         * Regardless of whether we're setting a new background or not, we want
15741         * to clear the previous drawable.
15742         */
15743        if (mBackground != null) {
15744            mBackground.setCallback(null);
15745            unscheduleDrawable(mBackground);
15746        }
15747
15748        if (background != null) {
15749            Rect padding = sThreadLocal.get();
15750            if (padding == null) {
15751                padding = new Rect();
15752                sThreadLocal.set(padding);
15753            }
15754            resetResolvedDrawables();
15755            background.setLayoutDirection(getLayoutDirection());
15756            if (background.getPadding(padding)) {
15757                resetResolvedPadding();
15758                switch (background.getLayoutDirection()) {
15759                    case LAYOUT_DIRECTION_RTL:
15760                        mUserPaddingLeftInitial = padding.right;
15761                        mUserPaddingRightInitial = padding.left;
15762                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
15763                        break;
15764                    case LAYOUT_DIRECTION_LTR:
15765                    default:
15766                        mUserPaddingLeftInitial = padding.left;
15767                        mUserPaddingRightInitial = padding.right;
15768                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
15769                }
15770                mLeftPaddingDefined = false;
15771                mRightPaddingDefined = false;
15772            }
15773
15774            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
15775            // if it has a different minimum size, we should layout again
15776            if (mBackground == null || mBackground.getMinimumHeight() != background.getMinimumHeight() ||
15777                    mBackground.getMinimumWidth() != background.getMinimumWidth()) {
15778                requestLayout = true;
15779            }
15780
15781            background.setCallback(this);
15782            if (background.isStateful()) {
15783                background.setState(getDrawableState());
15784            }
15785            background.setVisible(getVisibility() == VISIBLE, false);
15786            mBackground = background;
15787
15788            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
15789                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
15790                mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
15791                requestLayout = true;
15792            }
15793        } else {
15794            /* Remove the background */
15795            mBackground = null;
15796
15797            if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) {
15798                /*
15799                 * This view ONLY drew the background before and we're removing
15800                 * the background, so now it won't draw anything
15801                 * (hence we SKIP_DRAW)
15802                 */
15803                mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND;
15804                mPrivateFlags |= PFLAG_SKIP_DRAW;
15805            }
15806
15807            /*
15808             * When the background is set, we try to apply its padding to this
15809             * View. When the background is removed, we don't touch this View's
15810             * padding. This is noted in the Javadocs. Hence, we don't need to
15811             * requestLayout(), the invalidate() below is sufficient.
15812             */
15813
15814            // The old background's minimum size could have affected this
15815            // View's layout, so let's requestLayout
15816            requestLayout = true;
15817        }
15818
15819        computeOpaqueFlags();
15820
15821        if (requestLayout) {
15822            requestLayout();
15823        }
15824
15825        mBackgroundSizeChanged = true;
15826        invalidate(true);
15827    }
15828
15829    /**
15830     * Gets the background drawable
15831     *
15832     * @return The drawable used as the background for this view, if any.
15833     *
15834     * @see #setBackground(Drawable)
15835     *
15836     * @attr ref android.R.styleable#View_background
15837     */
15838    public Drawable getBackground() {
15839        return mBackground;
15840    }
15841
15842    /**
15843     * Sets the padding. The view may add on the space required to display
15844     * the scrollbars, depending on the style and visibility of the scrollbars.
15845     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
15846     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
15847     * from the values set in this call.
15848     *
15849     * @attr ref android.R.styleable#View_padding
15850     * @attr ref android.R.styleable#View_paddingBottom
15851     * @attr ref android.R.styleable#View_paddingLeft
15852     * @attr ref android.R.styleable#View_paddingRight
15853     * @attr ref android.R.styleable#View_paddingTop
15854     * @param left the left padding in pixels
15855     * @param top the top padding in pixels
15856     * @param right the right padding in pixels
15857     * @param bottom the bottom padding in pixels
15858     */
15859    public void setPadding(int left, int top, int right, int bottom) {
15860        resetResolvedPadding();
15861
15862        mUserPaddingStart = UNDEFINED_PADDING;
15863        mUserPaddingEnd = UNDEFINED_PADDING;
15864
15865        mUserPaddingLeftInitial = left;
15866        mUserPaddingRightInitial = right;
15867
15868        mLeftPaddingDefined = true;
15869        mRightPaddingDefined = true;
15870
15871        internalSetPadding(left, top, right, bottom);
15872    }
15873
15874    /**
15875     * @hide
15876     */
15877    protected void internalSetPadding(int left, int top, int right, int bottom) {
15878        mUserPaddingLeft = left;
15879        mUserPaddingRight = right;
15880        mUserPaddingBottom = bottom;
15881
15882        final int viewFlags = mViewFlags;
15883        boolean changed = false;
15884
15885        // Common case is there are no scroll bars.
15886        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
15887            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
15888                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
15889                        ? 0 : getVerticalScrollbarWidth();
15890                switch (mVerticalScrollbarPosition) {
15891                    case SCROLLBAR_POSITION_DEFAULT:
15892                        if (isLayoutRtl()) {
15893                            left += offset;
15894                        } else {
15895                            right += offset;
15896                        }
15897                        break;
15898                    case SCROLLBAR_POSITION_RIGHT:
15899                        right += offset;
15900                        break;
15901                    case SCROLLBAR_POSITION_LEFT:
15902                        left += offset;
15903                        break;
15904                }
15905            }
15906            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
15907                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
15908                        ? 0 : getHorizontalScrollbarHeight();
15909            }
15910        }
15911
15912        if (mPaddingLeft != left) {
15913            changed = true;
15914            mPaddingLeft = left;
15915        }
15916        if (mPaddingTop != top) {
15917            changed = true;
15918            mPaddingTop = top;
15919        }
15920        if (mPaddingRight != right) {
15921            changed = true;
15922            mPaddingRight = right;
15923        }
15924        if (mPaddingBottom != bottom) {
15925            changed = true;
15926            mPaddingBottom = bottom;
15927        }
15928
15929        if (changed) {
15930            requestLayout();
15931        }
15932    }
15933
15934    /**
15935     * Sets the relative padding. The view may add on the space required to display
15936     * the scrollbars, depending on the style and visibility of the scrollbars.
15937     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
15938     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
15939     * from the values set in this call.
15940     *
15941     * @attr ref android.R.styleable#View_padding
15942     * @attr ref android.R.styleable#View_paddingBottom
15943     * @attr ref android.R.styleable#View_paddingStart
15944     * @attr ref android.R.styleable#View_paddingEnd
15945     * @attr ref android.R.styleable#View_paddingTop
15946     * @param start the start padding in pixels
15947     * @param top the top padding in pixels
15948     * @param end the end padding in pixels
15949     * @param bottom the bottom padding in pixels
15950     */
15951    public void setPaddingRelative(int start, int top, int end, int bottom) {
15952        resetResolvedPadding();
15953
15954        mUserPaddingStart = start;
15955        mUserPaddingEnd = end;
15956        mLeftPaddingDefined = true;
15957        mRightPaddingDefined = true;
15958
15959        switch(getLayoutDirection()) {
15960            case LAYOUT_DIRECTION_RTL:
15961                mUserPaddingLeftInitial = end;
15962                mUserPaddingRightInitial = start;
15963                internalSetPadding(end, top, start, bottom);
15964                break;
15965            case LAYOUT_DIRECTION_LTR:
15966            default:
15967                mUserPaddingLeftInitial = start;
15968                mUserPaddingRightInitial = end;
15969                internalSetPadding(start, top, end, bottom);
15970        }
15971    }
15972
15973    /**
15974     * Returns the top padding of this view.
15975     *
15976     * @return the top padding in pixels
15977     */
15978    public int getPaddingTop() {
15979        return mPaddingTop;
15980    }
15981
15982    /**
15983     * Returns the bottom padding of this view. If there are inset and enabled
15984     * scrollbars, this value may include the space required to display the
15985     * scrollbars as well.
15986     *
15987     * @return the bottom padding in pixels
15988     */
15989    public int getPaddingBottom() {
15990        return mPaddingBottom;
15991    }
15992
15993    /**
15994     * Returns the left padding of this view. If there are inset and enabled
15995     * scrollbars, this value may include the space required to display the
15996     * scrollbars as well.
15997     *
15998     * @return the left padding in pixels
15999     */
16000    public int getPaddingLeft() {
16001        if (!isPaddingResolved()) {
16002            resolvePadding();
16003        }
16004        return mPaddingLeft;
16005    }
16006
16007    /**
16008     * Returns the start padding of this view depending on its resolved layout direction.
16009     * If there are inset and enabled scrollbars, this value may include the space
16010     * required to display the scrollbars as well.
16011     *
16012     * @return the start padding in pixels
16013     */
16014    public int getPaddingStart() {
16015        if (!isPaddingResolved()) {
16016            resolvePadding();
16017        }
16018        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
16019                mPaddingRight : mPaddingLeft;
16020    }
16021
16022    /**
16023     * Returns the right padding of this view. If there are inset and enabled
16024     * scrollbars, this value may include the space required to display the
16025     * scrollbars as well.
16026     *
16027     * @return the right padding in pixels
16028     */
16029    public int getPaddingRight() {
16030        if (!isPaddingResolved()) {
16031            resolvePadding();
16032        }
16033        return mPaddingRight;
16034    }
16035
16036    /**
16037     * Returns the end padding of this view depending on its resolved layout direction.
16038     * If there are inset and enabled scrollbars, this value may include the space
16039     * required to display the scrollbars as well.
16040     *
16041     * @return the end padding in pixels
16042     */
16043    public int getPaddingEnd() {
16044        if (!isPaddingResolved()) {
16045            resolvePadding();
16046        }
16047        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
16048                mPaddingLeft : mPaddingRight;
16049    }
16050
16051    /**
16052     * Return if the padding as been set thru relative values
16053     * {@link #setPaddingRelative(int, int, int, int)} or thru
16054     * @attr ref android.R.styleable#View_paddingStart or
16055     * @attr ref android.R.styleable#View_paddingEnd
16056     *
16057     * @return true if the padding is relative or false if it is not.
16058     */
16059    public boolean isPaddingRelative() {
16060        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
16061    }
16062
16063    Insets computeOpticalInsets() {
16064        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
16065    }
16066
16067    /**
16068     * @hide
16069     */
16070    public void resetPaddingToInitialValues() {
16071        if (isRtlCompatibilityMode()) {
16072            mPaddingLeft = mUserPaddingLeftInitial;
16073            mPaddingRight = mUserPaddingRightInitial;
16074            return;
16075        }
16076        if (isLayoutRtl()) {
16077            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
16078            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
16079        } else {
16080            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
16081            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
16082        }
16083    }
16084
16085    /**
16086     * @hide
16087     */
16088    public Insets getOpticalInsets() {
16089        if (mLayoutInsets == null) {
16090            mLayoutInsets = computeOpticalInsets();
16091        }
16092        return mLayoutInsets;
16093    }
16094
16095    /**
16096     * Set this view's optical insets.
16097     *
16098     * <p>This method should be treated similarly to setMeasuredDimension and not as a general
16099     * property. Views that compute their own optical insets should call it as part of measurement.
16100     * This method does not request layout. If you are setting optical insets outside of
16101     * measure/layout itself you will want to call requestLayout() yourself.
16102     * </p>
16103     * @hide
16104     */
16105    public void setOpticalInsets(Insets insets) {
16106        mLayoutInsets = insets;
16107    }
16108
16109    /**
16110     * Changes the selection state of this view. A view can be selected or not.
16111     * Note that selection is not the same as focus. Views are typically
16112     * selected in the context of an AdapterView like ListView or GridView;
16113     * the selected view is the view that is highlighted.
16114     *
16115     * @param selected true if the view must be selected, false otherwise
16116     */
16117    public void setSelected(boolean selected) {
16118        //noinspection DoubleNegation
16119        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
16120            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
16121            if (!selected) resetPressedState();
16122            invalidate(true);
16123            refreshDrawableState();
16124            dispatchSetSelected(selected);
16125            notifyViewAccessibilityStateChangedIfNeeded(
16126                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
16127        }
16128    }
16129
16130    /**
16131     * Dispatch setSelected to all of this View's children.
16132     *
16133     * @see #setSelected(boolean)
16134     *
16135     * @param selected The new selected state
16136     */
16137    protected void dispatchSetSelected(boolean selected) {
16138    }
16139
16140    /**
16141     * Indicates the selection state of this view.
16142     *
16143     * @return true if the view is selected, false otherwise
16144     */
16145    @ViewDebug.ExportedProperty
16146    public boolean isSelected() {
16147        return (mPrivateFlags & PFLAG_SELECTED) != 0;
16148    }
16149
16150    /**
16151     * Changes the activated state of this view. A view can be activated or not.
16152     * Note that activation is not the same as selection.  Selection is
16153     * a transient property, representing the view (hierarchy) the user is
16154     * currently interacting with.  Activation is a longer-term state that the
16155     * user can move views in and out of.  For example, in a list view with
16156     * single or multiple selection enabled, the views in the current selection
16157     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
16158     * here.)  The activated state is propagated down to children of the view it
16159     * is set on.
16160     *
16161     * @param activated true if the view must be activated, false otherwise
16162     */
16163    public void setActivated(boolean activated) {
16164        //noinspection DoubleNegation
16165        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
16166            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
16167            invalidate(true);
16168            refreshDrawableState();
16169            dispatchSetActivated(activated);
16170        }
16171    }
16172
16173    /**
16174     * Dispatch setActivated to all of this View's children.
16175     *
16176     * @see #setActivated(boolean)
16177     *
16178     * @param activated The new activated state
16179     */
16180    protected void dispatchSetActivated(boolean activated) {
16181    }
16182
16183    /**
16184     * Indicates the activation state of this view.
16185     *
16186     * @return true if the view is activated, false otherwise
16187     */
16188    @ViewDebug.ExportedProperty
16189    public boolean isActivated() {
16190        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
16191    }
16192
16193    /**
16194     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
16195     * observer can be used to get notifications when global events, like
16196     * layout, happen.
16197     *
16198     * The returned ViewTreeObserver observer is not guaranteed to remain
16199     * valid for the lifetime of this View. If the caller of this method keeps
16200     * a long-lived reference to ViewTreeObserver, it should always check for
16201     * the return value of {@link ViewTreeObserver#isAlive()}.
16202     *
16203     * @return The ViewTreeObserver for this view's hierarchy.
16204     */
16205    public ViewTreeObserver getViewTreeObserver() {
16206        if (mAttachInfo != null) {
16207            return mAttachInfo.mTreeObserver;
16208        }
16209        if (mFloatingTreeObserver == null) {
16210            mFloatingTreeObserver = new ViewTreeObserver();
16211        }
16212        return mFloatingTreeObserver;
16213    }
16214
16215    /**
16216     * <p>Finds the topmost view in the current view hierarchy.</p>
16217     *
16218     * @return the topmost view containing this view
16219     */
16220    public View getRootView() {
16221        if (mAttachInfo != null) {
16222            final View v = mAttachInfo.mRootView;
16223            if (v != null) {
16224                return v;
16225            }
16226        }
16227
16228        View parent = this;
16229
16230        while (parent.mParent != null && parent.mParent instanceof View) {
16231            parent = (View) parent.mParent;
16232        }
16233
16234        return parent;
16235    }
16236
16237    /**
16238     * Transforms a motion event from view-local coordinates to on-screen
16239     * coordinates.
16240     *
16241     * @param ev the view-local motion event
16242     * @return false if the transformation could not be applied
16243     * @hide
16244     */
16245    public boolean toGlobalMotionEvent(MotionEvent ev) {
16246        final AttachInfo info = mAttachInfo;
16247        if (info == null) {
16248            return false;
16249        }
16250
16251        final Matrix m = info.mTmpMatrix;
16252        m.set(Matrix.IDENTITY_MATRIX);
16253        transformMatrixToGlobal(m);
16254        ev.transform(m);
16255        return true;
16256    }
16257
16258    /**
16259     * Transforms a motion event from on-screen coordinates to view-local
16260     * coordinates.
16261     *
16262     * @param ev the on-screen motion event
16263     * @return false if the transformation could not be applied
16264     * @hide
16265     */
16266    public boolean toLocalMotionEvent(MotionEvent ev) {
16267        final AttachInfo info = mAttachInfo;
16268        if (info == null) {
16269            return false;
16270        }
16271
16272        final Matrix m = info.mTmpMatrix;
16273        m.set(Matrix.IDENTITY_MATRIX);
16274        transformMatrixToLocal(m);
16275        ev.transform(m);
16276        return true;
16277    }
16278
16279    /**
16280     * Modifies the input matrix such that it maps view-local coordinates to
16281     * on-screen coordinates.
16282     *
16283     * @param m input matrix to modify
16284     */
16285    void transformMatrixToGlobal(Matrix m) {
16286        final ViewParent parent = mParent;
16287        if (parent instanceof View) {
16288            final View vp = (View) parent;
16289            vp.transformMatrixToGlobal(m);
16290            m.postTranslate(-vp.mScrollX, -vp.mScrollY);
16291        } else if (parent instanceof ViewRootImpl) {
16292            final ViewRootImpl vr = (ViewRootImpl) parent;
16293            vr.transformMatrixToGlobal(m);
16294            m.postTranslate(0, -vr.mCurScrollY);
16295        }
16296
16297        m.postTranslate(mLeft, mTop);
16298
16299        if (!hasIdentityMatrix()) {
16300            m.postConcat(getMatrix());
16301        }
16302    }
16303
16304    /**
16305     * Modifies the input matrix such that it maps on-screen coordinates to
16306     * view-local coordinates.
16307     *
16308     * @param m input matrix to modify
16309     */
16310    void transformMatrixToLocal(Matrix m) {
16311        final ViewParent parent = mParent;
16312        if (parent instanceof View) {
16313            final View vp = (View) parent;
16314            vp.transformMatrixToLocal(m);
16315            m.preTranslate(vp.mScrollX, vp.mScrollY);
16316        } else if (parent instanceof ViewRootImpl) {
16317            final ViewRootImpl vr = (ViewRootImpl) parent;
16318            vr.transformMatrixToLocal(m);
16319            m.preTranslate(0, vr.mCurScrollY);
16320        }
16321
16322        m.preTranslate(-mLeft, -mTop);
16323
16324        if (!hasIdentityMatrix()) {
16325            m.preConcat(getInverseMatrix());
16326        }
16327    }
16328
16329    /**
16330     * <p>Computes the coordinates of this view on the screen. The argument
16331     * must be an array of two integers. After the method returns, the array
16332     * contains the x and y location in that order.</p>
16333     *
16334     * @param location an array of two integers in which to hold the coordinates
16335     */
16336    public void getLocationOnScreen(int[] location) {
16337        getLocationInWindow(location);
16338
16339        final AttachInfo info = mAttachInfo;
16340        if (info != null) {
16341            location[0] += info.mWindowLeft;
16342            location[1] += info.mWindowTop;
16343        }
16344    }
16345
16346    /**
16347     * <p>Computes the coordinates of this view in its window. The argument
16348     * must be an array of two integers. After the method returns, the array
16349     * contains the x and y location in that order.</p>
16350     *
16351     * @param location an array of two integers in which to hold the coordinates
16352     */
16353    public void getLocationInWindow(int[] location) {
16354        if (location == null || location.length < 2) {
16355            throw new IllegalArgumentException("location must be an array of two integers");
16356        }
16357
16358        if (mAttachInfo == null) {
16359            // When the view is not attached to a window, this method does not make sense
16360            location[0] = location[1] = 0;
16361            return;
16362        }
16363
16364        float[] position = mAttachInfo.mTmpTransformLocation;
16365        position[0] = position[1] = 0.0f;
16366
16367        if (!hasIdentityMatrix()) {
16368            getMatrix().mapPoints(position);
16369        }
16370
16371        position[0] += mLeft;
16372        position[1] += mTop;
16373
16374        ViewParent viewParent = mParent;
16375        while (viewParent instanceof View) {
16376            final View view = (View) viewParent;
16377
16378            position[0] -= view.mScrollX;
16379            position[1] -= view.mScrollY;
16380
16381            if (!view.hasIdentityMatrix()) {
16382                view.getMatrix().mapPoints(position);
16383            }
16384
16385            position[0] += view.mLeft;
16386            position[1] += view.mTop;
16387
16388            viewParent = view.mParent;
16389         }
16390
16391        if (viewParent instanceof ViewRootImpl) {
16392            // *cough*
16393            final ViewRootImpl vr = (ViewRootImpl) viewParent;
16394            position[1] -= vr.mCurScrollY;
16395        }
16396
16397        location[0] = (int) (position[0] + 0.5f);
16398        location[1] = (int) (position[1] + 0.5f);
16399    }
16400
16401    /**
16402     * {@hide}
16403     * @param id the id of the view to be found
16404     * @return the view of the specified id, null if cannot be found
16405     */
16406    protected View findViewTraversal(int id) {
16407        if (id == mID) {
16408            return this;
16409        }
16410        return null;
16411    }
16412
16413    /**
16414     * {@hide}
16415     * @param tag the tag of the view to be found
16416     * @return the view of specified tag, null if cannot be found
16417     */
16418    protected View findViewWithTagTraversal(Object tag) {
16419        if (tag != null && tag.equals(mTag)) {
16420            return this;
16421        }
16422        return null;
16423    }
16424
16425    /**
16426     * {@hide}
16427     * @param predicate The predicate to evaluate.
16428     * @param childToSkip If not null, ignores this child during the recursive traversal.
16429     * @return The first view that matches the predicate or null.
16430     */
16431    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
16432        if (predicate.apply(this)) {
16433            return this;
16434        }
16435        return null;
16436    }
16437
16438    /**
16439     * Look for a child view with the given id.  If this view has the given
16440     * id, return this view.
16441     *
16442     * @param id The id to search for.
16443     * @return The view that has the given id in the hierarchy or null
16444     */
16445    public final View findViewById(int id) {
16446        if (id < 0) {
16447            return null;
16448        }
16449        return findViewTraversal(id);
16450    }
16451
16452    /**
16453     * Finds a view by its unuque and stable accessibility id.
16454     *
16455     * @param accessibilityId The searched accessibility id.
16456     * @return The found view.
16457     */
16458    final View findViewByAccessibilityId(int accessibilityId) {
16459        if (accessibilityId < 0) {
16460            return null;
16461        }
16462        return findViewByAccessibilityIdTraversal(accessibilityId);
16463    }
16464
16465    /**
16466     * Performs the traversal to find a view by its unuque and stable accessibility id.
16467     *
16468     * <strong>Note:</strong>This method does not stop at the root namespace
16469     * boundary since the user can touch the screen at an arbitrary location
16470     * potentially crossing the root namespace bounday which will send an
16471     * accessibility event to accessibility services and they should be able
16472     * to obtain the event source. Also accessibility ids are guaranteed to be
16473     * unique in the window.
16474     *
16475     * @param accessibilityId The accessibility id.
16476     * @return The found view.
16477     *
16478     * @hide
16479     */
16480    public View findViewByAccessibilityIdTraversal(int accessibilityId) {
16481        if (getAccessibilityViewId() == accessibilityId) {
16482            return this;
16483        }
16484        return null;
16485    }
16486
16487    /**
16488     * Look for a child view with the given tag.  If this view has the given
16489     * tag, return this view.
16490     *
16491     * @param tag The tag to search for, using "tag.equals(getTag())".
16492     * @return The View that has the given tag in the hierarchy or null
16493     */
16494    public final View findViewWithTag(Object tag) {
16495        if (tag == null) {
16496            return null;
16497        }
16498        return findViewWithTagTraversal(tag);
16499    }
16500
16501    /**
16502     * {@hide}
16503     * Look for a child view that matches the specified predicate.
16504     * If this view matches the predicate, return this view.
16505     *
16506     * @param predicate The predicate to evaluate.
16507     * @return The first view that matches the predicate or null.
16508     */
16509    public final View findViewByPredicate(Predicate<View> predicate) {
16510        return findViewByPredicateTraversal(predicate, null);
16511    }
16512
16513    /**
16514     * {@hide}
16515     * Look for a child view that matches the specified predicate,
16516     * starting with the specified view and its descendents and then
16517     * recusively searching the ancestors and siblings of that view
16518     * until this view is reached.
16519     *
16520     * This method is useful in cases where the predicate does not match
16521     * a single unique view (perhaps multiple views use the same id)
16522     * and we are trying to find the view that is "closest" in scope to the
16523     * starting view.
16524     *
16525     * @param start The view to start from.
16526     * @param predicate The predicate to evaluate.
16527     * @return The first view that matches the predicate or null.
16528     */
16529    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
16530        View childToSkip = null;
16531        for (;;) {
16532            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
16533            if (view != null || start == this) {
16534                return view;
16535            }
16536
16537            ViewParent parent = start.getParent();
16538            if (parent == null || !(parent instanceof View)) {
16539                return null;
16540            }
16541
16542            childToSkip = start;
16543            start = (View) parent;
16544        }
16545    }
16546
16547    /**
16548     * Sets the identifier for this view. The identifier does not have to be
16549     * unique in this view's hierarchy. The identifier should be a positive
16550     * number.
16551     *
16552     * @see #NO_ID
16553     * @see #getId()
16554     * @see #findViewById(int)
16555     *
16556     * @param id a number used to identify the view
16557     *
16558     * @attr ref android.R.styleable#View_id
16559     */
16560    public void setId(int id) {
16561        mID = id;
16562        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
16563            mID = generateViewId();
16564        }
16565    }
16566
16567    /**
16568     * {@hide}
16569     *
16570     * @param isRoot true if the view belongs to the root namespace, false
16571     *        otherwise
16572     */
16573    public void setIsRootNamespace(boolean isRoot) {
16574        if (isRoot) {
16575            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
16576        } else {
16577            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
16578        }
16579    }
16580
16581    /**
16582     * {@hide}
16583     *
16584     * @return true if the view belongs to the root namespace, false otherwise
16585     */
16586    public boolean isRootNamespace() {
16587        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
16588    }
16589
16590    /**
16591     * Returns this view's identifier.
16592     *
16593     * @return a positive integer used to identify the view or {@link #NO_ID}
16594     *         if the view has no ID
16595     *
16596     * @see #setId(int)
16597     * @see #findViewById(int)
16598     * @attr ref android.R.styleable#View_id
16599     */
16600    @ViewDebug.CapturedViewProperty
16601    public int getId() {
16602        return mID;
16603    }
16604
16605    /**
16606     * Returns this view's tag.
16607     *
16608     * @return the Object stored in this view as a tag, or {@code null} if not
16609     *         set
16610     *
16611     * @see #setTag(Object)
16612     * @see #getTag(int)
16613     */
16614    @ViewDebug.ExportedProperty
16615    public Object getTag() {
16616        return mTag;
16617    }
16618
16619    /**
16620     * Sets the tag associated with this view. A tag can be used to mark
16621     * a view in its hierarchy and does not have to be unique within the
16622     * hierarchy. Tags can also be used to store data within a view without
16623     * resorting to another data structure.
16624     *
16625     * @param tag an Object to tag the view with
16626     *
16627     * @see #getTag()
16628     * @see #setTag(int, Object)
16629     */
16630    public void setTag(final Object tag) {
16631        mTag = tag;
16632    }
16633
16634    /**
16635     * Returns the tag associated with this view and the specified key.
16636     *
16637     * @param key The key identifying the tag
16638     *
16639     * @return the Object stored in this view as a tag, or {@code null} if not
16640     *         set
16641     *
16642     * @see #setTag(int, Object)
16643     * @see #getTag()
16644     */
16645    public Object getTag(int key) {
16646        if (mKeyedTags != null) return mKeyedTags.get(key);
16647        return null;
16648    }
16649
16650    /**
16651     * Sets a tag associated with this view and a key. A tag can be used
16652     * to mark a view in its hierarchy and does not have to be unique within
16653     * the hierarchy. Tags can also be used to store data within a view
16654     * without resorting to another data structure.
16655     *
16656     * The specified key should be an id declared in the resources of the
16657     * application to ensure it is unique (see the <a
16658     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
16659     * Keys identified as belonging to
16660     * the Android framework or not associated with any package will cause
16661     * an {@link IllegalArgumentException} to be thrown.
16662     *
16663     * @param key The key identifying the tag
16664     * @param tag An Object to tag the view with
16665     *
16666     * @throws IllegalArgumentException If they specified key is not valid
16667     *
16668     * @see #setTag(Object)
16669     * @see #getTag(int)
16670     */
16671    public void setTag(int key, final Object tag) {
16672        // If the package id is 0x00 or 0x01, it's either an undefined package
16673        // or a framework id
16674        if ((key >>> 24) < 2) {
16675            throw new IllegalArgumentException("The key must be an application-specific "
16676                    + "resource id.");
16677        }
16678
16679        setKeyedTag(key, tag);
16680    }
16681
16682    /**
16683     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
16684     * framework id.
16685     *
16686     * @hide
16687     */
16688    public void setTagInternal(int key, Object tag) {
16689        if ((key >>> 24) != 0x1) {
16690            throw new IllegalArgumentException("The key must be a framework-specific "
16691                    + "resource id.");
16692        }
16693
16694        setKeyedTag(key, tag);
16695    }
16696
16697    private void setKeyedTag(int key, Object tag) {
16698        if (mKeyedTags == null) {
16699            mKeyedTags = new SparseArray<Object>(2);
16700        }
16701
16702        mKeyedTags.put(key, tag);
16703    }
16704
16705    /**
16706     * Prints information about this view in the log output, with the tag
16707     * {@link #VIEW_LOG_TAG}.
16708     *
16709     * @hide
16710     */
16711    public void debug() {
16712        debug(0);
16713    }
16714
16715    /**
16716     * Prints information about this view in the log output, with the tag
16717     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
16718     * indentation defined by the <code>depth</code>.
16719     *
16720     * @param depth the indentation level
16721     *
16722     * @hide
16723     */
16724    protected void debug(int depth) {
16725        String output = debugIndent(depth - 1);
16726
16727        output += "+ " + this;
16728        int id = getId();
16729        if (id != -1) {
16730            output += " (id=" + id + ")";
16731        }
16732        Object tag = getTag();
16733        if (tag != null) {
16734            output += " (tag=" + tag + ")";
16735        }
16736        Log.d(VIEW_LOG_TAG, output);
16737
16738        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
16739            output = debugIndent(depth) + " FOCUSED";
16740            Log.d(VIEW_LOG_TAG, output);
16741        }
16742
16743        output = debugIndent(depth);
16744        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
16745                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
16746                + "} ";
16747        Log.d(VIEW_LOG_TAG, output);
16748
16749        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
16750                || mPaddingBottom != 0) {
16751            output = debugIndent(depth);
16752            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
16753                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
16754            Log.d(VIEW_LOG_TAG, output);
16755        }
16756
16757        output = debugIndent(depth);
16758        output += "mMeasureWidth=" + mMeasuredWidth +
16759                " mMeasureHeight=" + mMeasuredHeight;
16760        Log.d(VIEW_LOG_TAG, output);
16761
16762        output = debugIndent(depth);
16763        if (mLayoutParams == null) {
16764            output += "BAD! no layout params";
16765        } else {
16766            output = mLayoutParams.debug(output);
16767        }
16768        Log.d(VIEW_LOG_TAG, output);
16769
16770        output = debugIndent(depth);
16771        output += "flags={";
16772        output += View.printFlags(mViewFlags);
16773        output += "}";
16774        Log.d(VIEW_LOG_TAG, output);
16775
16776        output = debugIndent(depth);
16777        output += "privateFlags={";
16778        output += View.printPrivateFlags(mPrivateFlags);
16779        output += "}";
16780        Log.d(VIEW_LOG_TAG, output);
16781    }
16782
16783    /**
16784     * Creates a string of whitespaces used for indentation.
16785     *
16786     * @param depth the indentation level
16787     * @return a String containing (depth * 2 + 3) * 2 white spaces
16788     *
16789     * @hide
16790     */
16791    protected static String debugIndent(int depth) {
16792        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
16793        for (int i = 0; i < (depth * 2) + 3; i++) {
16794            spaces.append(' ').append(' ');
16795        }
16796        return spaces.toString();
16797    }
16798
16799    /**
16800     * <p>Return the offset of the widget's text baseline from the widget's top
16801     * boundary. If this widget does not support baseline alignment, this
16802     * method returns -1. </p>
16803     *
16804     * @return the offset of the baseline within the widget's bounds or -1
16805     *         if baseline alignment is not supported
16806     */
16807    @ViewDebug.ExportedProperty(category = "layout")
16808    public int getBaseline() {
16809        return -1;
16810    }
16811
16812    /**
16813     * Returns whether the view hierarchy is currently undergoing a layout pass. This
16814     * information is useful to avoid situations such as calling {@link #requestLayout()} during
16815     * a layout pass.
16816     *
16817     * @return whether the view hierarchy is currently undergoing a layout pass
16818     */
16819    public boolean isInLayout() {
16820        ViewRootImpl viewRoot = getViewRootImpl();
16821        return (viewRoot != null && viewRoot.isInLayout());
16822    }
16823
16824    /**
16825     * Call this when something has changed which has invalidated the
16826     * layout of this view. This will schedule a layout pass of the view
16827     * tree. This should not be called while the view hierarchy is currently in a layout
16828     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
16829     * end of the current layout pass (and then layout will run again) or after the current
16830     * frame is drawn and the next layout occurs.
16831     *
16832     * <p>Subclasses which override this method should call the superclass method to
16833     * handle possible request-during-layout errors correctly.</p>
16834     */
16835    public void requestLayout() {
16836        if (mMeasureCache != null) mMeasureCache.clear();
16837
16838        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
16839            // Only trigger request-during-layout logic if this is the view requesting it,
16840            // not the views in its parent hierarchy
16841            ViewRootImpl viewRoot = getViewRootImpl();
16842            if (viewRoot != null && viewRoot.isInLayout()) {
16843                if (!viewRoot.requestLayoutDuringLayout(this)) {
16844                    return;
16845                }
16846            }
16847            mAttachInfo.mViewRequestingLayout = this;
16848        }
16849
16850        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
16851        mPrivateFlags |= PFLAG_INVALIDATED;
16852
16853        if (mParent != null && !mParent.isLayoutRequested()) {
16854            mParent.requestLayout();
16855        }
16856        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
16857            mAttachInfo.mViewRequestingLayout = null;
16858        }
16859    }
16860
16861    /**
16862     * Forces this view to be laid out during the next layout pass.
16863     * This method does not call requestLayout() or forceLayout()
16864     * on the parent.
16865     */
16866    public void forceLayout() {
16867        if (mMeasureCache != null) mMeasureCache.clear();
16868
16869        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
16870        mPrivateFlags |= PFLAG_INVALIDATED;
16871    }
16872
16873    /**
16874     * <p>
16875     * This is called to find out how big a view should be. The parent
16876     * supplies constraint information in the width and height parameters.
16877     * </p>
16878     *
16879     * <p>
16880     * The actual measurement work of a view is performed in
16881     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
16882     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
16883     * </p>
16884     *
16885     *
16886     * @param widthMeasureSpec Horizontal space requirements as imposed by the
16887     *        parent
16888     * @param heightMeasureSpec Vertical space requirements as imposed by the
16889     *        parent
16890     *
16891     * @see #onMeasure(int, int)
16892     */
16893    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
16894        boolean optical = isLayoutModeOptical(this);
16895        if (optical != isLayoutModeOptical(mParent)) {
16896            Insets insets = getOpticalInsets();
16897            int oWidth  = insets.left + insets.right;
16898            int oHeight = insets.top  + insets.bottom;
16899            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
16900            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
16901        }
16902
16903        // Suppress sign extension for the low bytes
16904        long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
16905        if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
16906
16907        if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ||
16908                widthMeasureSpec != mOldWidthMeasureSpec ||
16909                heightMeasureSpec != mOldHeightMeasureSpec) {
16910
16911            // first clears the measured dimension flag
16912            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
16913
16914            resolveRtlPropertiesIfNeeded();
16915
16916            int cacheIndex = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ? -1 :
16917                    mMeasureCache.indexOfKey(key);
16918            if (cacheIndex < 0 || sIgnoreMeasureCache) {
16919                // measure ourselves, this should set the measured dimension flag back
16920                onMeasure(widthMeasureSpec, heightMeasureSpec);
16921                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
16922            } else {
16923                long value = mMeasureCache.valueAt(cacheIndex);
16924                // Casting a long to int drops the high 32 bits, no mask needed
16925                setMeasuredDimensionRaw((int) (value >> 32), (int) value);
16926                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
16927            }
16928
16929            // flag not set, setMeasuredDimension() was not invoked, we raise
16930            // an exception to warn the developer
16931            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
16932                throw new IllegalStateException("onMeasure() did not set the"
16933                        + " measured dimension by calling"
16934                        + " setMeasuredDimension()");
16935            }
16936
16937            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
16938        }
16939
16940        mOldWidthMeasureSpec = widthMeasureSpec;
16941        mOldHeightMeasureSpec = heightMeasureSpec;
16942
16943        mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
16944                (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
16945    }
16946
16947    /**
16948     * <p>
16949     * Measure the view and its content to determine the measured width and the
16950     * measured height. This method is invoked by {@link #measure(int, int)} and
16951     * should be overriden by subclasses to provide accurate and efficient
16952     * measurement of their contents.
16953     * </p>
16954     *
16955     * <p>
16956     * <strong>CONTRACT:</strong> When overriding this method, you
16957     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
16958     * measured width and height of this view. Failure to do so will trigger an
16959     * <code>IllegalStateException</code>, thrown by
16960     * {@link #measure(int, int)}. Calling the superclass'
16961     * {@link #onMeasure(int, int)} is a valid use.
16962     * </p>
16963     *
16964     * <p>
16965     * The base class implementation of measure defaults to the background size,
16966     * unless a larger size is allowed by the MeasureSpec. Subclasses should
16967     * override {@link #onMeasure(int, int)} to provide better measurements of
16968     * their content.
16969     * </p>
16970     *
16971     * <p>
16972     * If this method is overridden, it is the subclass's responsibility to make
16973     * sure the measured height and width are at least the view's minimum height
16974     * and width ({@link #getSuggestedMinimumHeight()} and
16975     * {@link #getSuggestedMinimumWidth()}).
16976     * </p>
16977     *
16978     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
16979     *                         The requirements are encoded with
16980     *                         {@link android.view.View.MeasureSpec}.
16981     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
16982     *                         The requirements are encoded with
16983     *                         {@link android.view.View.MeasureSpec}.
16984     *
16985     * @see #getMeasuredWidth()
16986     * @see #getMeasuredHeight()
16987     * @see #setMeasuredDimension(int, int)
16988     * @see #getSuggestedMinimumHeight()
16989     * @see #getSuggestedMinimumWidth()
16990     * @see android.view.View.MeasureSpec#getMode(int)
16991     * @see android.view.View.MeasureSpec#getSize(int)
16992     */
16993    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
16994        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
16995                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
16996    }
16997
16998    /**
16999     * <p>This method must be called by {@link #onMeasure(int, int)} to store the
17000     * measured width and measured height. Failing to do so will trigger an
17001     * exception at measurement time.</p>
17002     *
17003     * @param measuredWidth The measured width of this view.  May be a complex
17004     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17005     * {@link #MEASURED_STATE_TOO_SMALL}.
17006     * @param measuredHeight The measured height of this view.  May be a complex
17007     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17008     * {@link #MEASURED_STATE_TOO_SMALL}.
17009     */
17010    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
17011        boolean optical = isLayoutModeOptical(this);
17012        if (optical != isLayoutModeOptical(mParent)) {
17013            Insets insets = getOpticalInsets();
17014            int opticalWidth  = insets.left + insets.right;
17015            int opticalHeight = insets.top  + insets.bottom;
17016
17017            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
17018            measuredHeight += optical ? opticalHeight : -opticalHeight;
17019        }
17020        setMeasuredDimensionRaw(measuredWidth, measuredHeight);
17021    }
17022
17023    /**
17024     * Sets the measured dimension without extra processing for things like optical bounds.
17025     * Useful for reapplying consistent values that have already been cooked with adjustments
17026     * for optical bounds, etc. such as those from the measurement cache.
17027     *
17028     * @param measuredWidth The measured width of this view.  May be a complex
17029     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17030     * {@link #MEASURED_STATE_TOO_SMALL}.
17031     * @param measuredHeight The measured height of this view.  May be a complex
17032     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17033     * {@link #MEASURED_STATE_TOO_SMALL}.
17034     */
17035    private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
17036        mMeasuredWidth = measuredWidth;
17037        mMeasuredHeight = measuredHeight;
17038
17039        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
17040    }
17041
17042    /**
17043     * Merge two states as returned by {@link #getMeasuredState()}.
17044     * @param curState The current state as returned from a view or the result
17045     * of combining multiple views.
17046     * @param newState The new view state to combine.
17047     * @return Returns a new integer reflecting the combination of the two
17048     * states.
17049     */
17050    public static int combineMeasuredStates(int curState, int newState) {
17051        return curState | newState;
17052    }
17053
17054    /**
17055     * Version of {@link #resolveSizeAndState(int, int, int)}
17056     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
17057     */
17058    public static int resolveSize(int size, int measureSpec) {
17059        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
17060    }
17061
17062    /**
17063     * Utility to reconcile a desired size and state, with constraints imposed
17064     * by a MeasureSpec.  Will take the desired size, unless a different size
17065     * is imposed by the constraints.  The returned value is a compound integer,
17066     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
17067     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
17068     * size is smaller than the size the view wants to be.
17069     *
17070     * @param size How big the view wants to be
17071     * @param measureSpec Constraints imposed by the parent
17072     * @return Size information bit mask as defined by
17073     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
17074     */
17075    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
17076        int result = size;
17077        int specMode = MeasureSpec.getMode(measureSpec);
17078        int specSize =  MeasureSpec.getSize(measureSpec);
17079        switch (specMode) {
17080        case MeasureSpec.UNSPECIFIED:
17081            result = size;
17082            break;
17083        case MeasureSpec.AT_MOST:
17084            if (specSize < size) {
17085                result = specSize | MEASURED_STATE_TOO_SMALL;
17086            } else {
17087                result = size;
17088            }
17089            break;
17090        case MeasureSpec.EXACTLY:
17091            result = specSize;
17092            break;
17093        }
17094        return result | (childMeasuredState&MEASURED_STATE_MASK);
17095    }
17096
17097    /**
17098     * Utility to return a default size. Uses the supplied size if the
17099     * MeasureSpec imposed no constraints. Will get larger if allowed
17100     * by the MeasureSpec.
17101     *
17102     * @param size Default size for this view
17103     * @param measureSpec Constraints imposed by the parent
17104     * @return The size this view should be.
17105     */
17106    public static int getDefaultSize(int size, int measureSpec) {
17107        int result = size;
17108        int specMode = MeasureSpec.getMode(measureSpec);
17109        int specSize = MeasureSpec.getSize(measureSpec);
17110
17111        switch (specMode) {
17112        case MeasureSpec.UNSPECIFIED:
17113            result = size;
17114            break;
17115        case MeasureSpec.AT_MOST:
17116        case MeasureSpec.EXACTLY:
17117            result = specSize;
17118            break;
17119        }
17120        return result;
17121    }
17122
17123    /**
17124     * Returns the suggested minimum height that the view should use. This
17125     * returns the maximum of the view's minimum height
17126     * and the background's minimum height
17127     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
17128     * <p>
17129     * When being used in {@link #onMeasure(int, int)}, the caller should still
17130     * ensure the returned height is within the requirements of the parent.
17131     *
17132     * @return The suggested minimum height of the view.
17133     */
17134    protected int getSuggestedMinimumHeight() {
17135        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
17136
17137    }
17138
17139    /**
17140     * Returns the suggested minimum width that the view should use. This
17141     * returns the maximum of the view's minimum width)
17142     * and the background's minimum width
17143     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
17144     * <p>
17145     * When being used in {@link #onMeasure(int, int)}, the caller should still
17146     * ensure the returned width is within the requirements of the parent.
17147     *
17148     * @return The suggested minimum width of the view.
17149     */
17150    protected int getSuggestedMinimumWidth() {
17151        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
17152    }
17153
17154    /**
17155     * Returns the minimum height of the view.
17156     *
17157     * @return the minimum height the view will try to be.
17158     *
17159     * @see #setMinimumHeight(int)
17160     *
17161     * @attr ref android.R.styleable#View_minHeight
17162     */
17163    public int getMinimumHeight() {
17164        return mMinHeight;
17165    }
17166
17167    /**
17168     * Sets the minimum height of the view. It is not guaranteed the view will
17169     * be able to achieve this minimum height (for example, if its parent layout
17170     * constrains it with less available height).
17171     *
17172     * @param minHeight The minimum height the view will try to be.
17173     *
17174     * @see #getMinimumHeight()
17175     *
17176     * @attr ref android.R.styleable#View_minHeight
17177     */
17178    public void setMinimumHeight(int minHeight) {
17179        mMinHeight = minHeight;
17180        requestLayout();
17181    }
17182
17183    /**
17184     * Returns the minimum width of the view.
17185     *
17186     * @return the minimum width the view will try to be.
17187     *
17188     * @see #setMinimumWidth(int)
17189     *
17190     * @attr ref android.R.styleable#View_minWidth
17191     */
17192    public int getMinimumWidth() {
17193        return mMinWidth;
17194    }
17195
17196    /**
17197     * Sets the minimum width of the view. It is not guaranteed the view will
17198     * be able to achieve this minimum width (for example, if its parent layout
17199     * constrains it with less available width).
17200     *
17201     * @param minWidth The minimum width the view will try to be.
17202     *
17203     * @see #getMinimumWidth()
17204     *
17205     * @attr ref android.R.styleable#View_minWidth
17206     */
17207    public void setMinimumWidth(int minWidth) {
17208        mMinWidth = minWidth;
17209        requestLayout();
17210
17211    }
17212
17213    /**
17214     * Get the animation currently associated with this view.
17215     *
17216     * @return The animation that is currently playing or
17217     *         scheduled to play for this view.
17218     */
17219    public Animation getAnimation() {
17220        return mCurrentAnimation;
17221    }
17222
17223    /**
17224     * Start the specified animation now.
17225     *
17226     * @param animation the animation to start now
17227     */
17228    public void startAnimation(Animation animation) {
17229        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
17230        setAnimation(animation);
17231        invalidateParentCaches();
17232        invalidate(true);
17233    }
17234
17235    /**
17236     * Cancels any animations for this view.
17237     */
17238    public void clearAnimation() {
17239        if (mCurrentAnimation != null) {
17240            mCurrentAnimation.detach();
17241        }
17242        mCurrentAnimation = null;
17243        invalidateParentIfNeeded();
17244    }
17245
17246    /**
17247     * Sets the next animation to play for this view.
17248     * If you want the animation to play immediately, use
17249     * {@link #startAnimation(android.view.animation.Animation)} instead.
17250     * This method provides allows fine-grained
17251     * control over the start time and invalidation, but you
17252     * must make sure that 1) the animation has a start time set, and
17253     * 2) the view's parent (which controls animations on its children)
17254     * will be invalidated when the animation is supposed to
17255     * start.
17256     *
17257     * @param animation The next animation, or null.
17258     */
17259    public void setAnimation(Animation animation) {
17260        mCurrentAnimation = animation;
17261
17262        if (animation != null) {
17263            // If the screen is off assume the animation start time is now instead of
17264            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
17265            // would cause the animation to start when the screen turns back on
17266            if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF
17267                    && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
17268                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
17269            }
17270            animation.reset();
17271        }
17272    }
17273
17274    /**
17275     * Invoked by a parent ViewGroup to notify the start of the animation
17276     * currently associated with this view. If you override this method,
17277     * always call super.onAnimationStart();
17278     *
17279     * @see #setAnimation(android.view.animation.Animation)
17280     * @see #getAnimation()
17281     */
17282    protected void onAnimationStart() {
17283        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
17284    }
17285
17286    /**
17287     * Invoked by a parent ViewGroup to notify the end of the animation
17288     * currently associated with this view. If you override this method,
17289     * always call super.onAnimationEnd();
17290     *
17291     * @see #setAnimation(android.view.animation.Animation)
17292     * @see #getAnimation()
17293     */
17294    protected void onAnimationEnd() {
17295        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
17296    }
17297
17298    /**
17299     * Invoked if there is a Transform that involves alpha. Subclass that can
17300     * draw themselves with the specified alpha should return true, and then
17301     * respect that alpha when their onDraw() is called. If this returns false
17302     * then the view may be redirected to draw into an offscreen buffer to
17303     * fulfill the request, which will look fine, but may be slower than if the
17304     * subclass handles it internally. The default implementation returns false.
17305     *
17306     * @param alpha The alpha (0..255) to apply to the view's drawing
17307     * @return true if the view can draw with the specified alpha.
17308     */
17309    protected boolean onSetAlpha(int alpha) {
17310        return false;
17311    }
17312
17313    /**
17314     * This is used by the RootView to perform an optimization when
17315     * the view hierarchy contains one or several SurfaceView.
17316     * SurfaceView is always considered transparent, but its children are not,
17317     * therefore all View objects remove themselves from the global transparent
17318     * region (passed as a parameter to this function).
17319     *
17320     * @param region The transparent region for this ViewAncestor (window).
17321     *
17322     * @return Returns true if the effective visibility of the view at this
17323     * point is opaque, regardless of the transparent region; returns false
17324     * if it is possible for underlying windows to be seen behind the view.
17325     *
17326     * {@hide}
17327     */
17328    public boolean gatherTransparentRegion(Region region) {
17329        final AttachInfo attachInfo = mAttachInfo;
17330        if (region != null && attachInfo != null) {
17331            final int pflags = mPrivateFlags;
17332            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
17333                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
17334                // remove it from the transparent region.
17335                final int[] location = attachInfo.mTransparentLocation;
17336                getLocationInWindow(location);
17337                region.op(location[0], location[1], location[0] + mRight - mLeft,
17338                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
17339            } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) {
17340                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
17341                // exists, so we remove the background drawable's non-transparent
17342                // parts from this transparent region.
17343                applyDrawableToTransparentRegion(mBackground, region);
17344            }
17345        }
17346        return true;
17347    }
17348
17349    /**
17350     * Play a sound effect for this view.
17351     *
17352     * <p>The framework will play sound effects for some built in actions, such as
17353     * clicking, but you may wish to play these effects in your widget,
17354     * for instance, for internal navigation.
17355     *
17356     * <p>The sound effect will only be played if sound effects are enabled by the user, and
17357     * {@link #isSoundEffectsEnabled()} is true.
17358     *
17359     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
17360     */
17361    public void playSoundEffect(int soundConstant) {
17362        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
17363            return;
17364        }
17365        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
17366    }
17367
17368    /**
17369     * BZZZTT!!1!
17370     *
17371     * <p>Provide haptic feedback to the user for this view.
17372     *
17373     * <p>The framework will provide haptic feedback for some built in actions,
17374     * such as long presses, but you may wish to provide feedback for your
17375     * own widget.
17376     *
17377     * <p>The feedback will only be performed if
17378     * {@link #isHapticFeedbackEnabled()} is true.
17379     *
17380     * @param feedbackConstant One of the constants defined in
17381     * {@link HapticFeedbackConstants}
17382     */
17383    public boolean performHapticFeedback(int feedbackConstant) {
17384        return performHapticFeedback(feedbackConstant, 0);
17385    }
17386
17387    /**
17388     * BZZZTT!!1!
17389     *
17390     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
17391     *
17392     * @param feedbackConstant One of the constants defined in
17393     * {@link HapticFeedbackConstants}
17394     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
17395     */
17396    public boolean performHapticFeedback(int feedbackConstant, int flags) {
17397        if (mAttachInfo == null) {
17398            return false;
17399        }
17400        //noinspection SimplifiableIfStatement
17401        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
17402                && !isHapticFeedbackEnabled()) {
17403            return false;
17404        }
17405        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
17406                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
17407    }
17408
17409    /**
17410     * Request that the visibility of the status bar or other screen/window
17411     * decorations be changed.
17412     *
17413     * <p>This method is used to put the over device UI into temporary modes
17414     * where the user's attention is focused more on the application content,
17415     * by dimming or hiding surrounding system affordances.  This is typically
17416     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
17417     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
17418     * to be placed behind the action bar (and with these flags other system
17419     * affordances) so that smooth transitions between hiding and showing them
17420     * can be done.
17421     *
17422     * <p>Two representative examples of the use of system UI visibility is
17423     * implementing a content browsing application (like a magazine reader)
17424     * and a video playing application.
17425     *
17426     * <p>The first code shows a typical implementation of a View in a content
17427     * browsing application.  In this implementation, the application goes
17428     * into a content-oriented mode by hiding the status bar and action bar,
17429     * and putting the navigation elements into lights out mode.  The user can
17430     * then interact with content while in this mode.  Such an application should
17431     * provide an easy way for the user to toggle out of the mode (such as to
17432     * check information in the status bar or access notifications).  In the
17433     * implementation here, this is done simply by tapping on the content.
17434     *
17435     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
17436     *      content}
17437     *
17438     * <p>This second code sample shows a typical implementation of a View
17439     * in a video playing application.  In this situation, while the video is
17440     * playing the application would like to go into a complete full-screen mode,
17441     * to use as much of the display as possible for the video.  When in this state
17442     * the user can not interact with the application; the system intercepts
17443     * touching on the screen to pop the UI out of full screen mode.  See
17444     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
17445     *
17446     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
17447     *      content}
17448     *
17449     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
17450     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
17451     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
17452     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
17453     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
17454     */
17455    public void setSystemUiVisibility(int visibility) {
17456        if (visibility != mSystemUiVisibility) {
17457            mSystemUiVisibility = visibility;
17458            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
17459                mParent.recomputeViewAttributes(this);
17460            }
17461        }
17462    }
17463
17464    /**
17465     * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested.
17466     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
17467     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
17468     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
17469     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
17470     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
17471     */
17472    public int getSystemUiVisibility() {
17473        return mSystemUiVisibility;
17474    }
17475
17476    /**
17477     * Returns the current system UI visibility that is currently set for
17478     * the entire window.  This is the combination of the
17479     * {@link #setSystemUiVisibility(int)} values supplied by all of the
17480     * views in the window.
17481     */
17482    public int getWindowSystemUiVisibility() {
17483        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
17484    }
17485
17486    /**
17487     * Override to find out when the window's requested system UI visibility
17488     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
17489     * This is different from the callbacks received through
17490     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
17491     * in that this is only telling you about the local request of the window,
17492     * not the actual values applied by the system.
17493     */
17494    public void onWindowSystemUiVisibilityChanged(int visible) {
17495    }
17496
17497    /**
17498     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
17499     * the view hierarchy.
17500     */
17501    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
17502        onWindowSystemUiVisibilityChanged(visible);
17503    }
17504
17505    /**
17506     * Set a listener to receive callbacks when the visibility of the system bar changes.
17507     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
17508     */
17509    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
17510        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
17511        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
17512            mParent.recomputeViewAttributes(this);
17513        }
17514    }
17515
17516    /**
17517     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
17518     * the view hierarchy.
17519     */
17520    public void dispatchSystemUiVisibilityChanged(int visibility) {
17521        ListenerInfo li = mListenerInfo;
17522        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
17523            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
17524                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
17525        }
17526    }
17527
17528    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
17529        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
17530        if (val != mSystemUiVisibility) {
17531            setSystemUiVisibility(val);
17532            return true;
17533        }
17534        return false;
17535    }
17536
17537    /** @hide */
17538    public void setDisabledSystemUiVisibility(int flags) {
17539        if (mAttachInfo != null) {
17540            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
17541                mAttachInfo.mDisabledSystemUiVisibility = flags;
17542                if (mParent != null) {
17543                    mParent.recomputeViewAttributes(this);
17544                }
17545            }
17546        }
17547    }
17548
17549    /**
17550     * Creates an image that the system displays during the drag and drop
17551     * operation. This is called a &quot;drag shadow&quot;. The default implementation
17552     * for a DragShadowBuilder based on a View returns an image that has exactly the same
17553     * appearance as the given View. The default also positions the center of the drag shadow
17554     * directly under the touch point. If no View is provided (the constructor with no parameters
17555     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
17556     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
17557     * default is an invisible drag shadow.
17558     * <p>
17559     * You are not required to use the View you provide to the constructor as the basis of the
17560     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
17561     * anything you want as the drag shadow.
17562     * </p>
17563     * <p>
17564     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
17565     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
17566     *  size and position of the drag shadow. It uses this data to construct a
17567     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
17568     *  so that your application can draw the shadow image in the Canvas.
17569     * </p>
17570     *
17571     * <div class="special reference">
17572     * <h3>Developer Guides</h3>
17573     * <p>For a guide to implementing drag and drop features, read the
17574     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
17575     * </div>
17576     */
17577    public static class DragShadowBuilder {
17578        private final WeakReference<View> mView;
17579
17580        /**
17581         * Constructs a shadow image builder based on a View. By default, the resulting drag
17582         * shadow will have the same appearance and dimensions as the View, with the touch point
17583         * over the center of the View.
17584         * @param view A View. Any View in scope can be used.
17585         */
17586        public DragShadowBuilder(View view) {
17587            mView = new WeakReference<View>(view);
17588        }
17589
17590        /**
17591         * Construct a shadow builder object with no associated View.  This
17592         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
17593         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
17594         * to supply the drag shadow's dimensions and appearance without
17595         * reference to any View object. If they are not overridden, then the result is an
17596         * invisible drag shadow.
17597         */
17598        public DragShadowBuilder() {
17599            mView = new WeakReference<View>(null);
17600        }
17601
17602        /**
17603         * Returns the View object that had been passed to the
17604         * {@link #View.DragShadowBuilder(View)}
17605         * constructor.  If that View parameter was {@code null} or if the
17606         * {@link #View.DragShadowBuilder()}
17607         * constructor was used to instantiate the builder object, this method will return
17608         * null.
17609         *
17610         * @return The View object associate with this builder object.
17611         */
17612        @SuppressWarnings({"JavadocReference"})
17613        final public View getView() {
17614            return mView.get();
17615        }
17616
17617        /**
17618         * Provides the metrics for the shadow image. These include the dimensions of
17619         * the shadow image, and the point within that shadow that should
17620         * be centered under the touch location while dragging.
17621         * <p>
17622         * The default implementation sets the dimensions of the shadow to be the
17623         * same as the dimensions of the View itself and centers the shadow under
17624         * the touch point.
17625         * </p>
17626         *
17627         * @param shadowSize A {@link android.graphics.Point} containing the width and height
17628         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
17629         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
17630         * image.
17631         *
17632         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
17633         * shadow image that should be underneath the touch point during the drag and drop
17634         * operation. Your application must set {@link android.graphics.Point#x} to the
17635         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
17636         */
17637        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
17638            final View view = mView.get();
17639            if (view != null) {
17640                shadowSize.set(view.getWidth(), view.getHeight());
17641                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
17642            } else {
17643                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
17644            }
17645        }
17646
17647        /**
17648         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
17649         * based on the dimensions it received from the
17650         * {@link #onProvideShadowMetrics(Point, Point)} callback.
17651         *
17652         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
17653         */
17654        public void onDrawShadow(Canvas canvas) {
17655            final View view = mView.get();
17656            if (view != null) {
17657                view.draw(canvas);
17658            } else {
17659                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
17660            }
17661        }
17662    }
17663
17664    /**
17665     * Starts a drag and drop operation. When your application calls this method, it passes a
17666     * {@link android.view.View.DragShadowBuilder} object to the system. The
17667     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
17668     * to get metrics for the drag shadow, and then calls the object's
17669     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
17670     * <p>
17671     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
17672     *  drag events to all the View objects in your application that are currently visible. It does
17673     *  this either by calling the View object's drag listener (an implementation of
17674     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
17675     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
17676     *  Both are passed a {@link android.view.DragEvent} object that has a
17677     *  {@link android.view.DragEvent#getAction()} value of
17678     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
17679     * </p>
17680     * <p>
17681     * Your application can invoke startDrag() on any attached View object. The View object does not
17682     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
17683     * be related to the View the user selected for dragging.
17684     * </p>
17685     * @param data A {@link android.content.ClipData} object pointing to the data to be
17686     * transferred by the drag and drop operation.
17687     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
17688     * drag shadow.
17689     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
17690     * drop operation. This Object is put into every DragEvent object sent by the system during the
17691     * current drag.
17692     * <p>
17693     * myLocalState is a lightweight mechanism for the sending information from the dragged View
17694     * to the target Views. For example, it can contain flags that differentiate between a
17695     * a copy operation and a move operation.
17696     * </p>
17697     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
17698     * so the parameter should be set to 0.
17699     * @return {@code true} if the method completes successfully, or
17700     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
17701     * do a drag, and so no drag operation is in progress.
17702     */
17703    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
17704            Object myLocalState, int flags) {
17705        if (ViewDebug.DEBUG_DRAG) {
17706            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
17707        }
17708        boolean okay = false;
17709
17710        Point shadowSize = new Point();
17711        Point shadowTouchPoint = new Point();
17712        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
17713
17714        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
17715                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
17716            throw new IllegalStateException("Drag shadow dimensions must not be negative");
17717        }
17718
17719        if (ViewDebug.DEBUG_DRAG) {
17720            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
17721                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
17722        }
17723        Surface surface = new Surface();
17724        try {
17725            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
17726                    flags, shadowSize.x, shadowSize.y, surface);
17727            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
17728                    + " surface=" + surface);
17729            if (token != null) {
17730                Canvas canvas = surface.lockCanvas(null);
17731                try {
17732                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
17733                    shadowBuilder.onDrawShadow(canvas);
17734                } finally {
17735                    surface.unlockCanvasAndPost(canvas);
17736                }
17737
17738                final ViewRootImpl root = getViewRootImpl();
17739
17740                // Cache the local state object for delivery with DragEvents
17741                root.setLocalDragState(myLocalState);
17742
17743                // repurpose 'shadowSize' for the last touch point
17744                root.getLastTouchPoint(shadowSize);
17745
17746                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
17747                        shadowSize.x, shadowSize.y,
17748                        shadowTouchPoint.x, shadowTouchPoint.y, data);
17749                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
17750
17751                // Off and running!  Release our local surface instance; the drag
17752                // shadow surface is now managed by the system process.
17753                surface.release();
17754            }
17755        } catch (Exception e) {
17756            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
17757            surface.destroy();
17758        }
17759
17760        return okay;
17761    }
17762
17763    /**
17764     * Handles drag events sent by the system following a call to
17765     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
17766     *<p>
17767     * When the system calls this method, it passes a
17768     * {@link android.view.DragEvent} object. A call to
17769     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
17770     * in DragEvent. The method uses these to determine what is happening in the drag and drop
17771     * operation.
17772     * @param event The {@link android.view.DragEvent} sent by the system.
17773     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
17774     * in DragEvent, indicating the type of drag event represented by this object.
17775     * @return {@code true} if the method was successful, otherwise {@code false}.
17776     * <p>
17777     *  The method should return {@code true} in response to an action type of
17778     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
17779     *  operation.
17780     * </p>
17781     * <p>
17782     *  The method should also return {@code true} in response to an action type of
17783     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
17784     *  {@code false} if it didn't.
17785     * </p>
17786     */
17787    public boolean onDragEvent(DragEvent event) {
17788        return false;
17789    }
17790
17791    /**
17792     * Detects if this View is enabled and has a drag event listener.
17793     * If both are true, then it calls the drag event listener with the
17794     * {@link android.view.DragEvent} it received. If the drag event listener returns
17795     * {@code true}, then dispatchDragEvent() returns {@code true}.
17796     * <p>
17797     * For all other cases, the method calls the
17798     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
17799     * method and returns its result.
17800     * </p>
17801     * <p>
17802     * This ensures that a drag event is always consumed, even if the View does not have a drag
17803     * event listener. However, if the View has a listener and the listener returns true, then
17804     * onDragEvent() is not called.
17805     * </p>
17806     */
17807    public boolean dispatchDragEvent(DragEvent event) {
17808        ListenerInfo li = mListenerInfo;
17809        //noinspection SimplifiableIfStatement
17810        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
17811                && li.mOnDragListener.onDrag(this, event)) {
17812            return true;
17813        }
17814        return onDragEvent(event);
17815    }
17816
17817    boolean canAcceptDrag() {
17818        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
17819    }
17820
17821    /**
17822     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
17823     * it is ever exposed at all.
17824     * @hide
17825     */
17826    public void onCloseSystemDialogs(String reason) {
17827    }
17828
17829    /**
17830     * Given a Drawable whose bounds have been set to draw into this view,
17831     * update a Region being computed for
17832     * {@link #gatherTransparentRegion(android.graphics.Region)} so
17833     * that any non-transparent parts of the Drawable are removed from the
17834     * given transparent region.
17835     *
17836     * @param dr The Drawable whose transparency is to be applied to the region.
17837     * @param region A Region holding the current transparency information,
17838     * where any parts of the region that are set are considered to be
17839     * transparent.  On return, this region will be modified to have the
17840     * transparency information reduced by the corresponding parts of the
17841     * Drawable that are not transparent.
17842     * {@hide}
17843     */
17844    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
17845        if (DBG) {
17846            Log.i("View", "Getting transparent region for: " + this);
17847        }
17848        final Region r = dr.getTransparentRegion();
17849        final Rect db = dr.getBounds();
17850        final AttachInfo attachInfo = mAttachInfo;
17851        if (r != null && attachInfo != null) {
17852            final int w = getRight()-getLeft();
17853            final int h = getBottom()-getTop();
17854            if (db.left > 0) {
17855                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
17856                r.op(0, 0, db.left, h, Region.Op.UNION);
17857            }
17858            if (db.right < w) {
17859                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
17860                r.op(db.right, 0, w, h, Region.Op.UNION);
17861            }
17862            if (db.top > 0) {
17863                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
17864                r.op(0, 0, w, db.top, Region.Op.UNION);
17865            }
17866            if (db.bottom < h) {
17867                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
17868                r.op(0, db.bottom, w, h, Region.Op.UNION);
17869            }
17870            final int[] location = attachInfo.mTransparentLocation;
17871            getLocationInWindow(location);
17872            r.translate(location[0], location[1]);
17873            region.op(r, Region.Op.INTERSECT);
17874        } else {
17875            region.op(db, Region.Op.DIFFERENCE);
17876        }
17877    }
17878
17879    private void checkForLongClick(int delayOffset) {
17880        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
17881            mHasPerformedLongPress = false;
17882
17883            if (mPendingCheckForLongPress == null) {
17884                mPendingCheckForLongPress = new CheckForLongPress();
17885            }
17886            mPendingCheckForLongPress.rememberWindowAttachCount();
17887            postDelayed(mPendingCheckForLongPress,
17888                    ViewConfiguration.getLongPressTimeout() - delayOffset);
17889        }
17890    }
17891
17892    /**
17893     * Inflate a view from an XML resource.  This convenience method wraps the {@link
17894     * LayoutInflater} class, which provides a full range of options for view inflation.
17895     *
17896     * @param context The Context object for your activity or application.
17897     * @param resource The resource ID to inflate
17898     * @param root A view group that will be the parent.  Used to properly inflate the
17899     * layout_* parameters.
17900     * @see LayoutInflater
17901     */
17902    public static View inflate(Context context, int resource, ViewGroup root) {
17903        LayoutInflater factory = LayoutInflater.from(context);
17904        return factory.inflate(resource, root);
17905    }
17906
17907    /**
17908     * Scroll the view with standard behavior for scrolling beyond the normal
17909     * content boundaries. Views that call this method should override
17910     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
17911     * results of an over-scroll operation.
17912     *
17913     * Views can use this method to handle any touch or fling-based scrolling.
17914     *
17915     * @param deltaX Change in X in pixels
17916     * @param deltaY Change in Y in pixels
17917     * @param scrollX Current X scroll value in pixels before applying deltaX
17918     * @param scrollY Current Y scroll value in pixels before applying deltaY
17919     * @param scrollRangeX Maximum content scroll range along the X axis
17920     * @param scrollRangeY Maximum content scroll range along the Y axis
17921     * @param maxOverScrollX Number of pixels to overscroll by in either direction
17922     *          along the X axis.
17923     * @param maxOverScrollY Number of pixels to overscroll by in either direction
17924     *          along the Y axis.
17925     * @param isTouchEvent true if this scroll operation is the result of a touch event.
17926     * @return true if scrolling was clamped to an over-scroll boundary along either
17927     *          axis, false otherwise.
17928     */
17929    @SuppressWarnings({"UnusedParameters"})
17930    protected boolean overScrollBy(int deltaX, int deltaY,
17931            int scrollX, int scrollY,
17932            int scrollRangeX, int scrollRangeY,
17933            int maxOverScrollX, int maxOverScrollY,
17934            boolean isTouchEvent) {
17935        final int overScrollMode = mOverScrollMode;
17936        final boolean canScrollHorizontal =
17937                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
17938        final boolean canScrollVertical =
17939                computeVerticalScrollRange() > computeVerticalScrollExtent();
17940        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
17941                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
17942        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
17943                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
17944
17945        int newScrollX = scrollX + deltaX;
17946        if (!overScrollHorizontal) {
17947            maxOverScrollX = 0;
17948        }
17949
17950        int newScrollY = scrollY + deltaY;
17951        if (!overScrollVertical) {
17952            maxOverScrollY = 0;
17953        }
17954
17955        // Clamp values if at the limits and record
17956        final int left = -maxOverScrollX;
17957        final int right = maxOverScrollX + scrollRangeX;
17958        final int top = -maxOverScrollY;
17959        final int bottom = maxOverScrollY + scrollRangeY;
17960
17961        boolean clampedX = false;
17962        if (newScrollX > right) {
17963            newScrollX = right;
17964            clampedX = true;
17965        } else if (newScrollX < left) {
17966            newScrollX = left;
17967            clampedX = true;
17968        }
17969
17970        boolean clampedY = false;
17971        if (newScrollY > bottom) {
17972            newScrollY = bottom;
17973            clampedY = true;
17974        } else if (newScrollY < top) {
17975            newScrollY = top;
17976            clampedY = true;
17977        }
17978
17979        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
17980
17981        return clampedX || clampedY;
17982    }
17983
17984    /**
17985     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
17986     * respond to the results of an over-scroll operation.
17987     *
17988     * @param scrollX New X scroll value in pixels
17989     * @param scrollY New Y scroll value in pixels
17990     * @param clampedX True if scrollX was clamped to an over-scroll boundary
17991     * @param clampedY True if scrollY was clamped to an over-scroll boundary
17992     */
17993    protected void onOverScrolled(int scrollX, int scrollY,
17994            boolean clampedX, boolean clampedY) {
17995        // Intentionally empty.
17996    }
17997
17998    /**
17999     * Returns the over-scroll mode for this view. The result will be
18000     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
18001     * (allow over-scrolling only if the view content is larger than the container),
18002     * or {@link #OVER_SCROLL_NEVER}.
18003     *
18004     * @return This view's over-scroll mode.
18005     */
18006    public int getOverScrollMode() {
18007        return mOverScrollMode;
18008    }
18009
18010    /**
18011     * Set the over-scroll mode for this view. Valid over-scroll modes are
18012     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
18013     * (allow over-scrolling only if the view content is larger than the container),
18014     * or {@link #OVER_SCROLL_NEVER}.
18015     *
18016     * Setting the over-scroll mode of a view will have an effect only if the
18017     * view is capable of scrolling.
18018     *
18019     * @param overScrollMode The new over-scroll mode for this view.
18020     */
18021    public void setOverScrollMode(int overScrollMode) {
18022        if (overScrollMode != OVER_SCROLL_ALWAYS &&
18023                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
18024                overScrollMode != OVER_SCROLL_NEVER) {
18025            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
18026        }
18027        mOverScrollMode = overScrollMode;
18028    }
18029
18030    /**
18031     * Enable or disable nested scrolling for this view.
18032     *
18033     * <p>If this property is set to true the view will be permitted to initiate nested
18034     * scrolling operations with a compatible parent view in the current hierarchy. If this
18035     * view does not implement nested scrolling this will have no effect. Disabling nested scrolling
18036     * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping}
18037     * the nested scroll.</p>
18038     *
18039     * @param enabled true to enable nested scrolling, false to disable
18040     *
18041     * @see #isNestedScrollingEnabled()
18042     */
18043    public void setNestedScrollingEnabled(boolean enabled) {
18044        if (enabled) {
18045            mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED;
18046        } else {
18047            stopNestedScroll();
18048            mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED;
18049        }
18050    }
18051
18052    /**
18053     * Returns true if nested scrolling is enabled for this view.
18054     *
18055     * <p>If nested scrolling is enabled and this View class implementation supports it,
18056     * this view will act as a nested scrolling child view when applicable, forwarding data
18057     * about the scroll operation in progress to a compatible and cooperating nested scrolling
18058     * parent.</p>
18059     *
18060     * @return true if nested scrolling is enabled
18061     *
18062     * @see #setNestedScrollingEnabled(boolean)
18063     */
18064    public boolean isNestedScrollingEnabled() {
18065        return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) ==
18066                PFLAG3_NESTED_SCROLLING_ENABLED;
18067    }
18068
18069    /**
18070     * Begin a nestable scroll operation along the given axes.
18071     *
18072     * <p>A view starting a nested scroll promises to abide by the following contract:</p>
18073     *
18074     * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case
18075     * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}.
18076     * In the case of touch scrolling the nested scroll will be terminated automatically in
18077     * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}.
18078     * In the event of programmatic scrolling the caller must explicitly call
18079     * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p>
18080     *
18081     * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found.
18082     * If it returns false the caller may ignore the rest of this contract until the next scroll.
18083     * Calling startNestedScroll while a nested scroll is already in progress will return true.</p>
18084     *
18085     * <p>At each incremental step of the scroll the caller should invoke
18086     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll}
18087     * once it has calculated the requested scrolling delta. If it returns true the nested scrolling
18088     * parent at least partially consumed the scroll and the caller should adjust the amount it
18089     * scrolls by.</p>
18090     *
18091     * <p>After applying the remainder of the scroll delta the caller should invoke
18092     * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing
18093     * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat
18094     * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}.
18095     * </p>
18096     *
18097     * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or
18098     *             {@link #SCROLL_AXIS_VERTICAL}.
18099     * @return true if a cooperative parent was found and nested scrolling has been enabled for
18100     *         the current gesture.
18101     *
18102     * @see #stopNestedScroll()
18103     * @see #dispatchNestedPreScroll(int, int, int[], int[])
18104     * @see #dispatchNestedScroll(int, int, int, int, int[])
18105     */
18106    public boolean startNestedScroll(int axes) {
18107        if (hasNestedScrollingParent()) {
18108            // Already in progress
18109            return true;
18110        }
18111        if (isNestedScrollingEnabled()) {
18112            ViewParent p = getParent();
18113            View child = this;
18114            while (p != null) {
18115                try {
18116                    if (p.onStartNestedScroll(child, this, axes)) {
18117                        mNestedScrollingParent = p;
18118                        p.onNestedScrollAccepted(child, this, axes);
18119                        return true;
18120                    }
18121                } catch (AbstractMethodError e) {
18122                    Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " +
18123                            "method onStartNestedScroll", e);
18124                    // Allow the search upward to continue
18125                }
18126                if (p instanceof View) {
18127                    child = (View) p;
18128                }
18129                p = p.getParent();
18130            }
18131        }
18132        return false;
18133    }
18134
18135    /**
18136     * Stop a nested scroll in progress.
18137     *
18138     * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p>
18139     *
18140     * @see #startNestedScroll(int)
18141     */
18142    public void stopNestedScroll() {
18143        if (mNestedScrollingParent != null) {
18144            mNestedScrollingParent.onStopNestedScroll(this);
18145            mNestedScrollingParent = null;
18146        }
18147    }
18148
18149    /**
18150     * Returns true if this view has a nested scrolling parent.
18151     *
18152     * <p>The presence of a nested scrolling parent indicates that this view has initiated
18153     * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p>
18154     *
18155     * @return whether this view has a nested scrolling parent
18156     */
18157    public boolean hasNestedScrollingParent() {
18158        return mNestedScrollingParent != null;
18159    }
18160
18161    /**
18162     * Dispatch one step of a nested scroll in progress.
18163     *
18164     * <p>Implementations of views that support nested scrolling should call this to report
18165     * info about a scroll in progress to the current nested scrolling parent. If a nested scroll
18166     * is not currently in progress or nested scrolling is not
18167     * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p>
18168     *
18169     * <p>Compatible View implementations should also call
18170     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before
18171     * consuming a component of the scroll event themselves.</p>
18172     *
18173     * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step
18174     * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step
18175     * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view
18176     * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view
18177     * @param offsetInWindow Optional. If not null, on return this will contain the offset
18178     *                       in local view coordinates of this view from before this operation
18179     *                       to after it completes. View implementations may use this to adjust
18180     *                       expected input coordinate tracking.
18181     * @return true if the event was dispatched, false if it could not be dispatched.
18182     * @see #dispatchNestedPreScroll(int, int, int[], int[])
18183     */
18184    public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed,
18185            int dxUnconsumed, int dyUnconsumed, int[] offsetInWindow) {
18186        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
18187            if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) {
18188                int startX = 0;
18189                int startY = 0;
18190                if (offsetInWindow != null) {
18191                    getLocationInWindow(offsetInWindow);
18192                    startX = offsetInWindow[0];
18193                    startY = offsetInWindow[1];
18194                }
18195
18196                mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed,
18197                        dxUnconsumed, dyUnconsumed);
18198
18199                if (offsetInWindow != null) {
18200                    getLocationInWindow(offsetInWindow);
18201                    offsetInWindow[0] -= startX;
18202                    offsetInWindow[1] -= startY;
18203                }
18204                return true;
18205            } else if (offsetInWindow != null) {
18206                // No motion, no dispatch. Keep offsetInWindow up to date.
18207                offsetInWindow[0] = 0;
18208                offsetInWindow[1] = 0;
18209            }
18210        }
18211        return false;
18212    }
18213
18214    /**
18215     * Dispatch one step of a nested scroll in progress before this view consumes any portion of it.
18216     *
18217     * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch.
18218     * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested
18219     * scrolling operation to consume some or all of the scroll operation before the child view
18220     * consumes it.</p>
18221     *
18222     * @param dx Horizontal scroll distance in pixels
18223     * @param dy Vertical scroll distance in pixels
18224     * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx
18225     *                 and consumed[1] the consumed dy.
18226     * @param offsetInWindow Optional. If not null, on return this will contain the offset
18227     *                       in local view coordinates of this view from before this operation
18228     *                       to after it completes. View implementations may use this to adjust
18229     *                       expected input coordinate tracking.
18230     * @return true if the parent consumed some or all of the scroll delta
18231     * @see #dispatchNestedScroll(int, int, int, int, int[])
18232     */
18233    public boolean dispatchNestedPreScroll(int dx, int dy, int[] consumed, int[] offsetInWindow) {
18234        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
18235            if (dx != 0 || dy != 0) {
18236                int startX = 0;
18237                int startY = 0;
18238                if (offsetInWindow != null) {
18239                    getLocationInWindow(offsetInWindow);
18240                    startX = offsetInWindow[0];
18241                    startY = offsetInWindow[1];
18242                }
18243
18244                if (consumed == null) {
18245                    if (mTempNestedScrollConsumed == null) {
18246                        mTempNestedScrollConsumed = new int[2];
18247                    }
18248                    consumed = mTempNestedScrollConsumed;
18249                }
18250                consumed[0] = 0;
18251                consumed[1] = 0;
18252                mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed);
18253
18254                if (offsetInWindow != null) {
18255                    getLocationInWindow(offsetInWindow);
18256                    offsetInWindow[0] -= startX;
18257                    offsetInWindow[1] -= startY;
18258                }
18259                return consumed[0] != 0 || consumed[1] != 0;
18260            } else if (offsetInWindow != null) {
18261                offsetInWindow[0] = 0;
18262                offsetInWindow[1] = 0;
18263            }
18264        }
18265        return false;
18266    }
18267
18268    /**
18269     * Dispatch a fling to a nested scrolling parent.
18270     *
18271     * <p>This method should be used to indicate that a nested scrolling child has detected
18272     * suitable conditions for a fling. Generally this means that a touch scroll has ended with a
18273     * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds
18274     * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity}
18275     * along a scrollable axis.</p>
18276     *
18277     * <p>If a nested scrolling child view would normally fling but it is at the edge of
18278     * its own content, it can use this method to delegate the fling to its nested scrolling
18279     * parent instead. The parent may optionally consume the fling or observe a child fling.</p>
18280     *
18281     * @param velocityX Horizontal fling velocity in pixels per second
18282     * @param velocityY Vertical fling velocity in pixels per second
18283     * @param consumed true if the child consumed the fling, false otherwise
18284     * @return true if the nested scrolling parent consumed or otherwise reacted to the fling
18285     */
18286    public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) {
18287        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
18288            return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed);
18289        }
18290        return false;
18291    }
18292
18293    /**
18294     * Gets a scale factor that determines the distance the view should scroll
18295     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
18296     * @return The vertical scroll scale factor.
18297     * @hide
18298     */
18299    protected float getVerticalScrollFactor() {
18300        if (mVerticalScrollFactor == 0) {
18301            TypedValue outValue = new TypedValue();
18302            if (!mContext.getTheme().resolveAttribute(
18303                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
18304                throw new IllegalStateException(
18305                        "Expected theme to define listPreferredItemHeight.");
18306            }
18307            mVerticalScrollFactor = outValue.getDimension(
18308                    mContext.getResources().getDisplayMetrics());
18309        }
18310        return mVerticalScrollFactor;
18311    }
18312
18313    /**
18314     * Gets a scale factor that determines the distance the view should scroll
18315     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
18316     * @return The horizontal scroll scale factor.
18317     * @hide
18318     */
18319    protected float getHorizontalScrollFactor() {
18320        // TODO: Should use something else.
18321        return getVerticalScrollFactor();
18322    }
18323
18324    /**
18325     * Return the value specifying the text direction or policy that was set with
18326     * {@link #setTextDirection(int)}.
18327     *
18328     * @return the defined text direction. It can be one of:
18329     *
18330     * {@link #TEXT_DIRECTION_INHERIT},
18331     * {@link #TEXT_DIRECTION_FIRST_STRONG}
18332     * {@link #TEXT_DIRECTION_ANY_RTL},
18333     * {@link #TEXT_DIRECTION_LTR},
18334     * {@link #TEXT_DIRECTION_RTL},
18335     * {@link #TEXT_DIRECTION_LOCALE}
18336     *
18337     * @attr ref android.R.styleable#View_textDirection
18338     *
18339     * @hide
18340     */
18341    @ViewDebug.ExportedProperty(category = "text", mapping = {
18342            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
18343            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
18344            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
18345            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
18346            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
18347            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
18348    })
18349    public int getRawTextDirection() {
18350        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
18351    }
18352
18353    /**
18354     * Set the text direction.
18355     *
18356     * @param textDirection the direction to set. Should be one of:
18357     *
18358     * {@link #TEXT_DIRECTION_INHERIT},
18359     * {@link #TEXT_DIRECTION_FIRST_STRONG}
18360     * {@link #TEXT_DIRECTION_ANY_RTL},
18361     * {@link #TEXT_DIRECTION_LTR},
18362     * {@link #TEXT_DIRECTION_RTL},
18363     * {@link #TEXT_DIRECTION_LOCALE}
18364     *
18365     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
18366     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
18367     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
18368     *
18369     * @attr ref android.R.styleable#View_textDirection
18370     */
18371    public void setTextDirection(int textDirection) {
18372        if (getRawTextDirection() != textDirection) {
18373            // Reset the current text direction and the resolved one
18374            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
18375            resetResolvedTextDirection();
18376            // Set the new text direction
18377            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
18378            // Do resolution
18379            resolveTextDirection();
18380            // Notify change
18381            onRtlPropertiesChanged(getLayoutDirection());
18382            // Refresh
18383            requestLayout();
18384            invalidate(true);
18385        }
18386    }
18387
18388    /**
18389     * Return the resolved text direction.
18390     *
18391     * @return the resolved text direction. Returns one of:
18392     *
18393     * {@link #TEXT_DIRECTION_FIRST_STRONG}
18394     * {@link #TEXT_DIRECTION_ANY_RTL},
18395     * {@link #TEXT_DIRECTION_LTR},
18396     * {@link #TEXT_DIRECTION_RTL},
18397     * {@link #TEXT_DIRECTION_LOCALE}
18398     *
18399     * @attr ref android.R.styleable#View_textDirection
18400     */
18401    @ViewDebug.ExportedProperty(category = "text", mapping = {
18402            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
18403            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
18404            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
18405            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
18406            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
18407            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
18408    })
18409    public int getTextDirection() {
18410        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
18411    }
18412
18413    /**
18414     * Resolve the text direction.
18415     *
18416     * @return true if resolution has been done, false otherwise.
18417     *
18418     * @hide
18419     */
18420    public boolean resolveTextDirection() {
18421        // Reset any previous text direction resolution
18422        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
18423
18424        if (hasRtlSupport()) {
18425            // Set resolved text direction flag depending on text direction flag
18426            final int textDirection = getRawTextDirection();
18427            switch(textDirection) {
18428                case TEXT_DIRECTION_INHERIT:
18429                    if (!canResolveTextDirection()) {
18430                        // We cannot do the resolution if there is no parent, so use the default one
18431                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18432                        // Resolution will need to happen again later
18433                        return false;
18434                    }
18435
18436                    // Parent has not yet resolved, so we still return the default
18437                    try {
18438                        if (!mParent.isTextDirectionResolved()) {
18439                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18440                            // Resolution will need to happen again later
18441                            return false;
18442                        }
18443                    } catch (AbstractMethodError e) {
18444                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18445                                " does not fully implement ViewParent", e);
18446                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED |
18447                                PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18448                        return true;
18449                    }
18450
18451                    // Set current resolved direction to the same value as the parent's one
18452                    int parentResolvedDirection;
18453                    try {
18454                        parentResolvedDirection = mParent.getTextDirection();
18455                    } catch (AbstractMethodError e) {
18456                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18457                                " does not fully implement ViewParent", e);
18458                        parentResolvedDirection = TEXT_DIRECTION_LTR;
18459                    }
18460                    switch (parentResolvedDirection) {
18461                        case TEXT_DIRECTION_FIRST_STRONG:
18462                        case TEXT_DIRECTION_ANY_RTL:
18463                        case TEXT_DIRECTION_LTR:
18464                        case TEXT_DIRECTION_RTL:
18465                        case TEXT_DIRECTION_LOCALE:
18466                            mPrivateFlags2 |=
18467                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
18468                            break;
18469                        default:
18470                            // Default resolved direction is "first strong" heuristic
18471                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18472                    }
18473                    break;
18474                case TEXT_DIRECTION_FIRST_STRONG:
18475                case TEXT_DIRECTION_ANY_RTL:
18476                case TEXT_DIRECTION_LTR:
18477                case TEXT_DIRECTION_RTL:
18478                case TEXT_DIRECTION_LOCALE:
18479                    // Resolved direction is the same as text direction
18480                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
18481                    break;
18482                default:
18483                    // Default resolved direction is "first strong" heuristic
18484                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18485            }
18486        } else {
18487            // Default resolved direction is "first strong" heuristic
18488            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18489        }
18490
18491        // Set to resolved
18492        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
18493        return true;
18494    }
18495
18496    /**
18497     * Check if text direction resolution can be done.
18498     *
18499     * @return true if text direction resolution can be done otherwise return false.
18500     */
18501    public boolean canResolveTextDirection() {
18502        switch (getRawTextDirection()) {
18503            case TEXT_DIRECTION_INHERIT:
18504                if (mParent != null) {
18505                    try {
18506                        return mParent.canResolveTextDirection();
18507                    } catch (AbstractMethodError e) {
18508                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18509                                " does not fully implement ViewParent", e);
18510                    }
18511                }
18512                return false;
18513
18514            default:
18515                return true;
18516        }
18517    }
18518
18519    /**
18520     * Reset resolved text direction. Text direction will be resolved during a call to
18521     * {@link #onMeasure(int, int)}.
18522     *
18523     * @hide
18524     */
18525    public void resetResolvedTextDirection() {
18526        // Reset any previous text direction resolution
18527        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
18528        // Set to default value
18529        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18530    }
18531
18532    /**
18533     * @return true if text direction is inherited.
18534     *
18535     * @hide
18536     */
18537    public boolean isTextDirectionInherited() {
18538        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
18539    }
18540
18541    /**
18542     * @return true if text direction is resolved.
18543     */
18544    public boolean isTextDirectionResolved() {
18545        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
18546    }
18547
18548    /**
18549     * Return the value specifying the text alignment or policy that was set with
18550     * {@link #setTextAlignment(int)}.
18551     *
18552     * @return the defined text alignment. It can be one of:
18553     *
18554     * {@link #TEXT_ALIGNMENT_INHERIT},
18555     * {@link #TEXT_ALIGNMENT_GRAVITY},
18556     * {@link #TEXT_ALIGNMENT_CENTER},
18557     * {@link #TEXT_ALIGNMENT_TEXT_START},
18558     * {@link #TEXT_ALIGNMENT_TEXT_END},
18559     * {@link #TEXT_ALIGNMENT_VIEW_START},
18560     * {@link #TEXT_ALIGNMENT_VIEW_END}
18561     *
18562     * @attr ref android.R.styleable#View_textAlignment
18563     *
18564     * @hide
18565     */
18566    @ViewDebug.ExportedProperty(category = "text", mapping = {
18567            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
18568            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
18569            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
18570            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
18571            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
18572            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
18573            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
18574    })
18575    @TextAlignment
18576    public int getRawTextAlignment() {
18577        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
18578    }
18579
18580    /**
18581     * Set the text alignment.
18582     *
18583     * @param textAlignment The text alignment to set. Should be one of
18584     *
18585     * {@link #TEXT_ALIGNMENT_INHERIT},
18586     * {@link #TEXT_ALIGNMENT_GRAVITY},
18587     * {@link #TEXT_ALIGNMENT_CENTER},
18588     * {@link #TEXT_ALIGNMENT_TEXT_START},
18589     * {@link #TEXT_ALIGNMENT_TEXT_END},
18590     * {@link #TEXT_ALIGNMENT_VIEW_START},
18591     * {@link #TEXT_ALIGNMENT_VIEW_END}
18592     *
18593     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
18594     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
18595     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
18596     *
18597     * @attr ref android.R.styleable#View_textAlignment
18598     */
18599    public void setTextAlignment(@TextAlignment int textAlignment) {
18600        if (textAlignment != getRawTextAlignment()) {
18601            // Reset the current and resolved text alignment
18602            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
18603            resetResolvedTextAlignment();
18604            // Set the new text alignment
18605            mPrivateFlags2 |=
18606                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
18607            // Do resolution
18608            resolveTextAlignment();
18609            // Notify change
18610            onRtlPropertiesChanged(getLayoutDirection());
18611            // Refresh
18612            requestLayout();
18613            invalidate(true);
18614        }
18615    }
18616
18617    /**
18618     * Return the resolved text alignment.
18619     *
18620     * @return the resolved text alignment. Returns one of:
18621     *
18622     * {@link #TEXT_ALIGNMENT_GRAVITY},
18623     * {@link #TEXT_ALIGNMENT_CENTER},
18624     * {@link #TEXT_ALIGNMENT_TEXT_START},
18625     * {@link #TEXT_ALIGNMENT_TEXT_END},
18626     * {@link #TEXT_ALIGNMENT_VIEW_START},
18627     * {@link #TEXT_ALIGNMENT_VIEW_END}
18628     *
18629     * @attr ref android.R.styleable#View_textAlignment
18630     */
18631    @ViewDebug.ExportedProperty(category = "text", mapping = {
18632            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
18633            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
18634            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
18635            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
18636            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
18637            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
18638            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
18639    })
18640    @TextAlignment
18641    public int getTextAlignment() {
18642        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
18643                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
18644    }
18645
18646    /**
18647     * Resolve the text alignment.
18648     *
18649     * @return true if resolution has been done, false otherwise.
18650     *
18651     * @hide
18652     */
18653    public boolean resolveTextAlignment() {
18654        // Reset any previous text alignment resolution
18655        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
18656
18657        if (hasRtlSupport()) {
18658            // Set resolved text alignment flag depending on text alignment flag
18659            final int textAlignment = getRawTextAlignment();
18660            switch (textAlignment) {
18661                case TEXT_ALIGNMENT_INHERIT:
18662                    // Check if we can resolve the text alignment
18663                    if (!canResolveTextAlignment()) {
18664                        // We cannot do the resolution if there is no parent so use the default
18665                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18666                        // Resolution will need to happen again later
18667                        return false;
18668                    }
18669
18670                    // Parent has not yet resolved, so we still return the default
18671                    try {
18672                        if (!mParent.isTextAlignmentResolved()) {
18673                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18674                            // Resolution will need to happen again later
18675                            return false;
18676                        }
18677                    } catch (AbstractMethodError e) {
18678                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18679                                " does not fully implement ViewParent", e);
18680                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED |
18681                                PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18682                        return true;
18683                    }
18684
18685                    int parentResolvedTextAlignment;
18686                    try {
18687                        parentResolvedTextAlignment = mParent.getTextAlignment();
18688                    } catch (AbstractMethodError e) {
18689                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18690                                " does not fully implement ViewParent", e);
18691                        parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY;
18692                    }
18693                    switch (parentResolvedTextAlignment) {
18694                        case TEXT_ALIGNMENT_GRAVITY:
18695                        case TEXT_ALIGNMENT_TEXT_START:
18696                        case TEXT_ALIGNMENT_TEXT_END:
18697                        case TEXT_ALIGNMENT_CENTER:
18698                        case TEXT_ALIGNMENT_VIEW_START:
18699                        case TEXT_ALIGNMENT_VIEW_END:
18700                            // Resolved text alignment is the same as the parent resolved
18701                            // text alignment
18702                            mPrivateFlags2 |=
18703                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
18704                            break;
18705                        default:
18706                            // Use default resolved text alignment
18707                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18708                    }
18709                    break;
18710                case TEXT_ALIGNMENT_GRAVITY:
18711                case TEXT_ALIGNMENT_TEXT_START:
18712                case TEXT_ALIGNMENT_TEXT_END:
18713                case TEXT_ALIGNMENT_CENTER:
18714                case TEXT_ALIGNMENT_VIEW_START:
18715                case TEXT_ALIGNMENT_VIEW_END:
18716                    // Resolved text alignment is the same as text alignment
18717                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
18718                    break;
18719                default:
18720                    // Use default resolved text alignment
18721                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18722            }
18723        } else {
18724            // Use default resolved text alignment
18725            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18726        }
18727
18728        // Set the resolved
18729        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
18730        return true;
18731    }
18732
18733    /**
18734     * Check if text alignment resolution can be done.
18735     *
18736     * @return true if text alignment resolution can be done otherwise return false.
18737     */
18738    public boolean canResolveTextAlignment() {
18739        switch (getRawTextAlignment()) {
18740            case TEXT_DIRECTION_INHERIT:
18741                if (mParent != null) {
18742                    try {
18743                        return mParent.canResolveTextAlignment();
18744                    } catch (AbstractMethodError e) {
18745                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18746                                " does not fully implement ViewParent", e);
18747                    }
18748                }
18749                return false;
18750
18751            default:
18752                return true;
18753        }
18754    }
18755
18756    /**
18757     * Reset resolved text alignment. Text alignment will be resolved during a call to
18758     * {@link #onMeasure(int, int)}.
18759     *
18760     * @hide
18761     */
18762    public void resetResolvedTextAlignment() {
18763        // Reset any previous text alignment resolution
18764        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
18765        // Set to default
18766        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18767    }
18768
18769    /**
18770     * @return true if text alignment is inherited.
18771     *
18772     * @hide
18773     */
18774    public boolean isTextAlignmentInherited() {
18775        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
18776    }
18777
18778    /**
18779     * @return true if text alignment is resolved.
18780     */
18781    public boolean isTextAlignmentResolved() {
18782        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
18783    }
18784
18785    /**
18786     * Generate a value suitable for use in {@link #setId(int)}.
18787     * This value will not collide with ID values generated at build time by aapt for R.id.
18788     *
18789     * @return a generated ID value
18790     */
18791    public static int generateViewId() {
18792        for (;;) {
18793            final int result = sNextGeneratedId.get();
18794            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
18795            int newValue = result + 1;
18796            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
18797            if (sNextGeneratedId.compareAndSet(result, newValue)) {
18798                return result;
18799            }
18800        }
18801    }
18802
18803    /**
18804     * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions.
18805     * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and
18806     *                           a normal View or a ViewGroup with
18807     *                           {@link android.view.ViewGroup#isTransitionGroup()} true.
18808     * @hide
18809     */
18810    public void captureTransitioningViews(List<View> transitioningViews) {
18811        if (getVisibility() == View.VISIBLE) {
18812            transitioningViews.add(this);
18813        }
18814    }
18815
18816    /**
18817     * Adds all Views that have {@link #getViewName()} non-null to namedElements.
18818     * @param namedElements Will contain all Views in the hierarchy having a view name.
18819     * @hide
18820     */
18821    public void findNamedViews(Map<String, View> namedElements) {
18822        if (getVisibility() == VISIBLE) {
18823            String viewName = getViewName();
18824            if (viewName != null) {
18825                namedElements.put(viewName, this);
18826            }
18827        }
18828    }
18829
18830    //
18831    // Properties
18832    //
18833    /**
18834     * A Property wrapper around the <code>alpha</code> functionality handled by the
18835     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
18836     */
18837    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
18838        @Override
18839        public void setValue(View object, float value) {
18840            object.setAlpha(value);
18841        }
18842
18843        @Override
18844        public Float get(View object) {
18845            return object.getAlpha();
18846        }
18847    };
18848
18849    /**
18850     * A Property wrapper around the <code>translationX</code> functionality handled by the
18851     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
18852     */
18853    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
18854        @Override
18855        public void setValue(View object, float value) {
18856            object.setTranslationX(value);
18857        }
18858
18859                @Override
18860        public Float get(View object) {
18861            return object.getTranslationX();
18862        }
18863    };
18864
18865    /**
18866     * A Property wrapper around the <code>translationY</code> functionality handled by the
18867     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
18868     */
18869    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
18870        @Override
18871        public void setValue(View object, float value) {
18872            object.setTranslationY(value);
18873        }
18874
18875        @Override
18876        public Float get(View object) {
18877            return object.getTranslationY();
18878        }
18879    };
18880
18881    /**
18882     * A Property wrapper around the <code>translationZ</code> functionality handled by the
18883     * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods.
18884     */
18885    public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") {
18886        @Override
18887        public void setValue(View object, float value) {
18888            object.setTranslationZ(value);
18889        }
18890
18891        @Override
18892        public Float get(View object) {
18893            return object.getTranslationZ();
18894        }
18895    };
18896
18897    /**
18898     * A Property wrapper around the <code>x</code> functionality handled by the
18899     * {@link View#setX(float)} and {@link View#getX()} methods.
18900     */
18901    public static final Property<View, Float> X = new FloatProperty<View>("x") {
18902        @Override
18903        public void setValue(View object, float value) {
18904            object.setX(value);
18905        }
18906
18907        @Override
18908        public Float get(View object) {
18909            return object.getX();
18910        }
18911    };
18912
18913    /**
18914     * A Property wrapper around the <code>y</code> functionality handled by the
18915     * {@link View#setY(float)} and {@link View#getY()} methods.
18916     */
18917    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
18918        @Override
18919        public void setValue(View object, float value) {
18920            object.setY(value);
18921        }
18922
18923        @Override
18924        public Float get(View object) {
18925            return object.getY();
18926        }
18927    };
18928
18929    /**
18930     * A Property wrapper around the <code>z</code> functionality handled by the
18931     * {@link View#setZ(float)} and {@link View#getZ()} methods.
18932     */
18933    public static final Property<View, Float> Z = new FloatProperty<View>("z") {
18934        @Override
18935        public void setValue(View object, float value) {
18936            object.setZ(value);
18937        }
18938
18939        @Override
18940        public Float get(View object) {
18941            return object.getZ();
18942        }
18943    };
18944
18945    /**
18946     * A Property wrapper around the <code>rotation</code> functionality handled by the
18947     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
18948     */
18949    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
18950        @Override
18951        public void setValue(View object, float value) {
18952            object.setRotation(value);
18953        }
18954
18955        @Override
18956        public Float get(View object) {
18957            return object.getRotation();
18958        }
18959    };
18960
18961    /**
18962     * A Property wrapper around the <code>rotationX</code> functionality handled by the
18963     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
18964     */
18965    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
18966        @Override
18967        public void setValue(View object, float value) {
18968            object.setRotationX(value);
18969        }
18970
18971        @Override
18972        public Float get(View object) {
18973            return object.getRotationX();
18974        }
18975    };
18976
18977    /**
18978     * A Property wrapper around the <code>rotationY</code> functionality handled by the
18979     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
18980     */
18981    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
18982        @Override
18983        public void setValue(View object, float value) {
18984            object.setRotationY(value);
18985        }
18986
18987        @Override
18988        public Float get(View object) {
18989            return object.getRotationY();
18990        }
18991    };
18992
18993    /**
18994     * A Property wrapper around the <code>scaleX</code> functionality handled by the
18995     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
18996     */
18997    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
18998        @Override
18999        public void setValue(View object, float value) {
19000            object.setScaleX(value);
19001        }
19002
19003        @Override
19004        public Float get(View object) {
19005            return object.getScaleX();
19006        }
19007    };
19008
19009    /**
19010     * A Property wrapper around the <code>scaleY</code> functionality handled by the
19011     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
19012     */
19013    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
19014        @Override
19015        public void setValue(View object, float value) {
19016            object.setScaleY(value);
19017        }
19018
19019        @Override
19020        public Float get(View object) {
19021            return object.getScaleY();
19022        }
19023    };
19024
19025    /**
19026     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
19027     * Each MeasureSpec represents a requirement for either the width or the height.
19028     * A MeasureSpec is comprised of a size and a mode. There are three possible
19029     * modes:
19030     * <dl>
19031     * <dt>UNSPECIFIED</dt>
19032     * <dd>
19033     * The parent has not imposed any constraint on the child. It can be whatever size
19034     * it wants.
19035     * </dd>
19036     *
19037     * <dt>EXACTLY</dt>
19038     * <dd>
19039     * The parent has determined an exact size for the child. The child is going to be
19040     * given those bounds regardless of how big it wants to be.
19041     * </dd>
19042     *
19043     * <dt>AT_MOST</dt>
19044     * <dd>
19045     * The child can be as large as it wants up to the specified size.
19046     * </dd>
19047     * </dl>
19048     *
19049     * MeasureSpecs are implemented as ints to reduce object allocation. This class
19050     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
19051     */
19052    public static class MeasureSpec {
19053        private static final int MODE_SHIFT = 30;
19054        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
19055
19056        /**
19057         * Measure specification mode: The parent has not imposed any constraint
19058         * on the child. It can be whatever size it wants.
19059         */
19060        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
19061
19062        /**
19063         * Measure specification mode: The parent has determined an exact size
19064         * for the child. The child is going to be given those bounds regardless
19065         * of how big it wants to be.
19066         */
19067        public static final int EXACTLY     = 1 << MODE_SHIFT;
19068
19069        /**
19070         * Measure specification mode: The child can be as large as it wants up
19071         * to the specified size.
19072         */
19073        public static final int AT_MOST     = 2 << MODE_SHIFT;
19074
19075        /**
19076         * Creates a measure specification based on the supplied size and mode.
19077         *
19078         * The mode must always be one of the following:
19079         * <ul>
19080         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
19081         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
19082         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
19083         * </ul>
19084         *
19085         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
19086         * implementation was such that the order of arguments did not matter
19087         * and overflow in either value could impact the resulting MeasureSpec.
19088         * {@link android.widget.RelativeLayout} was affected by this bug.
19089         * Apps targeting API levels greater than 17 will get the fixed, more strict
19090         * behavior.</p>
19091         *
19092         * @param size the size of the measure specification
19093         * @param mode the mode of the measure specification
19094         * @return the measure specification based on size and mode
19095         */
19096        public static int makeMeasureSpec(int size, int mode) {
19097            if (sUseBrokenMakeMeasureSpec) {
19098                return size + mode;
19099            } else {
19100                return (size & ~MODE_MASK) | (mode & MODE_MASK);
19101            }
19102        }
19103
19104        /**
19105         * Extracts the mode from the supplied measure specification.
19106         *
19107         * @param measureSpec the measure specification to extract the mode from
19108         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
19109         *         {@link android.view.View.MeasureSpec#AT_MOST} or
19110         *         {@link android.view.View.MeasureSpec#EXACTLY}
19111         */
19112        public static int getMode(int measureSpec) {
19113            return (measureSpec & MODE_MASK);
19114        }
19115
19116        /**
19117         * Extracts the size from the supplied measure specification.
19118         *
19119         * @param measureSpec the measure specification to extract the size from
19120         * @return the size in pixels defined in the supplied measure specification
19121         */
19122        public static int getSize(int measureSpec) {
19123            return (measureSpec & ~MODE_MASK);
19124        }
19125
19126        static int adjust(int measureSpec, int delta) {
19127            final int mode = getMode(measureSpec);
19128            if (mode == UNSPECIFIED) {
19129                // No need to adjust size for UNSPECIFIED mode.
19130                return makeMeasureSpec(0, UNSPECIFIED);
19131            }
19132            int size = getSize(measureSpec) + delta;
19133            if (size < 0) {
19134                Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size +
19135                        ") spec: " + toString(measureSpec) + " delta: " + delta);
19136                size = 0;
19137            }
19138            return makeMeasureSpec(size, mode);
19139        }
19140
19141        /**
19142         * Returns a String representation of the specified measure
19143         * specification.
19144         *
19145         * @param measureSpec the measure specification to convert to a String
19146         * @return a String with the following format: "MeasureSpec: MODE SIZE"
19147         */
19148        public static String toString(int measureSpec) {
19149            int mode = getMode(measureSpec);
19150            int size = getSize(measureSpec);
19151
19152            StringBuilder sb = new StringBuilder("MeasureSpec: ");
19153
19154            if (mode == UNSPECIFIED)
19155                sb.append("UNSPECIFIED ");
19156            else if (mode == EXACTLY)
19157                sb.append("EXACTLY ");
19158            else if (mode == AT_MOST)
19159                sb.append("AT_MOST ");
19160            else
19161                sb.append(mode).append(" ");
19162
19163            sb.append(size);
19164            return sb.toString();
19165        }
19166    }
19167
19168    private final class CheckForLongPress implements Runnable {
19169        private int mOriginalWindowAttachCount;
19170
19171        @Override
19172        public void run() {
19173            if (isPressed() && (mParent != null)
19174                    && mOriginalWindowAttachCount == mWindowAttachCount) {
19175                if (performLongClick()) {
19176                    mHasPerformedLongPress = true;
19177                }
19178            }
19179        }
19180
19181        public void rememberWindowAttachCount() {
19182            mOriginalWindowAttachCount = mWindowAttachCount;
19183        }
19184    }
19185
19186    private final class CheckForTap implements Runnable {
19187        public float x;
19188        public float y;
19189
19190        @Override
19191        public void run() {
19192            mPrivateFlags &= ~PFLAG_PREPRESSED;
19193            setPressed(true, x, y);
19194            checkForLongClick(ViewConfiguration.getTapTimeout());
19195        }
19196    }
19197
19198    private final class PerformClick implements Runnable {
19199        @Override
19200        public void run() {
19201            performClick();
19202        }
19203    }
19204
19205    /** @hide */
19206    public void hackTurnOffWindowResizeAnim(boolean off) {
19207        mAttachInfo.mTurnOffWindowResizeAnim = off;
19208    }
19209
19210    /**
19211     * This method returns a ViewPropertyAnimator object, which can be used to animate
19212     * specific properties on this View.
19213     *
19214     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
19215     */
19216    public ViewPropertyAnimator animate() {
19217        if (mAnimator == null) {
19218            mAnimator = new ViewPropertyAnimator(this);
19219        }
19220        return mAnimator;
19221    }
19222
19223    /**
19224     * Sets the name of the View to be used to identify Views in Transitions.
19225     * Names should be unique in the View hierarchy.
19226     *
19227     * @param viewName The name of the View to uniquely identify it for Transitions.
19228     */
19229    public final void setViewName(String viewName) {
19230        mViewName = viewName;
19231    }
19232
19233    /**
19234     * Returns the name of the View to be used to identify Views in Transitions.
19235     * Names should be unique in the View hierarchy.
19236     *
19237     * <p>This returns null if the View has not been given a name.</p>
19238     *
19239     * @return The name used of the View to be used to identify Views in Transitions or null
19240     * if no name has been given.
19241     */
19242    public String getViewName() {
19243        return mViewName;
19244    }
19245
19246    /**
19247     * Interface definition for a callback to be invoked when a hardware key event is
19248     * dispatched to this view. The callback will be invoked before the key event is
19249     * given to the view. This is only useful for hardware keyboards; a software input
19250     * method has no obligation to trigger this listener.
19251     */
19252    public interface OnKeyListener {
19253        /**
19254         * Called when a hardware key is dispatched to a view. This allows listeners to
19255         * get a chance to respond before the target view.
19256         * <p>Key presses in software keyboards will generally NOT trigger this method,
19257         * although some may elect to do so in some situations. Do not assume a
19258         * software input method has to be key-based; even if it is, it may use key presses
19259         * in a different way than you expect, so there is no way to reliably catch soft
19260         * input key presses.
19261         *
19262         * @param v The view the key has been dispatched to.
19263         * @param keyCode The code for the physical key that was pressed
19264         * @param event The KeyEvent object containing full information about
19265         *        the event.
19266         * @return True if the listener has consumed the event, false otherwise.
19267         */
19268        boolean onKey(View v, int keyCode, KeyEvent event);
19269    }
19270
19271    /**
19272     * Interface definition for a callback to be invoked when a touch event is
19273     * dispatched to this view. The callback will be invoked before the touch
19274     * event is given to the view.
19275     */
19276    public interface OnTouchListener {
19277        /**
19278         * Called when a touch event is dispatched to a view. This allows listeners to
19279         * get a chance to respond before the target view.
19280         *
19281         * @param v The view the touch event has been dispatched to.
19282         * @param event The MotionEvent object containing full information about
19283         *        the event.
19284         * @return True if the listener has consumed the event, false otherwise.
19285         */
19286        boolean onTouch(View v, MotionEvent event);
19287    }
19288
19289    /**
19290     * Interface definition for a callback to be invoked when a hover event is
19291     * dispatched to this view. The callback will be invoked before the hover
19292     * event is given to the view.
19293     */
19294    public interface OnHoverListener {
19295        /**
19296         * Called when a hover event is dispatched to a view. This allows listeners to
19297         * get a chance to respond before the target view.
19298         *
19299         * @param v The view the hover event has been dispatched to.
19300         * @param event The MotionEvent object containing full information about
19301         *        the event.
19302         * @return True if the listener has consumed the event, false otherwise.
19303         */
19304        boolean onHover(View v, MotionEvent event);
19305    }
19306
19307    /**
19308     * Interface definition for a callback to be invoked when a generic motion event is
19309     * dispatched to this view. The callback will be invoked before the generic motion
19310     * event is given to the view.
19311     */
19312    public interface OnGenericMotionListener {
19313        /**
19314         * Called when a generic motion event is dispatched to a view. This allows listeners to
19315         * get a chance to respond before the target view.
19316         *
19317         * @param v The view the generic motion event has been dispatched to.
19318         * @param event The MotionEvent object containing full information about
19319         *        the event.
19320         * @return True if the listener has consumed the event, false otherwise.
19321         */
19322        boolean onGenericMotion(View v, MotionEvent event);
19323    }
19324
19325    /**
19326     * Interface definition for a callback to be invoked when a view has been clicked and held.
19327     */
19328    public interface OnLongClickListener {
19329        /**
19330         * Called when a view has been clicked and held.
19331         *
19332         * @param v The view that was clicked and held.
19333         *
19334         * @return true if the callback consumed the long click, false otherwise.
19335         */
19336        boolean onLongClick(View v);
19337    }
19338
19339    /**
19340     * Interface definition for a callback to be invoked when a drag is being dispatched
19341     * to this view.  The callback will be invoked before the hosting view's own
19342     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
19343     * onDrag(event) behavior, it should return 'false' from this callback.
19344     *
19345     * <div class="special reference">
19346     * <h3>Developer Guides</h3>
19347     * <p>For a guide to implementing drag and drop features, read the
19348     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
19349     * </div>
19350     */
19351    public interface OnDragListener {
19352        /**
19353         * Called when a drag event is dispatched to a view. This allows listeners
19354         * to get a chance to override base View behavior.
19355         *
19356         * @param v The View that received the drag event.
19357         * @param event The {@link android.view.DragEvent} object for the drag event.
19358         * @return {@code true} if the drag event was handled successfully, or {@code false}
19359         * if the drag event was not handled. Note that {@code false} will trigger the View
19360         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
19361         */
19362        boolean onDrag(View v, DragEvent event);
19363    }
19364
19365    /**
19366     * Interface definition for a callback to be invoked when the focus state of
19367     * a view changed.
19368     */
19369    public interface OnFocusChangeListener {
19370        /**
19371         * Called when the focus state of a view has changed.
19372         *
19373         * @param v The view whose state has changed.
19374         * @param hasFocus The new focus state of v.
19375         */
19376        void onFocusChange(View v, boolean hasFocus);
19377    }
19378
19379    /**
19380     * Interface definition for a callback to be invoked when a view is clicked.
19381     */
19382    public interface OnClickListener {
19383        /**
19384         * Called when a view has been clicked.
19385         *
19386         * @param v The view that was clicked.
19387         */
19388        void onClick(View v);
19389    }
19390
19391    /**
19392     * Interface definition for a callback to be invoked when the context menu
19393     * for this view is being built.
19394     */
19395    public interface OnCreateContextMenuListener {
19396        /**
19397         * Called when the context menu for this view is being built. It is not
19398         * safe to hold onto the menu after this method returns.
19399         *
19400         * @param menu The context menu that is being built
19401         * @param v The view for which the context menu is being built
19402         * @param menuInfo Extra information about the item for which the
19403         *            context menu should be shown. This information will vary
19404         *            depending on the class of v.
19405         */
19406        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
19407    }
19408
19409    /**
19410     * Interface definition for a callback to be invoked when the status bar changes
19411     * visibility.  This reports <strong>global</strong> changes to the system UI
19412     * state, not what the application is requesting.
19413     *
19414     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
19415     */
19416    public interface OnSystemUiVisibilityChangeListener {
19417        /**
19418         * Called when the status bar changes visibility because of a call to
19419         * {@link View#setSystemUiVisibility(int)}.
19420         *
19421         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
19422         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
19423         * This tells you the <strong>global</strong> state of these UI visibility
19424         * flags, not what your app is currently applying.
19425         */
19426        public void onSystemUiVisibilityChange(int visibility);
19427    }
19428
19429    /**
19430     * Interface definition for a callback to be invoked when this view is attached
19431     * or detached from its window.
19432     */
19433    public interface OnAttachStateChangeListener {
19434        /**
19435         * Called when the view is attached to a window.
19436         * @param v The view that was attached
19437         */
19438        public void onViewAttachedToWindow(View v);
19439        /**
19440         * Called when the view is detached from a window.
19441         * @param v The view that was detached
19442         */
19443        public void onViewDetachedFromWindow(View v);
19444    }
19445
19446    /**
19447     * Listener for applying window insets on a view in a custom way.
19448     *
19449     * <p>Apps may choose to implement this interface if they want to apply custom policy
19450     * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener
19451     * is set, its
19452     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
19453     * method will be called instead of the View's own
19454     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener
19455     * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply
19456     * the View's normal behavior as part of its own.</p>
19457     */
19458    public interface OnApplyWindowInsetsListener {
19459        /**
19460         * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set}
19461         * on a View, this listener method will be called instead of the view's own
19462         * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
19463         *
19464         * @param v The view applying window insets
19465         * @param insets The insets to apply
19466         * @return The insets supplied, minus any insets that were consumed
19467         */
19468        public WindowInsets onApplyWindowInsets(View v, WindowInsets insets);
19469    }
19470
19471    private final class UnsetPressedState implements Runnable {
19472        @Override
19473        public void run() {
19474            setPressed(false);
19475        }
19476    }
19477
19478    /**
19479     * Base class for derived classes that want to save and restore their own
19480     * state in {@link android.view.View#onSaveInstanceState()}.
19481     */
19482    public static class BaseSavedState extends AbsSavedState {
19483        /**
19484         * Constructor used when reading from a parcel. Reads the state of the superclass.
19485         *
19486         * @param source
19487         */
19488        public BaseSavedState(Parcel source) {
19489            super(source);
19490        }
19491
19492        /**
19493         * Constructor called by derived classes when creating their SavedState objects
19494         *
19495         * @param superState The state of the superclass of this view
19496         */
19497        public BaseSavedState(Parcelable superState) {
19498            super(superState);
19499        }
19500
19501        public static final Parcelable.Creator<BaseSavedState> CREATOR =
19502                new Parcelable.Creator<BaseSavedState>() {
19503            public BaseSavedState createFromParcel(Parcel in) {
19504                return new BaseSavedState(in);
19505            }
19506
19507            public BaseSavedState[] newArray(int size) {
19508                return new BaseSavedState[size];
19509            }
19510        };
19511    }
19512
19513    /**
19514     * A set of information given to a view when it is attached to its parent
19515     * window.
19516     */
19517    final static class AttachInfo {
19518        interface Callbacks {
19519            void playSoundEffect(int effectId);
19520            boolean performHapticFeedback(int effectId, boolean always);
19521        }
19522
19523        /**
19524         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
19525         * to a Handler. This class contains the target (View) to invalidate and
19526         * the coordinates of the dirty rectangle.
19527         *
19528         * For performance purposes, this class also implements a pool of up to
19529         * POOL_LIMIT objects that get reused. This reduces memory allocations
19530         * whenever possible.
19531         */
19532        static class InvalidateInfo {
19533            private static final int POOL_LIMIT = 10;
19534
19535            private static final SynchronizedPool<InvalidateInfo> sPool =
19536                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
19537
19538            View target;
19539
19540            int left;
19541            int top;
19542            int right;
19543            int bottom;
19544
19545            public static InvalidateInfo obtain() {
19546                InvalidateInfo instance = sPool.acquire();
19547                return (instance != null) ? instance : new InvalidateInfo();
19548            }
19549
19550            public void recycle() {
19551                target = null;
19552                sPool.release(this);
19553            }
19554        }
19555
19556        final IWindowSession mSession;
19557
19558        final IWindow mWindow;
19559
19560        final IBinder mWindowToken;
19561
19562        final Display mDisplay;
19563
19564        final Callbacks mRootCallbacks;
19565
19566        IWindowId mIWindowId;
19567        WindowId mWindowId;
19568
19569        /**
19570         * The top view of the hierarchy.
19571         */
19572        View mRootView;
19573
19574        IBinder mPanelParentWindowToken;
19575
19576        boolean mHardwareAccelerated;
19577        boolean mHardwareAccelerationRequested;
19578        HardwareRenderer mHardwareRenderer;
19579
19580        /**
19581         * The state of the display to which the window is attached, as reported
19582         * by {@link Display#getState()}.  Note that the display state constants
19583         * declared by {@link Display} do not exactly line up with the screen state
19584         * constants declared by {@link View} (there are more display states than
19585         * screen states).
19586         */
19587        int mDisplayState = Display.STATE_UNKNOWN;
19588
19589        /**
19590         * Scale factor used by the compatibility mode
19591         */
19592        float mApplicationScale;
19593
19594        /**
19595         * Indicates whether the application is in compatibility mode
19596         */
19597        boolean mScalingRequired;
19598
19599        /**
19600         * If set, ViewRootImpl doesn't use its lame animation for when the window resizes.
19601         */
19602        boolean mTurnOffWindowResizeAnim;
19603
19604        /**
19605         * Left position of this view's window
19606         */
19607        int mWindowLeft;
19608
19609        /**
19610         * Top position of this view's window
19611         */
19612        int mWindowTop;
19613
19614        /**
19615         * Indicates whether views need to use 32-bit drawing caches
19616         */
19617        boolean mUse32BitDrawingCache;
19618
19619        /**
19620         * For windows that are full-screen but using insets to layout inside
19621         * of the screen areas, these are the current insets to appear inside
19622         * the overscan area of the display.
19623         */
19624        final Rect mOverscanInsets = new Rect();
19625
19626        /**
19627         * For windows that are full-screen but using insets to layout inside
19628         * of the screen decorations, these are the current insets for the
19629         * content of the window.
19630         */
19631        final Rect mContentInsets = new Rect();
19632
19633        /**
19634         * For windows that are full-screen but using insets to layout inside
19635         * of the screen decorations, these are the current insets for the
19636         * actual visible parts of the window.
19637         */
19638        final Rect mVisibleInsets = new Rect();
19639
19640        /**
19641         * The internal insets given by this window.  This value is
19642         * supplied by the client (through
19643         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
19644         * be given to the window manager when changed to be used in laying
19645         * out windows behind it.
19646         */
19647        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
19648                = new ViewTreeObserver.InternalInsetsInfo();
19649
19650        /**
19651         * Set to true when mGivenInternalInsets is non-empty.
19652         */
19653        boolean mHasNonEmptyGivenInternalInsets;
19654
19655        /**
19656         * All views in the window's hierarchy that serve as scroll containers,
19657         * used to determine if the window can be resized or must be panned
19658         * to adjust for a soft input area.
19659         */
19660        final ArrayList<View> mScrollContainers = new ArrayList<View>();
19661
19662        final KeyEvent.DispatcherState mKeyDispatchState
19663                = new KeyEvent.DispatcherState();
19664
19665        /**
19666         * Indicates whether the view's window currently has the focus.
19667         */
19668        boolean mHasWindowFocus;
19669
19670        /**
19671         * The current visibility of the window.
19672         */
19673        int mWindowVisibility;
19674
19675        /**
19676         * Indicates the time at which drawing started to occur.
19677         */
19678        long mDrawingTime;
19679
19680        /**
19681         * Indicates whether or not ignoring the DIRTY_MASK flags.
19682         */
19683        boolean mIgnoreDirtyState;
19684
19685        /**
19686         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
19687         * to avoid clearing that flag prematurely.
19688         */
19689        boolean mSetIgnoreDirtyState = false;
19690
19691        /**
19692         * Indicates whether the view's window is currently in touch mode.
19693         */
19694        boolean mInTouchMode;
19695
19696        /**
19697         * Indicates whether the view has requested unbuffered input dispatching for the current
19698         * event stream.
19699         */
19700        boolean mUnbufferedDispatchRequested;
19701
19702        /**
19703         * Indicates that ViewAncestor should trigger a global layout change
19704         * the next time it performs a traversal
19705         */
19706        boolean mRecomputeGlobalAttributes;
19707
19708        /**
19709         * Always report new attributes at next traversal.
19710         */
19711        boolean mForceReportNewAttributes;
19712
19713        /**
19714         * Set during a traveral if any views want to keep the screen on.
19715         */
19716        boolean mKeepScreenOn;
19717
19718        /**
19719         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
19720         */
19721        int mSystemUiVisibility;
19722
19723        /**
19724         * Hack to force certain system UI visibility flags to be cleared.
19725         */
19726        int mDisabledSystemUiVisibility;
19727
19728        /**
19729         * Last global system UI visibility reported by the window manager.
19730         */
19731        int mGlobalSystemUiVisibility;
19732
19733        /**
19734         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
19735         * attached.
19736         */
19737        boolean mHasSystemUiListeners;
19738
19739        /**
19740         * Set if the window has requested to extend into the overscan region
19741         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
19742         */
19743        boolean mOverscanRequested;
19744
19745        /**
19746         * Set if the visibility of any views has changed.
19747         */
19748        boolean mViewVisibilityChanged;
19749
19750        /**
19751         * Set to true if a view has been scrolled.
19752         */
19753        boolean mViewScrollChanged;
19754
19755        /**
19756         * Global to the view hierarchy used as a temporary for dealing with
19757         * x/y points in the transparent region computations.
19758         */
19759        final int[] mTransparentLocation = new int[2];
19760
19761        /**
19762         * Global to the view hierarchy used as a temporary for dealing with
19763         * x/y points in the ViewGroup.invalidateChild implementation.
19764         */
19765        final int[] mInvalidateChildLocation = new int[2];
19766
19767        /**
19768         * Global to the view hierarchy used as a temporary for dealng with
19769         * computing absolute on-screen location.
19770         */
19771        final int[] mTmpLocation = new int[2];
19772
19773        /**
19774         * Global to the view hierarchy used as a temporary for dealing with
19775         * x/y location when view is transformed.
19776         */
19777        final float[] mTmpTransformLocation = new float[2];
19778
19779        /**
19780         * The view tree observer used to dispatch global events like
19781         * layout, pre-draw, touch mode change, etc.
19782         */
19783        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
19784
19785        /**
19786         * A Canvas used by the view hierarchy to perform bitmap caching.
19787         */
19788        Canvas mCanvas;
19789
19790        /**
19791         * The view root impl.
19792         */
19793        final ViewRootImpl mViewRootImpl;
19794
19795        /**
19796         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
19797         * handler can be used to pump events in the UI events queue.
19798         */
19799        final Handler mHandler;
19800
19801        /**
19802         * Temporary for use in computing invalidate rectangles while
19803         * calling up the hierarchy.
19804         */
19805        final Rect mTmpInvalRect = new Rect();
19806
19807        /**
19808         * Temporary for use in computing hit areas with transformed views
19809         */
19810        final RectF mTmpTransformRect = new RectF();
19811
19812        /**
19813         * Temporary for use in transforming invalidation rect
19814         */
19815        final Matrix mTmpMatrix = new Matrix();
19816
19817        /**
19818         * Temporary for use in transforming invalidation rect
19819         */
19820        final Transformation mTmpTransformation = new Transformation();
19821
19822        /**
19823         * Temporary list for use in collecting focusable descendents of a view.
19824         */
19825        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
19826
19827        /**
19828         * The id of the window for accessibility purposes.
19829         */
19830        int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
19831
19832        /**
19833         * Flags related to accessibility processing.
19834         *
19835         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
19836         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
19837         */
19838        int mAccessibilityFetchFlags;
19839
19840        /**
19841         * The drawable for highlighting accessibility focus.
19842         */
19843        Drawable mAccessibilityFocusDrawable;
19844
19845        /**
19846         * Show where the margins, bounds and layout bounds are for each view.
19847         */
19848        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
19849
19850        /**
19851         * Point used to compute visible regions.
19852         */
19853        final Point mPoint = new Point();
19854
19855        /**
19856         * Used to track which View originated a requestLayout() call, used when
19857         * requestLayout() is called during layout.
19858         */
19859        View mViewRequestingLayout;
19860
19861        /**
19862         * Creates a new set of attachment information with the specified
19863         * events handler and thread.
19864         *
19865         * @param handler the events handler the view must use
19866         */
19867        AttachInfo(IWindowSession session, IWindow window, Display display,
19868                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
19869            mSession = session;
19870            mWindow = window;
19871            mWindowToken = window.asBinder();
19872            mDisplay = display;
19873            mViewRootImpl = viewRootImpl;
19874            mHandler = handler;
19875            mRootCallbacks = effectPlayer;
19876        }
19877    }
19878
19879    /**
19880     * <p>ScrollabilityCache holds various fields used by a View when scrolling
19881     * is supported. This avoids keeping too many unused fields in most
19882     * instances of View.</p>
19883     */
19884    private static class ScrollabilityCache implements Runnable {
19885
19886        /**
19887         * Scrollbars are not visible
19888         */
19889        public static final int OFF = 0;
19890
19891        /**
19892         * Scrollbars are visible
19893         */
19894        public static final int ON = 1;
19895
19896        /**
19897         * Scrollbars are fading away
19898         */
19899        public static final int FADING = 2;
19900
19901        public boolean fadeScrollBars;
19902
19903        public int fadingEdgeLength;
19904        public int scrollBarDefaultDelayBeforeFade;
19905        public int scrollBarFadeDuration;
19906
19907        public int scrollBarSize;
19908        public ScrollBarDrawable scrollBar;
19909        public float[] interpolatorValues;
19910        public View host;
19911
19912        public final Paint paint;
19913        public final Matrix matrix;
19914        public Shader shader;
19915
19916        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
19917
19918        private static final float[] OPAQUE = { 255 };
19919        private static final float[] TRANSPARENT = { 0.0f };
19920
19921        /**
19922         * When fading should start. This time moves into the future every time
19923         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
19924         */
19925        public long fadeStartTime;
19926
19927
19928        /**
19929         * The current state of the scrollbars: ON, OFF, or FADING
19930         */
19931        public int state = OFF;
19932
19933        private int mLastColor;
19934
19935        public ScrollabilityCache(ViewConfiguration configuration, View host) {
19936            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
19937            scrollBarSize = configuration.getScaledScrollBarSize();
19938            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
19939            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
19940
19941            paint = new Paint();
19942            matrix = new Matrix();
19943            // use use a height of 1, and then wack the matrix each time we
19944            // actually use it.
19945            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
19946            paint.setShader(shader);
19947            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
19948
19949            this.host = host;
19950        }
19951
19952        public void setFadeColor(int color) {
19953            if (color != mLastColor) {
19954                mLastColor = color;
19955
19956                if (color != 0) {
19957                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
19958                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
19959                    paint.setShader(shader);
19960                    // Restore the default transfer mode (src_over)
19961                    paint.setXfermode(null);
19962                } else {
19963                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
19964                    paint.setShader(shader);
19965                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
19966                }
19967            }
19968        }
19969
19970        public void run() {
19971            long now = AnimationUtils.currentAnimationTimeMillis();
19972            if (now >= fadeStartTime) {
19973
19974                // the animation fades the scrollbars out by changing
19975                // the opacity (alpha) from fully opaque to fully
19976                // transparent
19977                int nextFrame = (int) now;
19978                int framesCount = 0;
19979
19980                Interpolator interpolator = scrollBarInterpolator;
19981
19982                // Start opaque
19983                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
19984
19985                // End transparent
19986                nextFrame += scrollBarFadeDuration;
19987                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
19988
19989                state = FADING;
19990
19991                // Kick off the fade animation
19992                host.invalidate(true);
19993            }
19994        }
19995    }
19996
19997    /**
19998     * Resuable callback for sending
19999     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
20000     */
20001    private class SendViewScrolledAccessibilityEvent implements Runnable {
20002        public volatile boolean mIsPending;
20003
20004        public void run() {
20005            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
20006            mIsPending = false;
20007        }
20008    }
20009
20010    /**
20011     * <p>
20012     * This class represents a delegate that can be registered in a {@link View}
20013     * to enhance accessibility support via composition rather via inheritance.
20014     * It is specifically targeted to widget developers that extend basic View
20015     * classes i.e. classes in package android.view, that would like their
20016     * applications to be backwards compatible.
20017     * </p>
20018     * <div class="special reference">
20019     * <h3>Developer Guides</h3>
20020     * <p>For more information about making applications accessible, read the
20021     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
20022     * developer guide.</p>
20023     * </div>
20024     * <p>
20025     * A scenario in which a developer would like to use an accessibility delegate
20026     * is overriding a method introduced in a later API version then the minimal API
20027     * version supported by the application. For example, the method
20028     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
20029     * in API version 4 when the accessibility APIs were first introduced. If a
20030     * developer would like his application to run on API version 4 devices (assuming
20031     * all other APIs used by the application are version 4 or lower) and take advantage
20032     * of this method, instead of overriding the method which would break the application's
20033     * backwards compatibility, he can override the corresponding method in this
20034     * delegate and register the delegate in the target View if the API version of
20035     * the system is high enough i.e. the API version is same or higher to the API
20036     * version that introduced
20037     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
20038     * </p>
20039     * <p>
20040     * Here is an example implementation:
20041     * </p>
20042     * <code><pre><p>
20043     * if (Build.VERSION.SDK_INT >= 14) {
20044     *     // If the API version is equal of higher than the version in
20045     *     // which onInitializeAccessibilityNodeInfo was introduced we
20046     *     // register a delegate with a customized implementation.
20047     *     View view = findViewById(R.id.view_id);
20048     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
20049     *         public void onInitializeAccessibilityNodeInfo(View host,
20050     *                 AccessibilityNodeInfo info) {
20051     *             // Let the default implementation populate the info.
20052     *             super.onInitializeAccessibilityNodeInfo(host, info);
20053     *             // Set some other information.
20054     *             info.setEnabled(host.isEnabled());
20055     *         }
20056     *     });
20057     * }
20058     * </code></pre></p>
20059     * <p>
20060     * This delegate contains methods that correspond to the accessibility methods
20061     * in View. If a delegate has been specified the implementation in View hands
20062     * off handling to the corresponding method in this delegate. The default
20063     * implementation the delegate methods behaves exactly as the corresponding
20064     * method in View for the case of no accessibility delegate been set. Hence,
20065     * to customize the behavior of a View method, clients can override only the
20066     * corresponding delegate method without altering the behavior of the rest
20067     * accessibility related methods of the host view.
20068     * </p>
20069     */
20070    public static class AccessibilityDelegate {
20071
20072        /**
20073         * Sends an accessibility event of the given type. If accessibility is not
20074         * enabled this method has no effect.
20075         * <p>
20076         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
20077         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
20078         * been set.
20079         * </p>
20080         *
20081         * @param host The View hosting the delegate.
20082         * @param eventType The type of the event to send.
20083         *
20084         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
20085         */
20086        public void sendAccessibilityEvent(View host, int eventType) {
20087            host.sendAccessibilityEventInternal(eventType);
20088        }
20089
20090        /**
20091         * Performs the specified accessibility action on the view. For
20092         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
20093         * <p>
20094         * The default implementation behaves as
20095         * {@link View#performAccessibilityAction(int, Bundle)
20096         *  View#performAccessibilityAction(int, Bundle)} for the case of
20097         *  no accessibility delegate been set.
20098         * </p>
20099         *
20100         * @param action The action to perform.
20101         * @return Whether the action was performed.
20102         *
20103         * @see View#performAccessibilityAction(int, Bundle)
20104         *      View#performAccessibilityAction(int, Bundle)
20105         */
20106        public boolean performAccessibilityAction(View host, int action, Bundle args) {
20107            return host.performAccessibilityActionInternal(action, args);
20108        }
20109
20110        /**
20111         * Sends an accessibility event. This method behaves exactly as
20112         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
20113         * empty {@link AccessibilityEvent} and does not perform a check whether
20114         * accessibility is enabled.
20115         * <p>
20116         * The default implementation behaves as
20117         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
20118         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
20119         * the case of no accessibility delegate been set.
20120         * </p>
20121         *
20122         * @param host The View hosting the delegate.
20123         * @param event The event to send.
20124         *
20125         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
20126         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
20127         */
20128        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
20129            host.sendAccessibilityEventUncheckedInternal(event);
20130        }
20131
20132        /**
20133         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
20134         * to its children for adding their text content to the event.
20135         * <p>
20136         * The default implementation behaves as
20137         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
20138         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
20139         * the case of no accessibility delegate been set.
20140         * </p>
20141         *
20142         * @param host The View hosting the delegate.
20143         * @param event The event.
20144         * @return True if the event population was completed.
20145         *
20146         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
20147         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
20148         */
20149        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
20150            return host.dispatchPopulateAccessibilityEventInternal(event);
20151        }
20152
20153        /**
20154         * Gives a chance to the host View to populate the accessibility event with its
20155         * text content.
20156         * <p>
20157         * The default implementation behaves as
20158         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
20159         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
20160         * the case of no accessibility delegate been set.
20161         * </p>
20162         *
20163         * @param host The View hosting the delegate.
20164         * @param event The accessibility event which to populate.
20165         *
20166         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
20167         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
20168         */
20169        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
20170            host.onPopulateAccessibilityEventInternal(event);
20171        }
20172
20173        /**
20174         * Initializes an {@link AccessibilityEvent} with information about the
20175         * the host View which is the event source.
20176         * <p>
20177         * The default implementation behaves as
20178         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
20179         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
20180         * the case of no accessibility delegate been set.
20181         * </p>
20182         *
20183         * @param host The View hosting the delegate.
20184         * @param event The event to initialize.
20185         *
20186         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
20187         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
20188         */
20189        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
20190            host.onInitializeAccessibilityEventInternal(event);
20191        }
20192
20193        /**
20194         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
20195         * <p>
20196         * The default implementation behaves as
20197         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
20198         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
20199         * the case of no accessibility delegate been set.
20200         * </p>
20201         *
20202         * @param host The View hosting the delegate.
20203         * @param info The instance to initialize.
20204         *
20205         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
20206         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
20207         */
20208        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
20209            host.onInitializeAccessibilityNodeInfoInternal(info);
20210        }
20211
20212        /**
20213         * Called when a child of the host View has requested sending an
20214         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
20215         * to augment the event.
20216         * <p>
20217         * The default implementation behaves as
20218         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
20219         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
20220         * the case of no accessibility delegate been set.
20221         * </p>
20222         *
20223         * @param host The View hosting the delegate.
20224         * @param child The child which requests sending the event.
20225         * @param event The event to be sent.
20226         * @return True if the event should be sent
20227         *
20228         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
20229         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
20230         */
20231        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
20232                AccessibilityEvent event) {
20233            return host.onRequestSendAccessibilityEventInternal(child, event);
20234        }
20235
20236        /**
20237         * Gets the provider for managing a virtual view hierarchy rooted at this View
20238         * and reported to {@link android.accessibilityservice.AccessibilityService}s
20239         * that explore the window content.
20240         * <p>
20241         * The default implementation behaves as
20242         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
20243         * the case of no accessibility delegate been set.
20244         * </p>
20245         *
20246         * @return The provider.
20247         *
20248         * @see AccessibilityNodeProvider
20249         */
20250        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
20251            return null;
20252        }
20253
20254        /**
20255         * Returns an {@link AccessibilityNodeInfo} representing the host view from the
20256         * point of view of an {@link android.accessibilityservice.AccessibilityService}.
20257         * This method is responsible for obtaining an accessibility node info from a
20258         * pool of reusable instances and calling
20259         * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host
20260         * view to initialize the former.
20261         * <p>
20262         * <strong>Note:</strong> The client is responsible for recycling the obtained
20263         * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object
20264         * creation.
20265         * </p>
20266         * <p>
20267         * The default implementation behaves as
20268         * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for
20269         * the case of no accessibility delegate been set.
20270         * </p>
20271         * @return A populated {@link AccessibilityNodeInfo}.
20272         *
20273         * @see AccessibilityNodeInfo
20274         *
20275         * @hide
20276         */
20277        public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) {
20278            return host.createAccessibilityNodeInfoInternal();
20279        }
20280    }
20281
20282    private class MatchIdPredicate implements Predicate<View> {
20283        public int mId;
20284
20285        @Override
20286        public boolean apply(View view) {
20287            return (view.mID == mId);
20288        }
20289    }
20290
20291    private class MatchLabelForPredicate implements Predicate<View> {
20292        private int mLabeledId;
20293
20294        @Override
20295        public boolean apply(View view) {
20296            return (view.mLabelForId == mLabeledId);
20297        }
20298    }
20299
20300    private class SendViewStateChangedAccessibilityEvent implements Runnable {
20301        private int mChangeTypes = 0;
20302        private boolean mPosted;
20303        private boolean mPostedWithDelay;
20304        private long mLastEventTimeMillis;
20305
20306        @Override
20307        public void run() {
20308            mPosted = false;
20309            mPostedWithDelay = false;
20310            mLastEventTimeMillis = SystemClock.uptimeMillis();
20311            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
20312                final AccessibilityEvent event = AccessibilityEvent.obtain();
20313                event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
20314                event.setContentChangeTypes(mChangeTypes);
20315                sendAccessibilityEventUnchecked(event);
20316            }
20317            mChangeTypes = 0;
20318        }
20319
20320        public void runOrPost(int changeType) {
20321            mChangeTypes |= changeType;
20322
20323            // If this is a live region or the child of a live region, collect
20324            // all events from this frame and send them on the next frame.
20325            if (inLiveRegion()) {
20326                // If we're already posted with a delay, remove that.
20327                if (mPostedWithDelay) {
20328                    removeCallbacks(this);
20329                    mPostedWithDelay = false;
20330                }
20331                // Only post if we're not already posted.
20332                if (!mPosted) {
20333                    post(this);
20334                    mPosted = true;
20335                }
20336                return;
20337            }
20338
20339            if (mPosted) {
20340                return;
20341            }
20342            final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
20343            final long minEventIntevalMillis =
20344                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
20345            if (timeSinceLastMillis >= minEventIntevalMillis) {
20346                removeCallbacks(this);
20347                run();
20348            } else {
20349                postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
20350                mPosted = true;
20351                mPostedWithDelay = true;
20352            }
20353        }
20354    }
20355
20356    private boolean inLiveRegion() {
20357        if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) {
20358            return true;
20359        }
20360
20361        ViewParent parent = getParent();
20362        while (parent instanceof View) {
20363            if (((View) parent).getAccessibilityLiveRegion()
20364                    != View.ACCESSIBILITY_LIVE_REGION_NONE) {
20365                return true;
20366            }
20367            parent = parent.getParent();
20368        }
20369
20370        return false;
20371    }
20372
20373    /**
20374     * Dump all private flags in readable format, useful for documentation and
20375     * sanity checking.
20376     */
20377    private static void dumpFlags() {
20378        final HashMap<String, String> found = Maps.newHashMap();
20379        try {
20380            for (Field field : View.class.getDeclaredFields()) {
20381                final int modifiers = field.getModifiers();
20382                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
20383                    if (field.getType().equals(int.class)) {
20384                        final int value = field.getInt(null);
20385                        dumpFlag(found, field.getName(), value);
20386                    } else if (field.getType().equals(int[].class)) {
20387                        final int[] values = (int[]) field.get(null);
20388                        for (int i = 0; i < values.length; i++) {
20389                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
20390                        }
20391                    }
20392                }
20393            }
20394        } catch (IllegalAccessException e) {
20395            throw new RuntimeException(e);
20396        }
20397
20398        final ArrayList<String> keys = Lists.newArrayList();
20399        keys.addAll(found.keySet());
20400        Collections.sort(keys);
20401        for (String key : keys) {
20402            Log.d(VIEW_LOG_TAG, found.get(key));
20403        }
20404    }
20405
20406    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
20407        // Sort flags by prefix, then by bits, always keeping unique keys
20408        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
20409        final int prefix = name.indexOf('_');
20410        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
20411        final String output = bits + " " + name;
20412        found.put(key, output);
20413    }
20414}
20415