View.java revision d621e77c8dfc99d0c347ff4cef765e9809f51333
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.annotation.IntDef;
20import android.annotation.NonNull;
21import android.annotation.Nullable;
22import android.content.ClipData;
23import android.content.Context;
24import android.content.res.Configuration;
25import android.content.res.Resources;
26import android.content.res.TypedArray;
27import android.graphics.Bitmap;
28import android.graphics.Camera;
29import android.graphics.Canvas;
30import android.graphics.Insets;
31import android.graphics.Interpolator;
32import android.graphics.LinearGradient;
33import android.graphics.Matrix;
34import android.graphics.Paint;
35import android.graphics.Path;
36import android.graphics.PixelFormat;
37import android.graphics.Point;
38import android.graphics.PorterDuff;
39import android.graphics.PorterDuffXfermode;
40import android.graphics.Rect;
41import android.graphics.RectF;
42import android.graphics.Region;
43import android.graphics.Shader;
44import android.graphics.drawable.ColorDrawable;
45import android.graphics.drawable.Drawable;
46import android.hardware.display.DisplayManagerGlobal;
47import android.os.Bundle;
48import android.os.Handler;
49import android.os.IBinder;
50import android.os.Parcel;
51import android.os.Parcelable;
52import android.os.RemoteException;
53import android.os.SystemClock;
54import android.os.SystemProperties;
55import android.text.TextUtils;
56import android.util.AttributeSet;
57import android.util.FloatProperty;
58import android.util.LayoutDirection;
59import android.util.Log;
60import android.util.LongSparseLongArray;
61import android.util.Pools.SynchronizedPool;
62import android.util.Property;
63import android.util.SparseArray;
64import android.util.SuperNotCalledException;
65import android.util.TypedValue;
66import android.view.ContextMenu.ContextMenuInfo;
67import android.view.AccessibilityIterators.TextSegmentIterator;
68import android.view.AccessibilityIterators.CharacterTextSegmentIterator;
69import android.view.AccessibilityIterators.WordTextSegmentIterator;
70import android.view.AccessibilityIterators.ParagraphTextSegmentIterator;
71import android.view.accessibility.AccessibilityEvent;
72import android.view.accessibility.AccessibilityEventSource;
73import android.view.accessibility.AccessibilityManager;
74import android.view.accessibility.AccessibilityNodeInfo;
75import android.view.accessibility.AccessibilityNodeProvider;
76import android.view.animation.Animation;
77import android.view.animation.AnimationUtils;
78import android.view.animation.Transformation;
79import android.view.inputmethod.EditorInfo;
80import android.view.inputmethod.InputConnection;
81import android.view.inputmethod.InputMethodManager;
82import android.widget.ScrollBarDrawable;
83
84import static android.os.Build.VERSION_CODES.*;
85import static java.lang.Math.max;
86
87import com.android.internal.R;
88import com.android.internal.util.Predicate;
89import com.android.internal.view.menu.MenuBuilder;
90import com.google.android.collect.Lists;
91import com.google.android.collect.Maps;
92
93import java.lang.annotation.Retention;
94import java.lang.annotation.RetentionPolicy;
95import java.lang.ref.WeakReference;
96import java.lang.reflect.Field;
97import java.lang.reflect.InvocationTargetException;
98import java.lang.reflect.Method;
99import java.lang.reflect.Modifier;
100import java.util.ArrayList;
101import java.util.Arrays;
102import java.util.Collections;
103import java.util.HashMap;
104import java.util.List;
105import java.util.Locale;
106import java.util.Map;
107import java.util.concurrent.CopyOnWriteArrayList;
108import java.util.concurrent.atomic.AtomicInteger;
109
110/**
111 * <p>
112 * This class represents the basic building block for user interface components. A View
113 * occupies a rectangular area on the screen and is responsible for drawing and
114 * event handling. View is the base class for <em>widgets</em>, which are
115 * used to create interactive UI components (buttons, text fields, etc.). The
116 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
117 * are invisible containers that hold other Views (or other ViewGroups) and define
118 * their layout properties.
119 * </p>
120 *
121 * <div class="special reference">
122 * <h3>Developer Guides</h3>
123 * <p>For information about using this class to develop your application's user interface,
124 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
125 * </div>
126 *
127 * <a name="Using"></a>
128 * <h3>Using Views</h3>
129 * <p>
130 * All of the views in a window are arranged in a single tree. You can add views
131 * either from code or by specifying a tree of views in one or more XML layout
132 * files. There are many specialized subclasses of views that act as controls or
133 * are capable of displaying text, images, or other content.
134 * </p>
135 * <p>
136 * Once you have created a tree of views, there are typically a few types of
137 * common operations you may wish to perform:
138 * <ul>
139 * <li><strong>Set properties:</strong> for example setting the text of a
140 * {@link android.widget.TextView}. The available properties and the methods
141 * that set them will vary among the different subclasses of views. Note that
142 * properties that are known at build time can be set in the XML layout
143 * files.</li>
144 * <li><strong>Set focus:</strong> The framework will handled moving focus in
145 * response to user input. To force focus to a specific view, call
146 * {@link #requestFocus}.</li>
147 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
148 * that will be notified when something interesting happens to the view. For
149 * example, all views will let you set a listener to be notified when the view
150 * gains or loses focus. You can register such a listener using
151 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
152 * Other view subclasses offer more specialized listeners. For example, a Button
153 * exposes a listener to notify clients when the button is clicked.</li>
154 * <li><strong>Set visibility:</strong> You can hide or show views using
155 * {@link #setVisibility(int)}.</li>
156 * </ul>
157 * </p>
158 * <p><em>
159 * Note: The Android framework is responsible for measuring, laying out and
160 * drawing views. You should not call methods that perform these actions on
161 * views yourself unless you are actually implementing a
162 * {@link android.view.ViewGroup}.
163 * </em></p>
164 *
165 * <a name="Lifecycle"></a>
166 * <h3>Implementing a Custom View</h3>
167 *
168 * <p>
169 * To implement a custom view, you will usually begin by providing overrides for
170 * some of the standard methods that the framework calls on all views. You do
171 * not need to override all of these methods. In fact, you can start by just
172 * overriding {@link #onDraw(android.graphics.Canvas)}.
173 * <table border="2" width="85%" align="center" cellpadding="5">
174 *     <thead>
175 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
176 *     </thead>
177 *
178 *     <tbody>
179 *     <tr>
180 *         <td rowspan="2">Creation</td>
181 *         <td>Constructors</td>
182 *         <td>There is a form of the constructor that are called when the view
183 *         is created from code and a form that is called when the view is
184 *         inflated from a layout file. The second form should parse and apply
185 *         any attributes defined in the layout file.
186 *         </td>
187 *     </tr>
188 *     <tr>
189 *         <td><code>{@link #onFinishInflate()}</code></td>
190 *         <td>Called after a view and all of its children has been inflated
191 *         from XML.</td>
192 *     </tr>
193 *
194 *     <tr>
195 *         <td rowspan="3">Layout</td>
196 *         <td><code>{@link #onMeasure(int, int)}</code></td>
197 *         <td>Called to determine the size requirements for this view and all
198 *         of its children.
199 *         </td>
200 *     </tr>
201 *     <tr>
202 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
203 *         <td>Called when this view should assign a size and position to all
204 *         of its children.
205 *         </td>
206 *     </tr>
207 *     <tr>
208 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
209 *         <td>Called when the size of this view has changed.
210 *         </td>
211 *     </tr>
212 *
213 *     <tr>
214 *         <td>Drawing</td>
215 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
216 *         <td>Called when the view should render its content.
217 *         </td>
218 *     </tr>
219 *
220 *     <tr>
221 *         <td rowspan="4">Event processing</td>
222 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
223 *         <td>Called when a new hardware key event occurs.
224 *         </td>
225 *     </tr>
226 *     <tr>
227 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
228 *         <td>Called when a hardware key up event occurs.
229 *         </td>
230 *     </tr>
231 *     <tr>
232 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
233 *         <td>Called when a trackball motion event occurs.
234 *         </td>
235 *     </tr>
236 *     <tr>
237 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
238 *         <td>Called when a touch screen motion event occurs.
239 *         </td>
240 *     </tr>
241 *
242 *     <tr>
243 *         <td rowspan="2">Focus</td>
244 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
245 *         <td>Called when the view gains or loses focus.
246 *         </td>
247 *     </tr>
248 *
249 *     <tr>
250 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
251 *         <td>Called when the window containing the view gains or loses focus.
252 *         </td>
253 *     </tr>
254 *
255 *     <tr>
256 *         <td rowspan="3">Attaching</td>
257 *         <td><code>{@link #onAttachedToWindow()}</code></td>
258 *         <td>Called when the view is attached to a window.
259 *         </td>
260 *     </tr>
261 *
262 *     <tr>
263 *         <td><code>{@link #onDetachedFromWindow}</code></td>
264 *         <td>Called when the view is detached from its window.
265 *         </td>
266 *     </tr>
267 *
268 *     <tr>
269 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
270 *         <td>Called when the visibility of the window containing the view
271 *         has changed.
272 *         </td>
273 *     </tr>
274 *     </tbody>
275 *
276 * </table>
277 * </p>
278 *
279 * <a name="IDs"></a>
280 * <h3>IDs</h3>
281 * Views may have an integer id associated with them. These ids are typically
282 * assigned in the layout XML files, and are used to find specific views within
283 * the view tree. A common pattern is to:
284 * <ul>
285 * <li>Define a Button in the layout file and assign it a unique ID.
286 * <pre>
287 * &lt;Button
288 *     android:id="@+id/my_button"
289 *     android:layout_width="wrap_content"
290 *     android:layout_height="wrap_content"
291 *     android:text="@string/my_button_text"/&gt;
292 * </pre></li>
293 * <li>From the onCreate method of an Activity, find the Button
294 * <pre class="prettyprint">
295 *      Button myButton = (Button) findViewById(R.id.my_button);
296 * </pre></li>
297 * </ul>
298 * <p>
299 * View IDs need not be unique throughout the tree, but it is good practice to
300 * ensure that they are at least unique within the part of the tree you are
301 * searching.
302 * </p>
303 *
304 * <a name="Position"></a>
305 * <h3>Position</h3>
306 * <p>
307 * The geometry of a view is that of a rectangle. A view has a location,
308 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
309 * two dimensions, expressed as a width and a height. The unit for location
310 * and dimensions is the pixel.
311 * </p>
312 *
313 * <p>
314 * It is possible to retrieve the location of a view by invoking the methods
315 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
316 * coordinate of the rectangle representing the view. The latter returns the
317 * top, or Y, coordinate of the rectangle representing the view. These methods
318 * both return the location of the view relative to its parent. For instance,
319 * when getLeft() returns 20, that means the view is located 20 pixels to the
320 * right of the left edge of its direct parent.
321 * </p>
322 *
323 * <p>
324 * In addition, several convenience methods are offered to avoid unnecessary
325 * computations, namely {@link #getRight()} and {@link #getBottom()}.
326 * These methods return the coordinates of the right and bottom edges of the
327 * rectangle representing the view. For instance, calling {@link #getRight()}
328 * is similar to the following computation: <code>getLeft() + getWidth()</code>
329 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
330 * </p>
331 *
332 * <a name="SizePaddingMargins"></a>
333 * <h3>Size, padding and margins</h3>
334 * <p>
335 * The size of a view is expressed with a width and a height. A view actually
336 * possess two pairs of width and height values.
337 * </p>
338 *
339 * <p>
340 * The first pair is known as <em>measured width</em> and
341 * <em>measured height</em>. These dimensions define how big a view wants to be
342 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
343 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
344 * and {@link #getMeasuredHeight()}.
345 * </p>
346 *
347 * <p>
348 * The second pair is simply known as <em>width</em> and <em>height</em>, or
349 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
350 * dimensions define the actual size of the view on screen, at drawing time and
351 * after layout. These values may, but do not have to, be different from the
352 * measured width and height. The width and height can be obtained by calling
353 * {@link #getWidth()} and {@link #getHeight()}.
354 * </p>
355 *
356 * <p>
357 * To measure its dimensions, a view takes into account its padding. The padding
358 * is expressed in pixels for the left, top, right and bottom parts of the view.
359 * Padding can be used to offset the content of the view by a specific amount of
360 * pixels. For instance, a left padding of 2 will push the view's content by
361 * 2 pixels to the right of the left edge. Padding can be set using the
362 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)}
363 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()},
364 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()},
365 * {@link #getPaddingEnd()}.
366 * </p>
367 *
368 * <p>
369 * Even though a view can define a padding, it does not provide any support for
370 * margins. However, view groups provide such a support. Refer to
371 * {@link android.view.ViewGroup} and
372 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
373 * </p>
374 *
375 * <a name="Layout"></a>
376 * <h3>Layout</h3>
377 * <p>
378 * Layout is a two pass process: a measure pass and a layout pass. The measuring
379 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
380 * of the view tree. Each view pushes dimension specifications down the tree
381 * during the recursion. At the end of the measure pass, every view has stored
382 * its measurements. The second pass happens in
383 * {@link #layout(int,int,int,int)} and is also top-down. During
384 * this pass each parent is responsible for positioning all of its children
385 * using the sizes computed in the measure pass.
386 * </p>
387 *
388 * <p>
389 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
390 * {@link #getMeasuredHeight()} values must be set, along with those for all of
391 * that view's descendants. A view's measured width and measured height values
392 * must respect the constraints imposed by the view's parents. This guarantees
393 * that at the end of the measure pass, all parents accept all of their
394 * children's measurements. A parent view may call measure() more than once on
395 * its children. For example, the parent may measure each child once with
396 * unspecified dimensions to find out how big they want to be, then call
397 * measure() on them again with actual numbers if the sum of all the children's
398 * unconstrained sizes is too big or too small.
399 * </p>
400 *
401 * <p>
402 * The measure pass uses two classes to communicate dimensions. The
403 * {@link MeasureSpec} class is used by views to tell their parents how they
404 * want to be measured and positioned. The base LayoutParams class just
405 * describes how big the view wants to be for both width and height. For each
406 * dimension, it can specify one of:
407 * <ul>
408 * <li> an exact number
409 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
410 * (minus padding)
411 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
412 * enclose its content (plus padding).
413 * </ul>
414 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
415 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
416 * an X and Y value.
417 * </p>
418 *
419 * <p>
420 * MeasureSpecs are used to push requirements down the tree from parent to
421 * child. A MeasureSpec can be in one of three modes:
422 * <ul>
423 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
424 * of a child view. For example, a LinearLayout may call measure() on its child
425 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
426 * tall the child view wants to be given a width of 240 pixels.
427 * <li>EXACTLY: This is used by the parent to impose an exact size on the
428 * child. The child must use this size, and guarantee that all of its
429 * descendants will fit within this size.
430 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
431 * child. The child must gurantee that it and all of its descendants will fit
432 * within this size.
433 * </ul>
434 * </p>
435 *
436 * <p>
437 * To intiate a layout, call {@link #requestLayout}. This method is typically
438 * called by a view on itself when it believes that is can no longer fit within
439 * its current bounds.
440 * </p>
441 *
442 * <a name="Drawing"></a>
443 * <h3>Drawing</h3>
444 * <p>
445 * Drawing is handled by walking the tree and rendering each view that
446 * intersects the invalid region. Because the tree is traversed in-order,
447 * this means that parents will draw before (i.e., behind) their children, with
448 * siblings drawn in the order they appear in the tree.
449 * If you set a background drawable for a View, then the View will draw it for you
450 * before calling back to its <code>onDraw()</code> method.
451 * </p>
452 *
453 * <p>
454 * Note that the framework will not draw views that are not in the invalid region.
455 * </p>
456 *
457 * <p>
458 * To force a view to draw, call {@link #invalidate()}.
459 * </p>
460 *
461 * <a name="EventHandlingThreading"></a>
462 * <h3>Event Handling and Threading</h3>
463 * <p>
464 * The basic cycle of a view is as follows:
465 * <ol>
466 * <li>An event comes in and is dispatched to the appropriate view. The view
467 * handles the event and notifies any listeners.</li>
468 * <li>If in the course of processing the event, the view's bounds may need
469 * to be changed, the view will call {@link #requestLayout()}.</li>
470 * <li>Similarly, if in the course of processing the event the view's appearance
471 * may need to be changed, the view will call {@link #invalidate()}.</li>
472 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
473 * the framework will take care of measuring, laying out, and drawing the tree
474 * as appropriate.</li>
475 * </ol>
476 * </p>
477 *
478 * <p><em>Note: The entire view tree is single threaded. You must always be on
479 * the UI thread when calling any method on any view.</em>
480 * If you are doing work on other threads and want to update the state of a view
481 * from that thread, you should use a {@link Handler}.
482 * </p>
483 *
484 * <a name="FocusHandling"></a>
485 * <h3>Focus Handling</h3>
486 * <p>
487 * The framework will handle routine focus movement in response to user input.
488 * This includes changing the focus as views are removed or hidden, or as new
489 * views become available. Views indicate their willingness to take focus
490 * through the {@link #isFocusable} method. To change whether a view can take
491 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
492 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
493 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
494 * </p>
495 * <p>
496 * Focus movement is based on an algorithm which finds the nearest neighbor in a
497 * given direction. In rare cases, the default algorithm may not match the
498 * intended behavior of the developer. In these situations, you can provide
499 * explicit overrides by using these XML attributes in the layout file:
500 * <pre>
501 * nextFocusDown
502 * nextFocusLeft
503 * nextFocusRight
504 * nextFocusUp
505 * </pre>
506 * </p>
507 *
508 *
509 * <p>
510 * To get a particular view to take focus, call {@link #requestFocus()}.
511 * </p>
512 *
513 * <a name="TouchMode"></a>
514 * <h3>Touch Mode</h3>
515 * <p>
516 * When a user is navigating a user interface via directional keys such as a D-pad, it is
517 * necessary to give focus to actionable items such as buttons so the user can see
518 * what will take input.  If the device has touch capabilities, however, and the user
519 * begins interacting with the interface by touching it, it is no longer necessary to
520 * always highlight, or give focus to, a particular view.  This motivates a mode
521 * for interaction named 'touch mode'.
522 * </p>
523 * <p>
524 * For a touch capable device, once the user touches the screen, the device
525 * will enter touch mode.  From this point onward, only views for which
526 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
527 * Other views that are touchable, like buttons, will not take focus when touched; they will
528 * only fire the on click listeners.
529 * </p>
530 * <p>
531 * Any time a user hits a directional key, such as a D-pad direction, the view device will
532 * exit touch mode, and find a view to take focus, so that the user may resume interacting
533 * with the user interface without touching the screen again.
534 * </p>
535 * <p>
536 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
537 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
538 * </p>
539 *
540 * <a name="Scrolling"></a>
541 * <h3>Scrolling</h3>
542 * <p>
543 * The framework provides basic support for views that wish to internally
544 * scroll their content. This includes keeping track of the X and Y scroll
545 * offset as well as mechanisms for drawing scrollbars. See
546 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
547 * {@link #awakenScrollBars()} for more details.
548 * </p>
549 *
550 * <a name="Tags"></a>
551 * <h3>Tags</h3>
552 * <p>
553 * Unlike IDs, tags are not used to identify views. Tags are essentially an
554 * extra piece of information that can be associated with a view. They are most
555 * often used as a convenience to store data related to views in the views
556 * themselves rather than by putting them in a separate structure.
557 * </p>
558 *
559 * <a name="Properties"></a>
560 * <h3>Properties</h3>
561 * <p>
562 * The View class exposes an {@link #ALPHA} property, as well as several transform-related
563 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are
564 * available both in the {@link Property} form as well as in similarly-named setter/getter
565 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can
566 * be used to set persistent state associated with these rendering-related properties on the view.
567 * The properties and methods can also be used in conjunction with
568 * {@link android.animation.Animator Animator}-based animations, described more in the
569 * <a href="#Animation">Animation</a> section.
570 * </p>
571 *
572 * <a name="Animation"></a>
573 * <h3>Animation</h3>
574 * <p>
575 * Starting with Android 3.0, the preferred way of animating views is to use the
576 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based
577 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and
578 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0
579 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only
580 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class
581 * makes animating these View properties particularly easy and efficient.
582 * </p>
583 * <p>
584 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered.
585 * You can attach an {@link Animation} object to a view using
586 * {@link #setAnimation(Animation)} or
587 * {@link #startAnimation(Animation)}. The animation can alter the scale,
588 * rotation, translation and alpha of a view over time. If the animation is
589 * attached to a view that has children, the animation will affect the entire
590 * subtree rooted by that node. When an animation is started, the framework will
591 * take care of redrawing the appropriate views until the animation completes.
592 * </p>
593 *
594 * <a name="Security"></a>
595 * <h3>Security</h3>
596 * <p>
597 * Sometimes it is essential that an application be able to verify that an action
598 * is being performed with the full knowledge and consent of the user, such as
599 * granting a permission request, making a purchase or clicking on an advertisement.
600 * Unfortunately, a malicious application could try to spoof the user into
601 * performing these actions, unaware, by concealing the intended purpose of the view.
602 * As a remedy, the framework offers a touch filtering mechanism that can be used to
603 * improve the security of views that provide access to sensitive functionality.
604 * </p><p>
605 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
606 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
607 * will discard touches that are received whenever the view's window is obscured by
608 * another visible window.  As a result, the view will not receive touches whenever a
609 * toast, dialog or other window appears above the view's window.
610 * </p><p>
611 * For more fine-grained control over security, consider overriding the
612 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
613 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
614 * </p>
615 *
616 * @attr ref android.R.styleable#View_alpha
617 * @attr ref android.R.styleable#View_background
618 * @attr ref android.R.styleable#View_clickable
619 * @attr ref android.R.styleable#View_contentDescription
620 * @attr ref android.R.styleable#View_drawingCacheQuality
621 * @attr ref android.R.styleable#View_duplicateParentState
622 * @attr ref android.R.styleable#View_id
623 * @attr ref android.R.styleable#View_requiresFadingEdge
624 * @attr ref android.R.styleable#View_fadeScrollbars
625 * @attr ref android.R.styleable#View_fadingEdgeLength
626 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
627 * @attr ref android.R.styleable#View_fitsSystemWindows
628 * @attr ref android.R.styleable#View_isScrollContainer
629 * @attr ref android.R.styleable#View_focusable
630 * @attr ref android.R.styleable#View_focusableInTouchMode
631 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
632 * @attr ref android.R.styleable#View_keepScreenOn
633 * @attr ref android.R.styleable#View_layerType
634 * @attr ref android.R.styleable#View_layoutDirection
635 * @attr ref android.R.styleable#View_longClickable
636 * @attr ref android.R.styleable#View_minHeight
637 * @attr ref android.R.styleable#View_minWidth
638 * @attr ref android.R.styleable#View_nextFocusDown
639 * @attr ref android.R.styleable#View_nextFocusLeft
640 * @attr ref android.R.styleable#View_nextFocusRight
641 * @attr ref android.R.styleable#View_nextFocusUp
642 * @attr ref android.R.styleable#View_onClick
643 * @attr ref android.R.styleable#View_padding
644 * @attr ref android.R.styleable#View_paddingBottom
645 * @attr ref android.R.styleable#View_paddingLeft
646 * @attr ref android.R.styleable#View_paddingRight
647 * @attr ref android.R.styleable#View_paddingTop
648 * @attr ref android.R.styleable#View_paddingStart
649 * @attr ref android.R.styleable#View_paddingEnd
650 * @attr ref android.R.styleable#View_saveEnabled
651 * @attr ref android.R.styleable#View_rotation
652 * @attr ref android.R.styleable#View_rotationX
653 * @attr ref android.R.styleable#View_rotationY
654 * @attr ref android.R.styleable#View_scaleX
655 * @attr ref android.R.styleable#View_scaleY
656 * @attr ref android.R.styleable#View_scrollX
657 * @attr ref android.R.styleable#View_scrollY
658 * @attr ref android.R.styleable#View_scrollbarSize
659 * @attr ref android.R.styleable#View_scrollbarStyle
660 * @attr ref android.R.styleable#View_scrollbars
661 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
662 * @attr ref android.R.styleable#View_scrollbarFadeDuration
663 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
664 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
665 * @attr ref android.R.styleable#View_scrollbarThumbVertical
666 * @attr ref android.R.styleable#View_scrollbarTrackVertical
667 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
668 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
669 * @attr ref android.R.styleable#View_sharedElementName
670 * @attr ref android.R.styleable#View_soundEffectsEnabled
671 * @attr ref android.R.styleable#View_tag
672 * @attr ref android.R.styleable#View_textAlignment
673 * @attr ref android.R.styleable#View_textDirection
674 * @attr ref android.R.styleable#View_transformPivotX
675 * @attr ref android.R.styleable#View_transformPivotY
676 * @attr ref android.R.styleable#View_translationX
677 * @attr ref android.R.styleable#View_translationY
678 * @attr ref android.R.styleable#View_translationZ
679 * @attr ref android.R.styleable#View_visibility
680 *
681 * @see android.view.ViewGroup
682 */
683public class View implements Drawable.Callback, KeyEvent.Callback,
684        AccessibilityEventSource {
685    private static final boolean DBG = false;
686
687    /**
688     * The logging tag used by this class with android.util.Log.
689     */
690    protected static final String VIEW_LOG_TAG = "View";
691
692    /**
693     * When set to true, apps will draw debugging information about their layouts.
694     *
695     * @hide
696     */
697    public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout";
698
699    /**
700     * Used to mark a View that has no ID.
701     */
702    public static final int NO_ID = -1;
703
704    /**
705     * Signals that compatibility booleans have been initialized according to
706     * target SDK versions.
707     */
708    private static boolean sCompatibilityDone = false;
709
710    /**
711     * Use the old (broken) way of building MeasureSpecs.
712     */
713    private static boolean sUseBrokenMakeMeasureSpec = false;
714
715    /**
716     * Ignore any optimizations using the measure cache.
717     */
718    private static boolean sIgnoreMeasureCache = false;
719
720    /**
721     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
722     * calling setFlags.
723     */
724    private static final int NOT_FOCUSABLE = 0x00000000;
725
726    /**
727     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
728     * setFlags.
729     */
730    private static final int FOCUSABLE = 0x00000001;
731
732    /**
733     * Mask for use with setFlags indicating bits used for focus.
734     */
735    private static final int FOCUSABLE_MASK = 0x00000001;
736
737    /**
738     * This view will adjust its padding to fit sytem windows (e.g. status bar)
739     */
740    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
741
742    /** @hide */
743    @IntDef({VISIBLE, INVISIBLE, GONE})
744    @Retention(RetentionPolicy.SOURCE)
745    public @interface Visibility {}
746
747    /**
748     * This view is visible.
749     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
750     * android:visibility}.
751     */
752    public static final int VISIBLE = 0x00000000;
753
754    /**
755     * This view is invisible, but it still takes up space for layout purposes.
756     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
757     * android:visibility}.
758     */
759    public static final int INVISIBLE = 0x00000004;
760
761    /**
762     * This view is invisible, and it doesn't take any space for layout
763     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
764     * android:visibility}.
765     */
766    public static final int GONE = 0x00000008;
767
768    /**
769     * Mask for use with setFlags indicating bits used for visibility.
770     * {@hide}
771     */
772    static final int VISIBILITY_MASK = 0x0000000C;
773
774    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
775
776    /**
777     * This view is enabled. Interpretation varies by subclass.
778     * Use with ENABLED_MASK when calling setFlags.
779     * {@hide}
780     */
781    static final int ENABLED = 0x00000000;
782
783    /**
784     * This view is disabled. Interpretation varies by subclass.
785     * Use with ENABLED_MASK when calling setFlags.
786     * {@hide}
787     */
788    static final int DISABLED = 0x00000020;
789
790   /**
791    * Mask for use with setFlags indicating bits used for indicating whether
792    * this view is enabled
793    * {@hide}
794    */
795    static final int ENABLED_MASK = 0x00000020;
796
797    /**
798     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
799     * called and further optimizations will be performed. It is okay to have
800     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
801     * {@hide}
802     */
803    static final int WILL_NOT_DRAW = 0x00000080;
804
805    /**
806     * Mask for use with setFlags indicating bits used for indicating whether
807     * this view is will draw
808     * {@hide}
809     */
810    static final int DRAW_MASK = 0x00000080;
811
812    /**
813     * <p>This view doesn't show scrollbars.</p>
814     * {@hide}
815     */
816    static final int SCROLLBARS_NONE = 0x00000000;
817
818    /**
819     * <p>This view shows horizontal scrollbars.</p>
820     * {@hide}
821     */
822    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
823
824    /**
825     * <p>This view shows vertical scrollbars.</p>
826     * {@hide}
827     */
828    static final int SCROLLBARS_VERTICAL = 0x00000200;
829
830    /**
831     * <p>Mask for use with setFlags indicating bits used for indicating which
832     * scrollbars are enabled.</p>
833     * {@hide}
834     */
835    static final int SCROLLBARS_MASK = 0x00000300;
836
837    /**
838     * Indicates that the view should filter touches when its window is obscured.
839     * Refer to the class comments for more information about this security feature.
840     * {@hide}
841     */
842    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
843
844    /**
845     * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
846     * that they are optional and should be skipped if the window has
847     * requested system UI flags that ignore those insets for layout.
848     */
849    static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
850
851    /**
852     * <p>This view doesn't show fading edges.</p>
853     * {@hide}
854     */
855    static final int FADING_EDGE_NONE = 0x00000000;
856
857    /**
858     * <p>This view shows horizontal fading edges.</p>
859     * {@hide}
860     */
861    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
862
863    /**
864     * <p>This view shows vertical fading edges.</p>
865     * {@hide}
866     */
867    static final int FADING_EDGE_VERTICAL = 0x00002000;
868
869    /**
870     * <p>Mask for use with setFlags indicating bits used for indicating which
871     * fading edges are enabled.</p>
872     * {@hide}
873     */
874    static final int FADING_EDGE_MASK = 0x00003000;
875
876    /**
877     * <p>Indicates this view can be clicked. When clickable, a View reacts
878     * to clicks by notifying the OnClickListener.<p>
879     * {@hide}
880     */
881    static final int CLICKABLE = 0x00004000;
882
883    /**
884     * <p>Indicates this view is caching its drawing into a bitmap.</p>
885     * {@hide}
886     */
887    static final int DRAWING_CACHE_ENABLED = 0x00008000;
888
889    /**
890     * <p>Indicates that no icicle should be saved for this view.<p>
891     * {@hide}
892     */
893    static final int SAVE_DISABLED = 0x000010000;
894
895    /**
896     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
897     * property.</p>
898     * {@hide}
899     */
900    static final int SAVE_DISABLED_MASK = 0x000010000;
901
902    /**
903     * <p>Indicates that no drawing cache should ever be created for this view.<p>
904     * {@hide}
905     */
906    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
907
908    /**
909     * <p>Indicates this view can take / keep focus when int touch mode.</p>
910     * {@hide}
911     */
912    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
913
914    /** @hide */
915    @Retention(RetentionPolicy.SOURCE)
916    @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO})
917    public @interface DrawingCacheQuality {}
918
919    /**
920     * <p>Enables low quality mode for the drawing cache.</p>
921     */
922    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
923
924    /**
925     * <p>Enables high quality mode for the drawing cache.</p>
926     */
927    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
928
929    /**
930     * <p>Enables automatic quality mode for the drawing cache.</p>
931     */
932    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
933
934    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
935            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
936    };
937
938    /**
939     * <p>Mask for use with setFlags indicating bits used for the cache
940     * quality property.</p>
941     * {@hide}
942     */
943    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
944
945    /**
946     * <p>
947     * Indicates this view can be long clicked. When long clickable, a View
948     * reacts to long clicks by notifying the OnLongClickListener or showing a
949     * context menu.
950     * </p>
951     * {@hide}
952     */
953    static final int LONG_CLICKABLE = 0x00200000;
954
955    /**
956     * <p>Indicates that this view gets its drawable states from its direct parent
957     * and ignores its original internal states.</p>
958     *
959     * @hide
960     */
961    static final int DUPLICATE_PARENT_STATE = 0x00400000;
962
963    /** @hide */
964    @IntDef({
965        SCROLLBARS_INSIDE_OVERLAY,
966        SCROLLBARS_INSIDE_INSET,
967        SCROLLBARS_OUTSIDE_OVERLAY,
968        SCROLLBARS_OUTSIDE_INSET
969    })
970    @Retention(RetentionPolicy.SOURCE)
971    public @interface ScrollBarStyle {}
972
973    /**
974     * The scrollbar style to display the scrollbars inside the content area,
975     * without increasing the padding. The scrollbars will be overlaid with
976     * translucency on the view's content.
977     */
978    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
979
980    /**
981     * The scrollbar style to display the scrollbars inside the padded area,
982     * increasing the padding of the view. The scrollbars will not overlap the
983     * content area of the view.
984     */
985    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
986
987    /**
988     * The scrollbar style to display the scrollbars at the edge of the view,
989     * without increasing the padding. The scrollbars will be overlaid with
990     * translucency.
991     */
992    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
993
994    /**
995     * The scrollbar style to display the scrollbars at the edge of the view,
996     * increasing the padding of the view. The scrollbars will only overlap the
997     * background, if any.
998     */
999    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
1000
1001    /**
1002     * Mask to check if the scrollbar style is overlay or inset.
1003     * {@hide}
1004     */
1005    static final int SCROLLBARS_INSET_MASK = 0x01000000;
1006
1007    /**
1008     * Mask to check if the scrollbar style is inside or outside.
1009     * {@hide}
1010     */
1011    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
1012
1013    /**
1014     * Mask for scrollbar style.
1015     * {@hide}
1016     */
1017    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
1018
1019    /**
1020     * View flag indicating that the screen should remain on while the
1021     * window containing this view is visible to the user.  This effectively
1022     * takes care of automatically setting the WindowManager's
1023     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
1024     */
1025    public static final int KEEP_SCREEN_ON = 0x04000000;
1026
1027    /**
1028     * View flag indicating whether this view should have sound effects enabled
1029     * for events such as clicking and touching.
1030     */
1031    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
1032
1033    /**
1034     * View flag indicating whether this view should have haptic feedback
1035     * enabled for events such as long presses.
1036     */
1037    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
1038
1039    /**
1040     * <p>Indicates that the view hierarchy should stop saving state when
1041     * it reaches this view.  If state saving is initiated immediately at
1042     * the view, it will be allowed.
1043     * {@hide}
1044     */
1045    static final int PARENT_SAVE_DISABLED = 0x20000000;
1046
1047    /**
1048     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
1049     * {@hide}
1050     */
1051    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
1052
1053    /** @hide */
1054    @IntDef(flag = true,
1055            value = {
1056                FOCUSABLES_ALL,
1057                FOCUSABLES_TOUCH_MODE
1058            })
1059    @Retention(RetentionPolicy.SOURCE)
1060    public @interface FocusableMode {}
1061
1062    /**
1063     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1064     * should add all focusable Views regardless if they are focusable in touch mode.
1065     */
1066    public static final int FOCUSABLES_ALL = 0x00000000;
1067
1068    /**
1069     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1070     * should add only Views focusable in touch mode.
1071     */
1072    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1073
1074    /** @hide */
1075    @IntDef({
1076            FOCUS_BACKWARD,
1077            FOCUS_FORWARD,
1078            FOCUS_LEFT,
1079            FOCUS_UP,
1080            FOCUS_RIGHT,
1081            FOCUS_DOWN
1082    })
1083    @Retention(RetentionPolicy.SOURCE)
1084    public @interface FocusDirection {}
1085
1086    /** @hide */
1087    @IntDef({
1088            FOCUS_LEFT,
1089            FOCUS_UP,
1090            FOCUS_RIGHT,
1091            FOCUS_DOWN
1092    })
1093    @Retention(RetentionPolicy.SOURCE)
1094    public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward
1095
1096    /**
1097     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1098     * item.
1099     */
1100    public static final int FOCUS_BACKWARD = 0x00000001;
1101
1102    /**
1103     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1104     * item.
1105     */
1106    public static final int FOCUS_FORWARD = 0x00000002;
1107
1108    /**
1109     * Use with {@link #focusSearch(int)}. Move focus to the left.
1110     */
1111    public static final int FOCUS_LEFT = 0x00000011;
1112
1113    /**
1114     * Use with {@link #focusSearch(int)}. Move focus up.
1115     */
1116    public static final int FOCUS_UP = 0x00000021;
1117
1118    /**
1119     * Use with {@link #focusSearch(int)}. Move focus to the right.
1120     */
1121    public static final int FOCUS_RIGHT = 0x00000042;
1122
1123    /**
1124     * Use with {@link #focusSearch(int)}. Move focus down.
1125     */
1126    public static final int FOCUS_DOWN = 0x00000082;
1127
1128    /**
1129     * Bits of {@link #getMeasuredWidthAndState()} and
1130     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1131     */
1132    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1133
1134    /**
1135     * Bits of {@link #getMeasuredWidthAndState()} and
1136     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1137     */
1138    public static final int MEASURED_STATE_MASK = 0xff000000;
1139
1140    /**
1141     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1142     * for functions that combine both width and height into a single int,
1143     * such as {@link #getMeasuredState()} and the childState argument of
1144     * {@link #resolveSizeAndState(int, int, int)}.
1145     */
1146    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1147
1148    /**
1149     * Bit of {@link #getMeasuredWidthAndState()} and
1150     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1151     * is smaller that the space the view would like to have.
1152     */
1153    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1154
1155    /**
1156     * Base View state sets
1157     */
1158    // Singles
1159    /**
1160     * Indicates the view has no states set. States are used with
1161     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1162     * view depending on its state.
1163     *
1164     * @see android.graphics.drawable.Drawable
1165     * @see #getDrawableState()
1166     */
1167    protected static final int[] EMPTY_STATE_SET;
1168    /**
1169     * Indicates the view is enabled. States are used with
1170     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1171     * view depending on its state.
1172     *
1173     * @see android.graphics.drawable.Drawable
1174     * @see #getDrawableState()
1175     */
1176    protected static final int[] ENABLED_STATE_SET;
1177    /**
1178     * Indicates the view is focused. States are used with
1179     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1180     * view depending on its state.
1181     *
1182     * @see android.graphics.drawable.Drawable
1183     * @see #getDrawableState()
1184     */
1185    protected static final int[] FOCUSED_STATE_SET;
1186    /**
1187     * Indicates the view is selected. States are used with
1188     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1189     * view depending on its state.
1190     *
1191     * @see android.graphics.drawable.Drawable
1192     * @see #getDrawableState()
1193     */
1194    protected static final int[] SELECTED_STATE_SET;
1195    /**
1196     * Indicates the view is pressed. States are used with
1197     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1198     * view depending on its state.
1199     *
1200     * @see android.graphics.drawable.Drawable
1201     * @see #getDrawableState()
1202     */
1203    protected static final int[] PRESSED_STATE_SET;
1204    /**
1205     * Indicates the view's window has focus. States are used with
1206     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1207     * view depending on its state.
1208     *
1209     * @see android.graphics.drawable.Drawable
1210     * @see #getDrawableState()
1211     */
1212    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1213    // Doubles
1214    /**
1215     * Indicates the view is enabled and has the focus.
1216     *
1217     * @see #ENABLED_STATE_SET
1218     * @see #FOCUSED_STATE_SET
1219     */
1220    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1221    /**
1222     * Indicates the view is enabled and selected.
1223     *
1224     * @see #ENABLED_STATE_SET
1225     * @see #SELECTED_STATE_SET
1226     */
1227    protected static final int[] ENABLED_SELECTED_STATE_SET;
1228    /**
1229     * Indicates the view is enabled and that its window has focus.
1230     *
1231     * @see #ENABLED_STATE_SET
1232     * @see #WINDOW_FOCUSED_STATE_SET
1233     */
1234    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1235    /**
1236     * Indicates the view is focused and selected.
1237     *
1238     * @see #FOCUSED_STATE_SET
1239     * @see #SELECTED_STATE_SET
1240     */
1241    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1242    /**
1243     * Indicates the view has the focus and that its window has the focus.
1244     *
1245     * @see #FOCUSED_STATE_SET
1246     * @see #WINDOW_FOCUSED_STATE_SET
1247     */
1248    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1249    /**
1250     * Indicates the view is selected and that its window has the focus.
1251     *
1252     * @see #SELECTED_STATE_SET
1253     * @see #WINDOW_FOCUSED_STATE_SET
1254     */
1255    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1256    // Triples
1257    /**
1258     * Indicates the view is enabled, focused and selected.
1259     *
1260     * @see #ENABLED_STATE_SET
1261     * @see #FOCUSED_STATE_SET
1262     * @see #SELECTED_STATE_SET
1263     */
1264    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1265    /**
1266     * Indicates the view is enabled, focused and its window has the focus.
1267     *
1268     * @see #ENABLED_STATE_SET
1269     * @see #FOCUSED_STATE_SET
1270     * @see #WINDOW_FOCUSED_STATE_SET
1271     */
1272    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1273    /**
1274     * Indicates the view is enabled, selected and its window has the focus.
1275     *
1276     * @see #ENABLED_STATE_SET
1277     * @see #SELECTED_STATE_SET
1278     * @see #WINDOW_FOCUSED_STATE_SET
1279     */
1280    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1281    /**
1282     * Indicates the view is focused, selected and its window has the focus.
1283     *
1284     * @see #FOCUSED_STATE_SET
1285     * @see #SELECTED_STATE_SET
1286     * @see #WINDOW_FOCUSED_STATE_SET
1287     */
1288    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1289    /**
1290     * Indicates the view is enabled, focused, selected and its window
1291     * has the focus.
1292     *
1293     * @see #ENABLED_STATE_SET
1294     * @see #FOCUSED_STATE_SET
1295     * @see #SELECTED_STATE_SET
1296     * @see #WINDOW_FOCUSED_STATE_SET
1297     */
1298    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1299    /**
1300     * Indicates the view is pressed and its window has the focus.
1301     *
1302     * @see #PRESSED_STATE_SET
1303     * @see #WINDOW_FOCUSED_STATE_SET
1304     */
1305    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1306    /**
1307     * Indicates the view is pressed and selected.
1308     *
1309     * @see #PRESSED_STATE_SET
1310     * @see #SELECTED_STATE_SET
1311     */
1312    protected static final int[] PRESSED_SELECTED_STATE_SET;
1313    /**
1314     * Indicates the view is pressed, selected and its window has the focus.
1315     *
1316     * @see #PRESSED_STATE_SET
1317     * @see #SELECTED_STATE_SET
1318     * @see #WINDOW_FOCUSED_STATE_SET
1319     */
1320    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1321    /**
1322     * Indicates the view is pressed and focused.
1323     *
1324     * @see #PRESSED_STATE_SET
1325     * @see #FOCUSED_STATE_SET
1326     */
1327    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1328    /**
1329     * Indicates the view is pressed, focused and its window has the focus.
1330     *
1331     * @see #PRESSED_STATE_SET
1332     * @see #FOCUSED_STATE_SET
1333     * @see #WINDOW_FOCUSED_STATE_SET
1334     */
1335    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1336    /**
1337     * Indicates the view is pressed, focused and selected.
1338     *
1339     * @see #PRESSED_STATE_SET
1340     * @see #SELECTED_STATE_SET
1341     * @see #FOCUSED_STATE_SET
1342     */
1343    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1344    /**
1345     * Indicates the view is pressed, focused, selected and its window has the focus.
1346     *
1347     * @see #PRESSED_STATE_SET
1348     * @see #FOCUSED_STATE_SET
1349     * @see #SELECTED_STATE_SET
1350     * @see #WINDOW_FOCUSED_STATE_SET
1351     */
1352    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1353    /**
1354     * Indicates the view is pressed and enabled.
1355     *
1356     * @see #PRESSED_STATE_SET
1357     * @see #ENABLED_STATE_SET
1358     */
1359    protected static final int[] PRESSED_ENABLED_STATE_SET;
1360    /**
1361     * Indicates the view is pressed, enabled and its window has the focus.
1362     *
1363     * @see #PRESSED_STATE_SET
1364     * @see #ENABLED_STATE_SET
1365     * @see #WINDOW_FOCUSED_STATE_SET
1366     */
1367    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1368    /**
1369     * Indicates the view is pressed, enabled and selected.
1370     *
1371     * @see #PRESSED_STATE_SET
1372     * @see #ENABLED_STATE_SET
1373     * @see #SELECTED_STATE_SET
1374     */
1375    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1376    /**
1377     * Indicates the view is pressed, enabled, selected and its window has the
1378     * focus.
1379     *
1380     * @see #PRESSED_STATE_SET
1381     * @see #ENABLED_STATE_SET
1382     * @see #SELECTED_STATE_SET
1383     * @see #WINDOW_FOCUSED_STATE_SET
1384     */
1385    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1386    /**
1387     * Indicates the view is pressed, enabled and focused.
1388     *
1389     * @see #PRESSED_STATE_SET
1390     * @see #ENABLED_STATE_SET
1391     * @see #FOCUSED_STATE_SET
1392     */
1393    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1394    /**
1395     * Indicates the view is pressed, enabled, focused and its window has the
1396     * focus.
1397     *
1398     * @see #PRESSED_STATE_SET
1399     * @see #ENABLED_STATE_SET
1400     * @see #FOCUSED_STATE_SET
1401     * @see #WINDOW_FOCUSED_STATE_SET
1402     */
1403    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1404    /**
1405     * Indicates the view is pressed, enabled, focused and selected.
1406     *
1407     * @see #PRESSED_STATE_SET
1408     * @see #ENABLED_STATE_SET
1409     * @see #SELECTED_STATE_SET
1410     * @see #FOCUSED_STATE_SET
1411     */
1412    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1413    /**
1414     * Indicates the view is pressed, enabled, focused, selected and its window
1415     * has the focus.
1416     *
1417     * @see #PRESSED_STATE_SET
1418     * @see #ENABLED_STATE_SET
1419     * @see #SELECTED_STATE_SET
1420     * @see #FOCUSED_STATE_SET
1421     * @see #WINDOW_FOCUSED_STATE_SET
1422     */
1423    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1424
1425    /**
1426     * The order here is very important to {@link #getDrawableState()}
1427     */
1428    private static final int[][] VIEW_STATE_SETS;
1429
1430    static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1431    static final int VIEW_STATE_SELECTED = 1 << 1;
1432    static final int VIEW_STATE_FOCUSED = 1 << 2;
1433    static final int VIEW_STATE_ENABLED = 1 << 3;
1434    static final int VIEW_STATE_PRESSED = 1 << 4;
1435    static final int VIEW_STATE_ACTIVATED = 1 << 5;
1436    static final int VIEW_STATE_ACCELERATED = 1 << 6;
1437    static final int VIEW_STATE_HOVERED = 1 << 7;
1438    static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8;
1439    static final int VIEW_STATE_DRAG_HOVERED = 1 << 9;
1440
1441    static final int[] VIEW_STATE_IDS = new int[] {
1442        R.attr.state_window_focused,    VIEW_STATE_WINDOW_FOCUSED,
1443        R.attr.state_selected,          VIEW_STATE_SELECTED,
1444        R.attr.state_focused,           VIEW_STATE_FOCUSED,
1445        R.attr.state_enabled,           VIEW_STATE_ENABLED,
1446        R.attr.state_pressed,           VIEW_STATE_PRESSED,
1447        R.attr.state_activated,         VIEW_STATE_ACTIVATED,
1448        R.attr.state_accelerated,       VIEW_STATE_ACCELERATED,
1449        R.attr.state_hovered,           VIEW_STATE_HOVERED,
1450        R.attr.state_drag_can_accept,   VIEW_STATE_DRAG_CAN_ACCEPT,
1451        R.attr.state_drag_hovered,      VIEW_STATE_DRAG_HOVERED
1452    };
1453
1454    static {
1455        if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1456            throw new IllegalStateException(
1457                    "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1458        }
1459        int[] orderedIds = new int[VIEW_STATE_IDS.length];
1460        for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
1461            int viewState = R.styleable.ViewDrawableStates[i];
1462            for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
1463                if (VIEW_STATE_IDS[j] == viewState) {
1464                    orderedIds[i * 2] = viewState;
1465                    orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
1466                }
1467            }
1468        }
1469        final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1470        VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1471        for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
1472            int numBits = Integer.bitCount(i);
1473            int[] set = new int[numBits];
1474            int pos = 0;
1475            for (int j = 0; j < orderedIds.length; j += 2) {
1476                if ((i & orderedIds[j+1]) != 0) {
1477                    set[pos++] = orderedIds[j];
1478                }
1479            }
1480            VIEW_STATE_SETS[i] = set;
1481        }
1482
1483        EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1484        WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1485        SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1486        SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1487                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1488        FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1489        FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1490                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1491        FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1492                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1493        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1494                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1495                | VIEW_STATE_FOCUSED];
1496        ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1497        ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1498                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1499        ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1500                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1501        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1502                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1503                | VIEW_STATE_ENABLED];
1504        ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1505                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1506        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1507                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1508                | VIEW_STATE_ENABLED];
1509        ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1510                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1511                | VIEW_STATE_ENABLED];
1512        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1513                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1514                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1515
1516        PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1517        PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1518                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1519        PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1520                VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1521        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1522                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1523                | VIEW_STATE_PRESSED];
1524        PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1525                VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1526        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1527                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1528                | VIEW_STATE_PRESSED];
1529        PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1530                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1531                | VIEW_STATE_PRESSED];
1532        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1533                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1534                | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1535        PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1536                VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1537        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1538                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1539                | VIEW_STATE_PRESSED];
1540        PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1541                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1542                | VIEW_STATE_PRESSED];
1543        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1544                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1545                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1546        PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1547                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1548                | VIEW_STATE_PRESSED];
1549        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1550                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1551                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1552        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1553                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1554                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1555        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1556                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1557                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1558                | VIEW_STATE_PRESSED];
1559    }
1560
1561    /**
1562     * Accessibility event types that are dispatched for text population.
1563     */
1564    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1565            AccessibilityEvent.TYPE_VIEW_CLICKED
1566            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1567            | AccessibilityEvent.TYPE_VIEW_SELECTED
1568            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1569            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1570            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1571            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1572            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1573            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
1574            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
1575            | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY;
1576
1577    /**
1578     * Temporary Rect currently for use in setBackground().  This will probably
1579     * be extended in the future to hold our own class with more than just
1580     * a Rect. :)
1581     */
1582    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1583
1584    /**
1585     * Map used to store views' tags.
1586     */
1587    private SparseArray<Object> mKeyedTags;
1588
1589    /**
1590     * The next available accessibility id.
1591     */
1592    private static int sNextAccessibilityViewId;
1593
1594    /**
1595     * The animation currently associated with this view.
1596     * @hide
1597     */
1598    protected Animation mCurrentAnimation = null;
1599
1600    /**
1601     * Width as measured during measure pass.
1602     * {@hide}
1603     */
1604    @ViewDebug.ExportedProperty(category = "measurement")
1605    int mMeasuredWidth;
1606
1607    /**
1608     * Height as measured during measure pass.
1609     * {@hide}
1610     */
1611    @ViewDebug.ExportedProperty(category = "measurement")
1612    int mMeasuredHeight;
1613
1614    /**
1615     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1616     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1617     * its display list. This flag, used only when hw accelerated, allows us to clear the
1618     * flag while retaining this information until it's needed (at getDisplayList() time and
1619     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1620     *
1621     * {@hide}
1622     */
1623    boolean mRecreateDisplayList = false;
1624
1625    /**
1626     * The view's identifier.
1627     * {@hide}
1628     *
1629     * @see #setId(int)
1630     * @see #getId()
1631     */
1632    @ViewDebug.ExportedProperty(resolveId = true)
1633    int mID = NO_ID;
1634
1635    /**
1636     * The stable ID of this view for accessibility purposes.
1637     */
1638    int mAccessibilityViewId = NO_ID;
1639
1640    private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
1641
1642    SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent;
1643
1644    /**
1645     * The view's tag.
1646     * {@hide}
1647     *
1648     * @see #setTag(Object)
1649     * @see #getTag()
1650     */
1651    protected Object mTag = null;
1652
1653    // for mPrivateFlags:
1654    /** {@hide} */
1655    static final int PFLAG_WANTS_FOCUS                 = 0x00000001;
1656    /** {@hide} */
1657    static final int PFLAG_FOCUSED                     = 0x00000002;
1658    /** {@hide} */
1659    static final int PFLAG_SELECTED                    = 0x00000004;
1660    /** {@hide} */
1661    static final int PFLAG_IS_ROOT_NAMESPACE           = 0x00000008;
1662    /** {@hide} */
1663    static final int PFLAG_HAS_BOUNDS                  = 0x00000010;
1664    /** {@hide} */
1665    static final int PFLAG_DRAWN                       = 0x00000020;
1666    /**
1667     * When this flag is set, this view is running an animation on behalf of its
1668     * children and should therefore not cancel invalidate requests, even if they
1669     * lie outside of this view's bounds.
1670     *
1671     * {@hide}
1672     */
1673    static final int PFLAG_DRAW_ANIMATION              = 0x00000040;
1674    /** {@hide} */
1675    static final int PFLAG_SKIP_DRAW                   = 0x00000080;
1676    /** {@hide} */
1677    static final int PFLAG_ONLY_DRAWS_BACKGROUND       = 0x00000100;
1678    /** {@hide} */
1679    static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1680    /** {@hide} */
1681    static final int PFLAG_DRAWABLE_STATE_DIRTY        = 0x00000400;
1682    /** {@hide} */
1683    static final int PFLAG_MEASURED_DIMENSION_SET      = 0x00000800;
1684    /** {@hide} */
1685    static final int PFLAG_FORCE_LAYOUT                = 0x00001000;
1686    /** {@hide} */
1687    static final int PFLAG_LAYOUT_REQUIRED             = 0x00002000;
1688
1689    private static final int PFLAG_PRESSED             = 0x00004000;
1690
1691    /** {@hide} */
1692    static final int PFLAG_DRAWING_CACHE_VALID         = 0x00008000;
1693    /**
1694     * Flag used to indicate that this view should be drawn once more (and only once
1695     * more) after its animation has completed.
1696     * {@hide}
1697     */
1698    static final int PFLAG_ANIMATION_STARTED           = 0x00010000;
1699
1700    private static final int PFLAG_SAVE_STATE_CALLED   = 0x00020000;
1701
1702    /**
1703     * Indicates that the View returned true when onSetAlpha() was called and that
1704     * the alpha must be restored.
1705     * {@hide}
1706     */
1707    static final int PFLAG_ALPHA_SET                   = 0x00040000;
1708
1709    /**
1710     * Set by {@link #setScrollContainer(boolean)}.
1711     */
1712    static final int PFLAG_SCROLL_CONTAINER            = 0x00080000;
1713
1714    /**
1715     * Set by {@link #setScrollContainer(boolean)}.
1716     */
1717    static final int PFLAG_SCROLL_CONTAINER_ADDED      = 0x00100000;
1718
1719    /**
1720     * View flag indicating whether this view was invalidated (fully or partially.)
1721     *
1722     * @hide
1723     */
1724    static final int PFLAG_DIRTY                       = 0x00200000;
1725
1726    /**
1727     * View flag indicating whether this view was invalidated by an opaque
1728     * invalidate request.
1729     *
1730     * @hide
1731     */
1732    static final int PFLAG_DIRTY_OPAQUE                = 0x00400000;
1733
1734    /**
1735     * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}.
1736     *
1737     * @hide
1738     */
1739    static final int PFLAG_DIRTY_MASK                  = 0x00600000;
1740
1741    /**
1742     * Indicates whether the background is opaque.
1743     *
1744     * @hide
1745     */
1746    static final int PFLAG_OPAQUE_BACKGROUND           = 0x00800000;
1747
1748    /**
1749     * Indicates whether the scrollbars are opaque.
1750     *
1751     * @hide
1752     */
1753    static final int PFLAG_OPAQUE_SCROLLBARS           = 0x01000000;
1754
1755    /**
1756     * Indicates whether the view is opaque.
1757     *
1758     * @hide
1759     */
1760    static final int PFLAG_OPAQUE_MASK                 = 0x01800000;
1761
1762    /**
1763     * Indicates a prepressed state;
1764     * the short time between ACTION_DOWN and recognizing
1765     * a 'real' press. Prepressed is used to recognize quick taps
1766     * even when they are shorter than ViewConfiguration.getTapTimeout().
1767     *
1768     * @hide
1769     */
1770    private static final int PFLAG_PREPRESSED          = 0x02000000;
1771
1772    /**
1773     * Indicates whether the view is temporarily detached.
1774     *
1775     * @hide
1776     */
1777    static final int PFLAG_CANCEL_NEXT_UP_EVENT        = 0x04000000;
1778
1779    /**
1780     * Indicates that we should awaken scroll bars once attached
1781     *
1782     * @hide
1783     */
1784    private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1785
1786    /**
1787     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1788     * @hide
1789     */
1790    private static final int PFLAG_HOVERED             = 0x10000000;
1791
1792    /**
1793     * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1794     * for transform operations
1795     *
1796     * @hide
1797     */
1798    private static final int PFLAG_PIVOT_EXPLICITLY_SET = 0x20000000;
1799
1800    /** {@hide} */
1801    static final int PFLAG_ACTIVATED                   = 0x40000000;
1802
1803    /**
1804     * Indicates that this view was specifically invalidated, not just dirtied because some
1805     * child view was invalidated. The flag is used to determine when we need to recreate
1806     * a view's display list (as opposed to just returning a reference to its existing
1807     * display list).
1808     *
1809     * @hide
1810     */
1811    static final int PFLAG_INVALIDATED                 = 0x80000000;
1812
1813    /**
1814     * Masks for mPrivateFlags2, as generated by dumpFlags():
1815     *
1816     * |-------|-------|-------|-------|
1817     *                                 1 PFLAG2_DRAG_CAN_ACCEPT
1818     *                                1  PFLAG2_DRAG_HOVERED
1819     *                              11   PFLAG2_LAYOUT_DIRECTION_MASK
1820     *                             1     PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL
1821     *                            1      PFLAG2_LAYOUT_DIRECTION_RESOLVED
1822     *                            11     PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK
1823     *                           1       PFLAG2_TEXT_DIRECTION_FLAGS[1]
1824     *                          1        PFLAG2_TEXT_DIRECTION_FLAGS[2]
1825     *                          11       PFLAG2_TEXT_DIRECTION_FLAGS[3]
1826     *                         1         PFLAG2_TEXT_DIRECTION_FLAGS[4]
1827     *                         1 1       PFLAG2_TEXT_DIRECTION_FLAGS[5]
1828     *                         111       PFLAG2_TEXT_DIRECTION_MASK
1829     *                        1          PFLAG2_TEXT_DIRECTION_RESOLVED
1830     *                       1           PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT
1831     *                     111           PFLAG2_TEXT_DIRECTION_RESOLVED_MASK
1832     *                    1              PFLAG2_TEXT_ALIGNMENT_FLAGS[1]
1833     *                   1               PFLAG2_TEXT_ALIGNMENT_FLAGS[2]
1834     *                   11              PFLAG2_TEXT_ALIGNMENT_FLAGS[3]
1835     *                  1                PFLAG2_TEXT_ALIGNMENT_FLAGS[4]
1836     *                  1 1              PFLAG2_TEXT_ALIGNMENT_FLAGS[5]
1837     *                  11               PFLAG2_TEXT_ALIGNMENT_FLAGS[6]
1838     *                  111              PFLAG2_TEXT_ALIGNMENT_MASK
1839     *                 1                 PFLAG2_TEXT_ALIGNMENT_RESOLVED
1840     *                1                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT
1841     *              111                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK
1842     *           111                     PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK
1843     *         11                        PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK
1844     *       1                           PFLAG2_ACCESSIBILITY_FOCUSED
1845     *      1                            PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED
1846     *     1                             PFLAG2_VIEW_QUICK_REJECTED
1847     *    1                              PFLAG2_PADDING_RESOLVED
1848     *   1                               PFLAG2_DRAWABLE_RESOLVED
1849     *  1                                PFLAG2_HAS_TRANSIENT_STATE
1850     * |-------|-------|-------|-------|
1851     */
1852
1853    /**
1854     * Indicates that this view has reported that it can accept the current drag's content.
1855     * Cleared when the drag operation concludes.
1856     * @hide
1857     */
1858    static final int PFLAG2_DRAG_CAN_ACCEPT            = 0x00000001;
1859
1860    /**
1861     * Indicates that this view is currently directly under the drag location in a
1862     * drag-and-drop operation involving content that it can accept.  Cleared when
1863     * the drag exits the view, or when the drag operation concludes.
1864     * @hide
1865     */
1866    static final int PFLAG2_DRAG_HOVERED               = 0x00000002;
1867
1868    /** @hide */
1869    @IntDef({
1870        LAYOUT_DIRECTION_LTR,
1871        LAYOUT_DIRECTION_RTL,
1872        LAYOUT_DIRECTION_INHERIT,
1873        LAYOUT_DIRECTION_LOCALE
1874    })
1875    @Retention(RetentionPolicy.SOURCE)
1876    // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection
1877    public @interface LayoutDir {}
1878
1879    /** @hide */
1880    @IntDef({
1881        LAYOUT_DIRECTION_LTR,
1882        LAYOUT_DIRECTION_RTL
1883    })
1884    @Retention(RetentionPolicy.SOURCE)
1885    public @interface ResolvedLayoutDir {}
1886
1887    /**
1888     * Horizontal layout direction of this view is from Left to Right.
1889     * Use with {@link #setLayoutDirection}.
1890     */
1891    public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR;
1892
1893    /**
1894     * Horizontal layout direction of this view is from Right to Left.
1895     * Use with {@link #setLayoutDirection}.
1896     */
1897    public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL;
1898
1899    /**
1900     * Horizontal layout direction of this view is inherited from its parent.
1901     * Use with {@link #setLayoutDirection}.
1902     */
1903    public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT;
1904
1905    /**
1906     * Horizontal layout direction of this view is from deduced from the default language
1907     * script for the locale. Use with {@link #setLayoutDirection}.
1908     */
1909    public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE;
1910
1911    /**
1912     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1913     * @hide
1914     */
1915    static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2;
1916
1917    /**
1918     * Mask for use with private flags indicating bits used for horizontal layout direction.
1919     * @hide
1920     */
1921    static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1922
1923    /**
1924     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
1925     * right-to-left direction.
1926     * @hide
1927     */
1928    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1929
1930    /**
1931     * Indicates whether the view horizontal layout direction has been resolved.
1932     * @hide
1933     */
1934    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1935
1936    /**
1937     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
1938     * @hide
1939     */
1940    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C
1941            << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1942
1943    /*
1944     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
1945     * flag value.
1946     * @hide
1947     */
1948    private static final int[] LAYOUT_DIRECTION_FLAGS = {
1949            LAYOUT_DIRECTION_LTR,
1950            LAYOUT_DIRECTION_RTL,
1951            LAYOUT_DIRECTION_INHERIT,
1952            LAYOUT_DIRECTION_LOCALE
1953    };
1954
1955    /**
1956     * Default horizontal layout direction.
1957     */
1958    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
1959
1960    /**
1961     * Default horizontal layout direction.
1962     * @hide
1963     */
1964    static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR;
1965
1966    /**
1967     * Text direction is inherited thru {@link ViewGroup}
1968     */
1969    public static final int TEXT_DIRECTION_INHERIT = 0;
1970
1971    /**
1972     * Text direction is using "first strong algorithm". The first strong directional character
1973     * determines the paragraph direction. If there is no strong directional character, the
1974     * paragraph direction is the view's resolved layout direction.
1975     */
1976    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
1977
1978    /**
1979     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
1980     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
1981     * If there are neither, the paragraph direction is the view's resolved layout direction.
1982     */
1983    public static final int TEXT_DIRECTION_ANY_RTL = 2;
1984
1985    /**
1986     * Text direction is forced to LTR.
1987     */
1988    public static final int TEXT_DIRECTION_LTR = 3;
1989
1990    /**
1991     * Text direction is forced to RTL.
1992     */
1993    public static final int TEXT_DIRECTION_RTL = 4;
1994
1995    /**
1996     * Text direction is coming from the system Locale.
1997     */
1998    public static final int TEXT_DIRECTION_LOCALE = 5;
1999
2000    /**
2001     * Default text direction is inherited
2002     */
2003    private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
2004
2005    /**
2006     * Default resolved text direction
2007     * @hide
2008     */
2009    static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG;
2010
2011    /**
2012     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
2013     * @hide
2014     */
2015    static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6;
2016
2017    /**
2018     * Mask for use with private flags indicating bits used for text direction.
2019     * @hide
2020     */
2021    static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007
2022            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2023
2024    /**
2025     * Array of text direction flags for mapping attribute "textDirection" to correct
2026     * flag value.
2027     * @hide
2028     */
2029    private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = {
2030            TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2031            TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2032            TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2033            TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2034            TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2035            TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT
2036    };
2037
2038    /**
2039     * Indicates whether the view text direction has been resolved.
2040     * @hide
2041     */
2042    static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008
2043            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2044
2045    /**
2046     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2047     * @hide
2048     */
2049    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
2050
2051    /**
2052     * Mask for use with private flags indicating bits used for resolved text direction.
2053     * @hide
2054     */
2055    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007
2056            << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2057
2058    /**
2059     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
2060     * @hide
2061     */
2062    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT =
2063            TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2064
2065    /** @hide */
2066    @IntDef({
2067        TEXT_ALIGNMENT_INHERIT,
2068        TEXT_ALIGNMENT_GRAVITY,
2069        TEXT_ALIGNMENT_CENTER,
2070        TEXT_ALIGNMENT_TEXT_START,
2071        TEXT_ALIGNMENT_TEXT_END,
2072        TEXT_ALIGNMENT_VIEW_START,
2073        TEXT_ALIGNMENT_VIEW_END
2074    })
2075    @Retention(RetentionPolicy.SOURCE)
2076    public @interface TextAlignment {}
2077
2078    /**
2079     * Default text alignment. The text alignment of this View is inherited from its parent.
2080     * Use with {@link #setTextAlignment(int)}
2081     */
2082    public static final int TEXT_ALIGNMENT_INHERIT = 0;
2083
2084    /**
2085     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
2086     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
2087     *
2088     * Use with {@link #setTextAlignment(int)}
2089     */
2090    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
2091
2092    /**
2093     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
2094     *
2095     * Use with {@link #setTextAlignment(int)}
2096     */
2097    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
2098
2099    /**
2100     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
2101     *
2102     * Use with {@link #setTextAlignment(int)}
2103     */
2104    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
2105
2106    /**
2107     * Center the paragraph, e.g. ALIGN_CENTER.
2108     *
2109     * Use with {@link #setTextAlignment(int)}
2110     */
2111    public static final int TEXT_ALIGNMENT_CENTER = 4;
2112
2113    /**
2114     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
2115     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
2116     *
2117     * Use with {@link #setTextAlignment(int)}
2118     */
2119    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
2120
2121    /**
2122     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
2123     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
2124     *
2125     * Use with {@link #setTextAlignment(int)}
2126     */
2127    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
2128
2129    /**
2130     * Default text alignment is inherited
2131     */
2132    private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2133
2134    /**
2135     * Default resolved text alignment
2136     * @hide
2137     */
2138    static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2139
2140    /**
2141      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2142      * @hide
2143      */
2144    static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13;
2145
2146    /**
2147      * Mask for use with private flags indicating bits used for text alignment.
2148      * @hide
2149      */
2150    static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2151
2152    /**
2153     * Array of text direction flags for mapping attribute "textAlignment" to correct
2154     * flag value.
2155     * @hide
2156     */
2157    private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = {
2158            TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2159            TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2160            TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2161            TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2162            TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2163            TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2164            TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
2165    };
2166
2167    /**
2168     * Indicates whether the view text alignment has been resolved.
2169     * @hide
2170     */
2171    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2172
2173    /**
2174     * Bit shift to get the resolved text alignment.
2175     * @hide
2176     */
2177    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2178
2179    /**
2180     * Mask for use with private flags indicating bits used for text alignment.
2181     * @hide
2182     */
2183    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007
2184            << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2185
2186    /**
2187     * Indicates whether if the view text alignment has been resolved to gravity
2188     */
2189    private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2190            TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2191
2192    // Accessiblity constants for mPrivateFlags2
2193
2194    /**
2195     * Shift for the bits in {@link #mPrivateFlags2} related to the
2196     * "importantForAccessibility" attribute.
2197     */
2198    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2199
2200    /**
2201     * Automatically determine whether a view is important for accessibility.
2202     */
2203    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2204
2205    /**
2206     * The view is important for accessibility.
2207     */
2208    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2209
2210    /**
2211     * The view is not important for accessibility.
2212     */
2213    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2214
2215    /**
2216     * The view is not important for accessibility, nor are any of its
2217     * descendant views.
2218     */
2219    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004;
2220
2221    /**
2222     * The default whether the view is important for accessibility.
2223     */
2224    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2225
2226    /**
2227     * Mask for obtainig the bits which specify how to determine
2228     * whether a view is important for accessibility.
2229     */
2230    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2231        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO
2232        | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS)
2233        << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2234
2235    /**
2236     * Shift for the bits in {@link #mPrivateFlags2} related to the
2237     * "accessibilityLiveRegion" attribute.
2238     */
2239    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23;
2240
2241    /**
2242     * Live region mode specifying that accessibility services should not
2243     * automatically announce changes to this view. This is the default live
2244     * region mode for most views.
2245     * <p>
2246     * Use with {@link #setAccessibilityLiveRegion(int)}.
2247     */
2248    public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000;
2249
2250    /**
2251     * Live region mode specifying that accessibility services should announce
2252     * changes to this view.
2253     * <p>
2254     * Use with {@link #setAccessibilityLiveRegion(int)}.
2255     */
2256    public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001;
2257
2258    /**
2259     * Live region mode specifying that accessibility services should interrupt
2260     * ongoing speech to immediately announce changes to this view.
2261     * <p>
2262     * Use with {@link #setAccessibilityLiveRegion(int)}.
2263     */
2264    public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002;
2265
2266    /**
2267     * The default whether the view is important for accessibility.
2268     */
2269    static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE;
2270
2271    /**
2272     * Mask for obtaining the bits which specify a view's accessibility live
2273     * region mode.
2274     */
2275    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE
2276            | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE)
2277            << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
2278
2279    /**
2280     * Flag indicating whether a view has accessibility focus.
2281     */
2282    static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000;
2283
2284    /**
2285     * Flag whether the accessibility state of the subtree rooted at this view changed.
2286     */
2287    static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000;
2288
2289    /**
2290     * Flag indicating whether a view failed the quickReject() check in draw(). This condition
2291     * is used to check whether later changes to the view's transform should invalidate the
2292     * view to force the quickReject test to run again.
2293     */
2294    static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000;
2295
2296    /**
2297     * Flag indicating that start/end padding has been resolved into left/right padding
2298     * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()}
2299     * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved
2300     * during measurement. In some special cases this is required such as when an adapter-based
2301     * view measures prospective children without attaching them to a window.
2302     */
2303    static final int PFLAG2_PADDING_RESOLVED = 0x20000000;
2304
2305    /**
2306     * Flag indicating that the start/end drawables has been resolved into left/right ones.
2307     */
2308    static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000;
2309
2310    /**
2311     * Indicates that the view is tracking some sort of transient state
2312     * that the app should not need to be aware of, but that the framework
2313     * should take special care to preserve.
2314     */
2315    static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000;
2316
2317    /**
2318     * Group of bits indicating that RTL properties resolution is done.
2319     */
2320    static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED |
2321            PFLAG2_TEXT_DIRECTION_RESOLVED |
2322            PFLAG2_TEXT_ALIGNMENT_RESOLVED |
2323            PFLAG2_PADDING_RESOLVED |
2324            PFLAG2_DRAWABLE_RESOLVED;
2325
2326    // There are a couple of flags left in mPrivateFlags2
2327
2328    /* End of masks for mPrivateFlags2 */
2329
2330    /**
2331     * Masks for mPrivateFlags3, as generated by dumpFlags():
2332     *
2333     * |-------|-------|-------|-------|
2334     *                                 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM
2335     *                                1  PFLAG3_VIEW_IS_ANIMATING_ALPHA
2336     *                               1   PFLAG3_IS_LAID_OUT
2337     *                              1    PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT
2338     *                             1     PFLAG3_CALLED_SUPER
2339     * |-------|-------|-------|-------|
2340     */
2341
2342    /**
2343     * Flag indicating that view has a transform animation set on it. This is used to track whether
2344     * an animation is cleared between successive frames, in order to tell the associated
2345     * DisplayList to clear its animation matrix.
2346     */
2347    static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1;
2348
2349    /**
2350     * Flag indicating that view has an alpha animation set on it. This is used to track whether an
2351     * animation is cleared between successive frames, in order to tell the associated
2352     * DisplayList to restore its alpha value.
2353     */
2354    static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2;
2355
2356    /**
2357     * Flag indicating that the view has been through at least one layout since it
2358     * was last attached to a window.
2359     */
2360    static final int PFLAG3_IS_LAID_OUT = 0x4;
2361
2362    /**
2363     * Flag indicating that a call to measure() was skipped and should be done
2364     * instead when layout() is invoked.
2365     */
2366    static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8;
2367
2368    /**
2369     * Flag indicating that an overridden method correctly  called down to
2370     * the superclass implementation as required by the API spec.
2371     */
2372    static final int PFLAG3_CALLED_SUPER = 0x10;
2373
2374    /**
2375     * Flag indicating that an view will be clipped to its outline.
2376     */
2377    static final int PFLAG3_CLIP_TO_OUTLINE = 0x20;
2378
2379    /**
2380     * Flag indicating that we're in the process of applying window insets.
2381     */
2382    static final int PFLAG3_APPLYING_INSETS = 0x40;
2383
2384    /**
2385     * Flag indicating that we're in the process of fitting system windows using the old method.
2386     */
2387    static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x80;
2388
2389    /**
2390     * Flag indicating that an view will cast a shadow onto the Z=0 plane if elevated.
2391     */
2392    static final int PFLAG3_CASTS_SHADOW = 0x100;
2393
2394    /**
2395     * Flag indicating that view will be transformed by the global camera if rotated in 3d, or given
2396     * a non-0 Z translation.
2397     */
2398    static final int PFLAG3_USES_GLOBAL_CAMERA = 0x200;
2399
2400    /* End of masks for mPrivateFlags3 */
2401
2402    static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED;
2403
2404    /**
2405     * Always allow a user to over-scroll this view, provided it is a
2406     * view that can scroll.
2407     *
2408     * @see #getOverScrollMode()
2409     * @see #setOverScrollMode(int)
2410     */
2411    public static final int OVER_SCROLL_ALWAYS = 0;
2412
2413    /**
2414     * Allow a user to over-scroll this view only if the content is large
2415     * enough to meaningfully scroll, provided it is a view that can scroll.
2416     *
2417     * @see #getOverScrollMode()
2418     * @see #setOverScrollMode(int)
2419     */
2420    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2421
2422    /**
2423     * Never allow a user to over-scroll this view.
2424     *
2425     * @see #getOverScrollMode()
2426     * @see #setOverScrollMode(int)
2427     */
2428    public static final int OVER_SCROLL_NEVER = 2;
2429
2430    /**
2431     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2432     * requested the system UI (status bar) to be visible (the default).
2433     *
2434     * @see #setSystemUiVisibility(int)
2435     */
2436    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2437
2438    /**
2439     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2440     * system UI to enter an unobtrusive "low profile" mode.
2441     *
2442     * <p>This is for use in games, book readers, video players, or any other
2443     * "immersive" application where the usual system chrome is deemed too distracting.
2444     *
2445     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2446     *
2447     * @see #setSystemUiVisibility(int)
2448     */
2449    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2450
2451    /**
2452     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2453     * system navigation be temporarily hidden.
2454     *
2455     * <p>This is an even less obtrusive state than that called for by
2456     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2457     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2458     * those to disappear. This is useful (in conjunction with the
2459     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2460     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2461     * window flags) for displaying content using every last pixel on the display.
2462     *
2463     * <p>There is a limitation: because navigation controls are so important, the least user
2464     * interaction will cause them to reappear immediately.  When this happens, both
2465     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2466     * so that both elements reappear at the same time.
2467     *
2468     * @see #setSystemUiVisibility(int)
2469     */
2470    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2471
2472    /**
2473     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2474     * into the normal fullscreen mode so that its content can take over the screen
2475     * while still allowing the user to interact with the application.
2476     *
2477     * <p>This has the same visual effect as
2478     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2479     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2480     * meaning that non-critical screen decorations (such as the status bar) will be
2481     * hidden while the user is in the View's window, focusing the experience on
2482     * that content.  Unlike the window flag, if you are using ActionBar in
2483     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2484     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2485     * hide the action bar.
2486     *
2487     * <p>This approach to going fullscreen is best used over the window flag when
2488     * it is a transient state -- that is, the application does this at certain
2489     * points in its user interaction where it wants to allow the user to focus
2490     * on content, but not as a continuous state.  For situations where the application
2491     * would like to simply stay full screen the entire time (such as a game that
2492     * wants to take over the screen), the
2493     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2494     * is usually a better approach.  The state set here will be removed by the system
2495     * in various situations (such as the user moving to another application) like
2496     * the other system UI states.
2497     *
2498     * <p>When using this flag, the application should provide some easy facility
2499     * for the user to go out of it.  A common example would be in an e-book
2500     * reader, where tapping on the screen brings back whatever screen and UI
2501     * decorations that had been hidden while the user was immersed in reading
2502     * the book.
2503     *
2504     * @see #setSystemUiVisibility(int)
2505     */
2506    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2507
2508    /**
2509     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2510     * flags, we would like a stable view of the content insets given to
2511     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2512     * will always represent the worst case that the application can expect
2513     * as a continuous state.  In the stock Android UI this is the space for
2514     * the system bar, nav bar, and status bar, but not more transient elements
2515     * such as an input method.
2516     *
2517     * The stable layout your UI sees is based on the system UI modes you can
2518     * switch to.  That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
2519     * then you will get a stable layout for changes of the
2520     * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
2521     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
2522     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
2523     * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
2524     * with a stable layout.  (Note that you should avoid using
2525     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
2526     *
2527     * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN}
2528     * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
2529     * then a hidden status bar will be considered a "stable" state for purposes
2530     * here.  This allows your UI to continually hide the status bar, while still
2531     * using the system UI flags to hide the action bar while still retaining
2532     * a stable layout.  Note that changing the window fullscreen flag will never
2533     * provide a stable layout for a clean transition.
2534     *
2535     * <p>If you are using ActionBar in
2536     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2537     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2538     * insets it adds to those given to the application.
2539     */
2540    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2541
2542    /**
2543     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2544     * to be layed out as if it has requested
2545     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2546     * allows it to avoid artifacts when switching in and out of that mode, at
2547     * the expense that some of its user interface may be covered by screen
2548     * decorations when they are shown.  You can perform layout of your inner
2549     * UI elements to account for the navigation system UI through the
2550     * {@link #fitSystemWindows(Rect)} method.
2551     */
2552    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2553
2554    /**
2555     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2556     * to be layed out as if it has requested
2557     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2558     * allows it to avoid artifacts when switching in and out of that mode, at
2559     * the expense that some of its user interface may be covered by screen
2560     * decorations when they are shown.  You can perform layout of your inner
2561     * UI elements to account for non-fullscreen system UI through the
2562     * {@link #fitSystemWindows(Rect)} method.
2563     */
2564    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2565
2566    /**
2567     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2568     * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  If this flag is
2569     * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any
2570     * user interaction.
2571     * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only
2572     * has an effect when used in combination with that flag.</p>
2573     */
2574    public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800;
2575
2576    /**
2577     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2578     * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation
2579     * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  Use this flag to create an immersive
2580     * experience while also hiding the system bars.  If this flag is not set,
2581     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user
2582     * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system
2583     * if the user swipes from the top of the screen.
2584     * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with
2585     * system gestures, such as swiping from the top of the screen.  These transient system bars
2586     * will overlay app’s content, may have some degree of transparency, and will automatically
2587     * hide after a short timeout.
2588     * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and
2589     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination
2590     * with one or both of those flags.</p>
2591     */
2592    public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000;
2593
2594    /**
2595     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2596     */
2597    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2598
2599    /**
2600     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2601     */
2602    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2603
2604    /**
2605     * @hide
2606     *
2607     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2608     * out of the public fields to keep the undefined bits out of the developer's way.
2609     *
2610     * Flag to make the status bar not expandable.  Unless you also
2611     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
2612     */
2613    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
2614
2615    /**
2616     * @hide
2617     *
2618     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2619     * out of the public fields to keep the undefined bits out of the developer's way.
2620     *
2621     * Flag to hide notification icons and scrolling ticker text.
2622     */
2623    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
2624
2625    /**
2626     * @hide
2627     *
2628     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2629     * out of the public fields to keep the undefined bits out of the developer's way.
2630     *
2631     * Flag to disable incoming notification alerts.  This will not block
2632     * icons, but it will block sound, vibrating and other visual or aural notifications.
2633     */
2634    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
2635
2636    /**
2637     * @hide
2638     *
2639     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2640     * out of the public fields to keep the undefined bits out of the developer's way.
2641     *
2642     * Flag to hide only the scrolling ticker.  Note that
2643     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
2644     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
2645     */
2646    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
2647
2648    /**
2649     * @hide
2650     *
2651     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2652     * out of the public fields to keep the undefined bits out of the developer's way.
2653     *
2654     * Flag to hide the center system info area.
2655     */
2656    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
2657
2658    /**
2659     * @hide
2660     *
2661     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2662     * out of the public fields to keep the undefined bits out of the developer's way.
2663     *
2664     * Flag to hide only the home button.  Don't use this
2665     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2666     */
2667    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
2668
2669    /**
2670     * @hide
2671     *
2672     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2673     * out of the public fields to keep the undefined bits out of the developer's way.
2674     *
2675     * Flag to hide only the back button. Don't use this
2676     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2677     */
2678    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
2679
2680    /**
2681     * @hide
2682     *
2683     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2684     * out of the public fields to keep the undefined bits out of the developer's way.
2685     *
2686     * Flag to hide only the clock.  You might use this if your activity has
2687     * its own clock making the status bar's clock redundant.
2688     */
2689    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
2690
2691    /**
2692     * @hide
2693     *
2694     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2695     * out of the public fields to keep the undefined bits out of the developer's way.
2696     *
2697     * Flag to hide only the recent apps button. Don't use this
2698     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2699     */
2700    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
2701
2702    /**
2703     * @hide
2704     *
2705     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2706     * out of the public fields to keep the undefined bits out of the developer's way.
2707     *
2708     * Flag to disable the global search gesture. Don't use this
2709     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2710     */
2711    public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000;
2712
2713    /**
2714     * @hide
2715     *
2716     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2717     * out of the public fields to keep the undefined bits out of the developer's way.
2718     *
2719     * Flag to specify that the status bar is displayed in transient mode.
2720     */
2721    public static final int STATUS_BAR_TRANSIENT = 0x04000000;
2722
2723    /**
2724     * @hide
2725     *
2726     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2727     * out of the public fields to keep the undefined bits out of the developer's way.
2728     *
2729     * Flag to specify that the navigation bar is displayed in transient mode.
2730     */
2731    public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000;
2732
2733    /**
2734     * @hide
2735     *
2736     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2737     * out of the public fields to keep the undefined bits out of the developer's way.
2738     *
2739     * Flag to specify that the hidden status bar would like to be shown.
2740     */
2741    public static final int STATUS_BAR_UNHIDE = 0x10000000;
2742
2743    /**
2744     * @hide
2745     *
2746     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2747     * out of the public fields to keep the undefined bits out of the developer's way.
2748     *
2749     * Flag to specify that the hidden navigation bar would like to be shown.
2750     */
2751    public static final int NAVIGATION_BAR_UNHIDE = 0x20000000;
2752
2753    /**
2754     * @hide
2755     *
2756     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2757     * out of the public fields to keep the undefined bits out of the developer's way.
2758     *
2759     * Flag to specify that the status bar is displayed in translucent mode.
2760     */
2761    public static final int STATUS_BAR_TRANSLUCENT = 0x40000000;
2762
2763    /**
2764     * @hide
2765     *
2766     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2767     * out of the public fields to keep the undefined bits out of the developer's way.
2768     *
2769     * Flag to specify that the navigation bar is displayed in translucent mode.
2770     */
2771    public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000;
2772
2773    /**
2774     * @hide
2775     */
2776    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF;
2777
2778    /**
2779     * These are the system UI flags that can be cleared by events outside
2780     * of an application.  Currently this is just the ability to tap on the
2781     * screen while hiding the navigation bar to have it return.
2782     * @hide
2783     */
2784    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
2785            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
2786            | SYSTEM_UI_FLAG_FULLSCREEN;
2787
2788    /**
2789     * Flags that can impact the layout in relation to system UI.
2790     */
2791    public static final int SYSTEM_UI_LAYOUT_FLAGS =
2792            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
2793            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
2794
2795    /** @hide */
2796    @IntDef(flag = true,
2797            value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION })
2798    @Retention(RetentionPolicy.SOURCE)
2799    public @interface FindViewFlags {}
2800
2801    /**
2802     * Find views that render the specified text.
2803     *
2804     * @see #findViewsWithText(ArrayList, CharSequence, int)
2805     */
2806    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
2807
2808    /**
2809     * Find find views that contain the specified content description.
2810     *
2811     * @see #findViewsWithText(ArrayList, CharSequence, int)
2812     */
2813    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
2814
2815    /**
2816     * Find views that contain {@link AccessibilityNodeProvider}. Such
2817     * a View is a root of virtual view hierarchy and may contain the searched
2818     * text. If this flag is set Views with providers are automatically
2819     * added and it is a responsibility of the client to call the APIs of
2820     * the provider to determine whether the virtual tree rooted at this View
2821     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
2822     * representing the virtual views with this text.
2823     *
2824     * @see #findViewsWithText(ArrayList, CharSequence, int)
2825     *
2826     * @hide
2827     */
2828    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
2829
2830    /**
2831     * The undefined cursor position.
2832     *
2833     * @hide
2834     */
2835    public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1;
2836
2837    /**
2838     * Indicates that the screen has changed state and is now off.
2839     *
2840     * @see #onScreenStateChanged(int)
2841     */
2842    public static final int SCREEN_STATE_OFF = 0x0;
2843
2844    /**
2845     * Indicates that the screen has changed state and is now on.
2846     *
2847     * @see #onScreenStateChanged(int)
2848     */
2849    public static final int SCREEN_STATE_ON = 0x1;
2850
2851    /**
2852     * Controls the over-scroll mode for this view.
2853     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
2854     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
2855     * and {@link #OVER_SCROLL_NEVER}.
2856     */
2857    private int mOverScrollMode;
2858
2859    /**
2860     * The parent this view is attached to.
2861     * {@hide}
2862     *
2863     * @see #getParent()
2864     */
2865    protected ViewParent mParent;
2866
2867    /**
2868     * {@hide}
2869     */
2870    AttachInfo mAttachInfo;
2871
2872    /**
2873     * {@hide}
2874     */
2875    @ViewDebug.ExportedProperty(flagMapping = {
2876        @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT,
2877                name = "FORCE_LAYOUT"),
2878        @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED,
2879                name = "LAYOUT_REQUIRED"),
2880        @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID,
2881            name = "DRAWING_CACHE_INVALID", outputIf = false),
2882        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true),
2883        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false),
2884        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
2885        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY")
2886    })
2887    int mPrivateFlags;
2888    int mPrivateFlags2;
2889    int mPrivateFlags3;
2890
2891    /**
2892     * This view's request for the visibility of the status bar.
2893     * @hide
2894     */
2895    @ViewDebug.ExportedProperty(flagMapping = {
2896        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
2897                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
2898                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
2899        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2900                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2901                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
2902        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
2903                                equals = SYSTEM_UI_FLAG_VISIBLE,
2904                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
2905    })
2906    int mSystemUiVisibility;
2907
2908    /**
2909     * Reference count for transient state.
2910     * @see #setHasTransientState(boolean)
2911     */
2912    int mTransientStateCount = 0;
2913
2914    /**
2915     * Count of how many windows this view has been attached to.
2916     */
2917    int mWindowAttachCount;
2918
2919    /**
2920     * The layout parameters associated with this view and used by the parent
2921     * {@link android.view.ViewGroup} to determine how this view should be
2922     * laid out.
2923     * {@hide}
2924     */
2925    protected ViewGroup.LayoutParams mLayoutParams;
2926
2927    /**
2928     * The view flags hold various views states.
2929     * {@hide}
2930     */
2931    @ViewDebug.ExportedProperty
2932    int mViewFlags;
2933
2934    static class TransformationInfo {
2935        /**
2936         * The transform matrix for the View. This transform is calculated internally
2937         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2938         * is used by default. Do *not* use this variable directly; instead call
2939         * getMatrix(), which will automatically recalculate the matrix if necessary
2940         * to get the correct matrix based on the latest rotation and scale properties.
2941         */
2942        private final Matrix mMatrix = new Matrix();
2943
2944        /**
2945         * The transform matrix for the View. This transform is calculated internally
2946         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2947         * is used by default. Do *not* use this variable directly; instead call
2948         * getInverseMatrix(), which will automatically recalculate the matrix if necessary
2949         * to get the correct matrix based on the latest rotation and scale properties.
2950         */
2951        private Matrix mInverseMatrix;
2952
2953        /**
2954         * An internal variable that tracks whether we need to recalculate the
2955         * transform matrix, based on whether the rotation or scaleX/Y properties
2956         * have changed since the matrix was last calculated.
2957         */
2958        boolean mMatrixDirty = false;
2959
2960        /**
2961         * An internal variable that tracks whether we need to recalculate the
2962         * transform matrix, based on whether the rotation or scaleX/Y properties
2963         * have changed since the matrix was last calculated.
2964         */
2965        private boolean mInverseMatrixDirty = true;
2966
2967        /**
2968         * A variable that tracks whether we need to recalculate the
2969         * transform matrix, based on whether the rotation or scaleX/Y properties
2970         * have changed since the matrix was last calculated. This variable
2971         * is only valid after a call to updateMatrix() or to a function that
2972         * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
2973         */
2974        private boolean mMatrixIsIdentity = true;
2975
2976        /**
2977         * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
2978         */
2979        private Camera mCamera = null;
2980
2981        /**
2982         * This matrix is used when computing the matrix for 3D rotations.
2983         */
2984        private Matrix matrix3D = null;
2985
2986        /**
2987         * These prev values are used to recalculate a centered pivot point when necessary. The
2988         * pivot point is only used in matrix operations (when rotation, scale, or translation are
2989         * set), so thes values are only used then as well.
2990         */
2991        private int mPrevWidth = -1;
2992        private int mPrevHeight = -1;
2993
2994        /**
2995         * The degrees rotation around the vertical axis through the pivot point.
2996         */
2997        @ViewDebug.ExportedProperty
2998        float mRotationY = 0f;
2999
3000        /**
3001         * The degrees rotation around the horizontal axis through the pivot point.
3002         */
3003        @ViewDebug.ExportedProperty
3004        float mRotationX = 0f;
3005
3006        /**
3007         * The degrees rotation around the pivot point.
3008         */
3009        @ViewDebug.ExportedProperty
3010        float mRotation = 0f;
3011
3012        /**
3013         * The amount of translation of the object away from its left property (post-layout).
3014         */
3015        @ViewDebug.ExportedProperty
3016        float mTranslationX = 0f;
3017
3018        /**
3019         * The amount of translation of the object away from its top property (post-layout).
3020         */
3021        @ViewDebug.ExportedProperty
3022        float mTranslationY = 0f;
3023
3024        @ViewDebug.ExportedProperty
3025        float mTranslationZ = 0f;
3026
3027        /**
3028         * The amount of scale in the x direction around the pivot point. A
3029         * value of 1 means no scaling is applied.
3030         */
3031        @ViewDebug.ExportedProperty
3032        float mScaleX = 1f;
3033
3034        /**
3035         * The amount of scale in the y direction around the pivot point. A
3036         * value of 1 means no scaling is applied.
3037         */
3038        @ViewDebug.ExportedProperty
3039        float mScaleY = 1f;
3040
3041        /**
3042         * The x location of the point around which the view is rotated and scaled.
3043         */
3044        @ViewDebug.ExportedProperty
3045        float mPivotX = 0f;
3046
3047        /**
3048         * The y location of the point around which the view is rotated and scaled.
3049         */
3050        @ViewDebug.ExportedProperty
3051        float mPivotY = 0f;
3052
3053        /**
3054         * The opacity of the View. This is a value from 0 to 1, where 0 means
3055         * completely transparent and 1 means completely opaque.
3056         */
3057        @ViewDebug.ExportedProperty
3058        float mAlpha = 1f;
3059
3060        /**
3061         * The opacity of the view as manipulated by the Fade transition. This is a hidden
3062         * property only used by transitions, which is composited with the other alpha
3063         * values to calculate the final visual alpha value.
3064         */
3065        float mTransitionAlpha = 1f;
3066    }
3067
3068    TransformationInfo mTransformationInfo;
3069
3070    /**
3071     * Current clip bounds. to which all drawing of this view are constrained.
3072     */
3073    private Rect mClipBounds = null;
3074
3075    private boolean mLastIsOpaque;
3076
3077    /**
3078     * Convenience value to check for float values that are close enough to zero to be considered
3079     * zero.
3080     */
3081    private static final float NONZERO_EPSILON = .001f;
3082
3083    /**
3084     * The distance in pixels from the left edge of this view's parent
3085     * to the left edge of this view.
3086     * {@hide}
3087     */
3088    @ViewDebug.ExportedProperty(category = "layout")
3089    protected int mLeft;
3090    /**
3091     * The distance in pixels from the left edge of this view's parent
3092     * to the right edge of this view.
3093     * {@hide}
3094     */
3095    @ViewDebug.ExportedProperty(category = "layout")
3096    protected int mRight;
3097    /**
3098     * The distance in pixels from the top edge of this view's parent
3099     * to the top edge of this view.
3100     * {@hide}
3101     */
3102    @ViewDebug.ExportedProperty(category = "layout")
3103    protected int mTop;
3104    /**
3105     * The distance in pixels from the top edge of this view's parent
3106     * to the bottom edge of this view.
3107     * {@hide}
3108     */
3109    @ViewDebug.ExportedProperty(category = "layout")
3110    protected int mBottom;
3111
3112    /**
3113     * The offset, in pixels, by which the content of this view is scrolled
3114     * horizontally.
3115     * {@hide}
3116     */
3117    @ViewDebug.ExportedProperty(category = "scrolling")
3118    protected int mScrollX;
3119    /**
3120     * The offset, in pixels, by which the content of this view is scrolled
3121     * vertically.
3122     * {@hide}
3123     */
3124    @ViewDebug.ExportedProperty(category = "scrolling")
3125    protected int mScrollY;
3126
3127    /**
3128     * The left padding in pixels, that is the distance in pixels between the
3129     * left edge of this view and the left edge of its content.
3130     * {@hide}
3131     */
3132    @ViewDebug.ExportedProperty(category = "padding")
3133    protected int mPaddingLeft = 0;
3134    /**
3135     * The right padding in pixels, that is the distance in pixels between the
3136     * right edge of this view and the right edge of its content.
3137     * {@hide}
3138     */
3139    @ViewDebug.ExportedProperty(category = "padding")
3140    protected int mPaddingRight = 0;
3141    /**
3142     * The top padding in pixels, that is the distance in pixels between the
3143     * top edge of this view and the top edge of its content.
3144     * {@hide}
3145     */
3146    @ViewDebug.ExportedProperty(category = "padding")
3147    protected int mPaddingTop;
3148    /**
3149     * The bottom padding in pixels, that is the distance in pixels between the
3150     * bottom edge of this view and the bottom edge of its content.
3151     * {@hide}
3152     */
3153    @ViewDebug.ExportedProperty(category = "padding")
3154    protected int mPaddingBottom;
3155
3156    /**
3157     * The layout insets in pixels, that is the distance in pixels between the
3158     * visible edges of this view its bounds.
3159     */
3160    private Insets mLayoutInsets;
3161
3162    /**
3163     * Briefly describes the view and is primarily used for accessibility support.
3164     */
3165    private CharSequence mContentDescription;
3166
3167    /**
3168     * Specifies the id of a view for which this view serves as a label for
3169     * accessibility purposes.
3170     */
3171    private int mLabelForId = View.NO_ID;
3172
3173    /**
3174     * Predicate for matching labeled view id with its label for
3175     * accessibility purposes.
3176     */
3177    private MatchLabelForPredicate mMatchLabelForPredicate;
3178
3179    /**
3180     * Predicate for matching a view by its id.
3181     */
3182    private MatchIdPredicate mMatchIdPredicate;
3183
3184    /**
3185     * Cache the paddingRight set by the user to append to the scrollbar's size.
3186     *
3187     * @hide
3188     */
3189    @ViewDebug.ExportedProperty(category = "padding")
3190    protected int mUserPaddingRight;
3191
3192    /**
3193     * Cache the paddingBottom set by the user to append to the scrollbar's size.
3194     *
3195     * @hide
3196     */
3197    @ViewDebug.ExportedProperty(category = "padding")
3198    protected int mUserPaddingBottom;
3199
3200    /**
3201     * Cache the paddingLeft set by the user to append to the scrollbar's size.
3202     *
3203     * @hide
3204     */
3205    @ViewDebug.ExportedProperty(category = "padding")
3206    protected int mUserPaddingLeft;
3207
3208    /**
3209     * Cache the paddingStart set by the user to append to the scrollbar's size.
3210     *
3211     */
3212    @ViewDebug.ExportedProperty(category = "padding")
3213    int mUserPaddingStart;
3214
3215    /**
3216     * Cache the paddingEnd set by the user to append to the scrollbar's size.
3217     *
3218     */
3219    @ViewDebug.ExportedProperty(category = "padding")
3220    int mUserPaddingEnd;
3221
3222    /**
3223     * Cache initial left padding.
3224     *
3225     * @hide
3226     */
3227    int mUserPaddingLeftInitial;
3228
3229    /**
3230     * Cache initial right padding.
3231     *
3232     * @hide
3233     */
3234    int mUserPaddingRightInitial;
3235
3236    /**
3237     * Default undefined padding
3238     */
3239    private static final int UNDEFINED_PADDING = Integer.MIN_VALUE;
3240
3241    /**
3242     * Cache if a left padding has been defined
3243     */
3244    private boolean mLeftPaddingDefined = false;
3245
3246    /**
3247     * Cache if a right padding has been defined
3248     */
3249    private boolean mRightPaddingDefined = false;
3250
3251    /**
3252     * @hide
3253     */
3254    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
3255    /**
3256     * @hide
3257     */
3258    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
3259
3260    private LongSparseLongArray mMeasureCache;
3261
3262    @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_")
3263    private Drawable mBackground;
3264
3265    /**
3266     * Display list used for backgrounds.
3267     * <p>
3268     * When non-null and valid, this is expected to contain an up-to-date copy
3269     * of the background drawable. It is cleared on temporary detach and reset
3270     * on cleanup.
3271     */
3272    private DisplayList mBackgroundDisplayList;
3273
3274    private int mBackgroundResource;
3275    private boolean mBackgroundSizeChanged;
3276
3277    static class ListenerInfo {
3278        /**
3279         * Listener used to dispatch focus change events.
3280         * This field should be made private, so it is hidden from the SDK.
3281         * {@hide}
3282         */
3283        protected OnFocusChangeListener mOnFocusChangeListener;
3284
3285        /**
3286         * Listeners for layout change events.
3287         */
3288        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
3289
3290        /**
3291         * Listeners for attach events.
3292         */
3293        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
3294
3295        /**
3296         * Listener used to dispatch click events.
3297         * This field should be made private, so it is hidden from the SDK.
3298         * {@hide}
3299         */
3300        public OnClickListener mOnClickListener;
3301
3302        /**
3303         * Listener used to dispatch long click events.
3304         * This field should be made private, so it is hidden from the SDK.
3305         * {@hide}
3306         */
3307        protected OnLongClickListener mOnLongClickListener;
3308
3309        /**
3310         * Listener used to build the context menu.
3311         * This field should be made private, so it is hidden from the SDK.
3312         * {@hide}
3313         */
3314        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
3315
3316        private OnKeyListener mOnKeyListener;
3317
3318        private OnTouchListener mOnTouchListener;
3319
3320        private OnHoverListener mOnHoverListener;
3321
3322        private OnGenericMotionListener mOnGenericMotionListener;
3323
3324        private OnDragListener mOnDragListener;
3325
3326        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
3327
3328        OnApplyWindowInsetsListener mOnApplyWindowInsetsListener;
3329    }
3330
3331    ListenerInfo mListenerInfo;
3332
3333    /**
3334     * The application environment this view lives in.
3335     * This field should be made private, so it is hidden from the SDK.
3336     * {@hide}
3337     */
3338    protected Context mContext;
3339
3340    private final Resources mResources;
3341
3342    private ScrollabilityCache mScrollCache;
3343
3344    private int[] mDrawableState = null;
3345
3346    /**
3347     * Stores the outline of the view, passed down to the DisplayList level for
3348     * defining shadow shape and clipping.
3349     */
3350    private Path mOutline;
3351
3352    /**
3353     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
3354     * the user may specify which view to go to next.
3355     */
3356    private int mNextFocusLeftId = View.NO_ID;
3357
3358    /**
3359     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
3360     * the user may specify which view to go to next.
3361     */
3362    private int mNextFocusRightId = View.NO_ID;
3363
3364    /**
3365     * When this view has focus and the next focus is {@link #FOCUS_UP},
3366     * the user may specify which view to go to next.
3367     */
3368    private int mNextFocusUpId = View.NO_ID;
3369
3370    /**
3371     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
3372     * the user may specify which view to go to next.
3373     */
3374    private int mNextFocusDownId = View.NO_ID;
3375
3376    /**
3377     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
3378     * the user may specify which view to go to next.
3379     */
3380    int mNextFocusForwardId = View.NO_ID;
3381
3382    private CheckForLongPress mPendingCheckForLongPress;
3383    private CheckForTap mPendingCheckForTap = null;
3384    private PerformClick mPerformClick;
3385    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
3386
3387    private UnsetPressedState mUnsetPressedState;
3388
3389    /**
3390     * Whether the long press's action has been invoked.  The tap's action is invoked on the
3391     * up event while a long press is invoked as soon as the long press duration is reached, so
3392     * a long press could be performed before the tap is checked, in which case the tap's action
3393     * should not be invoked.
3394     */
3395    private boolean mHasPerformedLongPress;
3396
3397    /**
3398     * The minimum height of the view. We'll try our best to have the height
3399     * of this view to at least this amount.
3400     */
3401    @ViewDebug.ExportedProperty(category = "measurement")
3402    private int mMinHeight;
3403
3404    /**
3405     * The minimum width of the view. We'll try our best to have the width
3406     * of this view to at least this amount.
3407     */
3408    @ViewDebug.ExportedProperty(category = "measurement")
3409    private int mMinWidth;
3410
3411    /**
3412     * The delegate to handle touch events that are physically in this view
3413     * but should be handled by another view.
3414     */
3415    private TouchDelegate mTouchDelegate = null;
3416
3417    /**
3418     * Solid color to use as a background when creating the drawing cache. Enables
3419     * the cache to use 16 bit bitmaps instead of 32 bit.
3420     */
3421    private int mDrawingCacheBackgroundColor = 0;
3422
3423    /**
3424     * Special tree observer used when mAttachInfo is null.
3425     */
3426    private ViewTreeObserver mFloatingTreeObserver;
3427
3428    /**
3429     * Cache the touch slop from the context that created the view.
3430     */
3431    private int mTouchSlop;
3432
3433    /**
3434     * Object that handles automatic animation of view properties.
3435     */
3436    private ViewPropertyAnimator mAnimator = null;
3437
3438    /**
3439     * Flag indicating that a drag can cross window boundaries.  When
3440     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
3441     * with this flag set, all visible applications will be able to participate
3442     * in the drag operation and receive the dragged content.
3443     *
3444     * @hide
3445     */
3446    public static final int DRAG_FLAG_GLOBAL = 1;
3447
3448    /**
3449     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
3450     */
3451    private float mVerticalScrollFactor;
3452
3453    /**
3454     * Position of the vertical scroll bar.
3455     */
3456    private int mVerticalScrollbarPosition;
3457
3458    /**
3459     * Position the scroll bar at the default position as determined by the system.
3460     */
3461    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
3462
3463    /**
3464     * Position the scroll bar along the left edge.
3465     */
3466    public static final int SCROLLBAR_POSITION_LEFT = 1;
3467
3468    /**
3469     * Position the scroll bar along the right edge.
3470     */
3471    public static final int SCROLLBAR_POSITION_RIGHT = 2;
3472
3473    /**
3474     * Indicates that the view does not have a layer.
3475     *
3476     * @see #getLayerType()
3477     * @see #setLayerType(int, android.graphics.Paint)
3478     * @see #LAYER_TYPE_SOFTWARE
3479     * @see #LAYER_TYPE_HARDWARE
3480     */
3481    public static final int LAYER_TYPE_NONE = 0;
3482
3483    /**
3484     * <p>Indicates that the view has a software layer. A software layer is backed
3485     * by a bitmap and causes the view to be rendered using Android's software
3486     * rendering pipeline, even if hardware acceleration is enabled.</p>
3487     *
3488     * <p>Software layers have various usages:</p>
3489     * <p>When the application is not using hardware acceleration, a software layer
3490     * is useful to apply a specific color filter and/or blending mode and/or
3491     * translucency to a view and all its children.</p>
3492     * <p>When the application is using hardware acceleration, a software layer
3493     * is useful to render drawing primitives not supported by the hardware
3494     * accelerated pipeline. It can also be used to cache a complex view tree
3495     * into a texture and reduce the complexity of drawing operations. For instance,
3496     * when animating a complex view tree with a translation, a software layer can
3497     * be used to render the view tree only once.</p>
3498     * <p>Software layers should be avoided when the affected view tree updates
3499     * often. Every update will require to re-render the software layer, which can
3500     * potentially be slow (particularly when hardware acceleration is turned on
3501     * since the layer will have to be uploaded into a hardware texture after every
3502     * update.)</p>
3503     *
3504     * @see #getLayerType()
3505     * @see #setLayerType(int, android.graphics.Paint)
3506     * @see #LAYER_TYPE_NONE
3507     * @see #LAYER_TYPE_HARDWARE
3508     */
3509    public static final int LAYER_TYPE_SOFTWARE = 1;
3510
3511    /**
3512     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3513     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3514     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3515     * rendering pipeline, but only if hardware acceleration is turned on for the
3516     * view hierarchy. When hardware acceleration is turned off, hardware layers
3517     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3518     *
3519     * <p>A hardware layer is useful to apply a specific color filter and/or
3520     * blending mode and/or translucency to a view and all its children.</p>
3521     * <p>A hardware layer can be used to cache a complex view tree into a
3522     * texture and reduce the complexity of drawing operations. For instance,
3523     * when animating a complex view tree with a translation, a hardware layer can
3524     * be used to render the view tree only once.</p>
3525     * <p>A hardware layer can also be used to increase the rendering quality when
3526     * rotation transformations are applied on a view. It can also be used to
3527     * prevent potential clipping issues when applying 3D transforms on a view.</p>
3528     *
3529     * @see #getLayerType()
3530     * @see #setLayerType(int, android.graphics.Paint)
3531     * @see #LAYER_TYPE_NONE
3532     * @see #LAYER_TYPE_SOFTWARE
3533     */
3534    public static final int LAYER_TYPE_HARDWARE = 2;
3535
3536    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3537            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
3538            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
3539            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
3540    })
3541    int mLayerType = LAYER_TYPE_NONE;
3542    Paint mLayerPaint;
3543    Rect mLocalDirtyRect;
3544    private HardwareLayer mHardwareLayer;
3545
3546    /**
3547     * Set to true when drawing cache is enabled and cannot be created.
3548     *
3549     * @hide
3550     */
3551    public boolean mCachingFailed;
3552    private Bitmap mDrawingCache;
3553    private Bitmap mUnscaledDrawingCache;
3554
3555    /**
3556     * Display list used for the View content.
3557     * <p>
3558     * When non-null and valid, this is expected to contain an up-to-date copy
3559     * of the View content. It is cleared on temporary detach and reset on
3560     * cleanup.
3561     */
3562    DisplayList mDisplayList;
3563
3564    /**
3565     * Set to true when the view is sending hover accessibility events because it
3566     * is the innermost hovered view.
3567     */
3568    private boolean mSendingHoverAccessibilityEvents;
3569
3570    /**
3571     * Delegate for injecting accessibility functionality.
3572     */
3573    AccessibilityDelegate mAccessibilityDelegate;
3574
3575    /**
3576     * The view's overlay layer. Developers get a reference to the overlay via getOverlay()
3577     * and add/remove objects to/from the overlay directly through the Overlay methods.
3578     */
3579    ViewOverlay mOverlay;
3580
3581    /**
3582     * Consistency verifier for debugging purposes.
3583     * @hide
3584     */
3585    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
3586            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
3587                    new InputEventConsistencyVerifier(this, 0) : null;
3588
3589    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
3590
3591    /**
3592     * Simple constructor to use when creating a view from code.
3593     *
3594     * @param context The Context the view is running in, through which it can
3595     *        access the current theme, resources, etc.
3596     */
3597    public View(Context context) {
3598        mContext = context;
3599        mResources = context != null ? context.getResources() : null;
3600        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
3601        // Set some flags defaults
3602        mPrivateFlags2 =
3603                (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) |
3604                (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) |
3605                (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) |
3606                (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) |
3607                (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) |
3608                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
3609        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
3610        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
3611        mUserPaddingStart = UNDEFINED_PADDING;
3612        mUserPaddingEnd = UNDEFINED_PADDING;
3613
3614        if (!sCompatibilityDone && context != null) {
3615            final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3616
3617            // Older apps may need this compatibility hack for measurement.
3618            sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1;
3619
3620            // Older apps expect onMeasure() to always be called on a layout pass, regardless
3621            // of whether a layout was requested on that View.
3622            sIgnoreMeasureCache = targetSdkVersion < KITKAT;
3623
3624            sCompatibilityDone = true;
3625        }
3626    }
3627
3628    /**
3629     * Constructor that is called when inflating a view from XML. This is called
3630     * when a view is being constructed from an XML file, supplying attributes
3631     * that were specified in the XML file. This version uses a default style of
3632     * 0, so the only attribute values applied are those in the Context's Theme
3633     * and the given AttributeSet.
3634     *
3635     * <p>
3636     * The method onFinishInflate() will be called after all children have been
3637     * added.
3638     *
3639     * @param context The Context the view is running in, through which it can
3640     *        access the current theme, resources, etc.
3641     * @param attrs The attributes of the XML tag that is inflating the view.
3642     * @see #View(Context, AttributeSet, int)
3643     */
3644    public View(Context context, AttributeSet attrs) {
3645        this(context, attrs, 0);
3646    }
3647
3648    /**
3649     * Perform inflation from XML and apply a class-specific base style from a
3650     * theme attribute. This constructor of View allows subclasses to use their
3651     * own base style when they are inflating. For example, a Button class's
3652     * constructor would call this version of the super class constructor and
3653     * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this
3654     * allows the theme's button style to modify all of the base view attributes
3655     * (in particular its background) as well as the Button class's attributes.
3656     *
3657     * @param context The Context the view is running in, through which it can
3658     *        access the current theme, resources, etc.
3659     * @param attrs The attributes of the XML tag that is inflating the view.
3660     * @param defStyleAttr An attribute in the current theme that contains a
3661     *        reference to a style resource that supplies default values for
3662     *        the view. Can be 0 to not look for defaults.
3663     * @see #View(Context, AttributeSet)
3664     */
3665    public View(Context context, AttributeSet attrs, int defStyleAttr) {
3666        this(context, attrs, defStyleAttr, 0);
3667    }
3668
3669    /**
3670     * Perform inflation from XML and apply a class-specific base style from a
3671     * theme attribute or style resource. This constructor of View allows
3672     * subclasses to use their own base style when they are inflating.
3673     * <p>
3674     * When determining the final value of a particular attribute, there are
3675     * four inputs that come into play:
3676     * <ol>
3677     * <li>Any attribute values in the given AttributeSet.
3678     * <li>The style resource specified in the AttributeSet (named "style").
3679     * <li>The default style specified by <var>defStyleAttr</var>.
3680     * <li>The default style specified by <var>defStyleRes</var>.
3681     * <li>The base values in this theme.
3682     * </ol>
3683     * <p>
3684     * Each of these inputs is considered in-order, with the first listed taking
3685     * precedence over the following ones. In other words, if in the
3686     * AttributeSet you have supplied <code>&lt;Button * textColor="#ff000000"&gt;</code>
3687     * , then the button's text will <em>always</em> be black, regardless of
3688     * what is specified in any of the styles.
3689     *
3690     * @param context The Context the view is running in, through which it can
3691     *        access the current theme, resources, etc.
3692     * @param attrs The attributes of the XML tag that is inflating the view.
3693     * @param defStyleAttr An attribute in the current theme that contains a
3694     *        reference to a style resource that supplies default values for
3695     *        the view. Can be 0 to not look for defaults.
3696     * @param defStyleRes A resource identifier of a style resource that
3697     *        supplies default values for the view, used only if
3698     *        defStyleAttr is 0 or can not be found in the theme. Can be 0
3699     *        to not look for defaults.
3700     * @see #View(Context, AttributeSet, int)
3701     */
3702    public View(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
3703        this(context);
3704
3705        final TypedArray a = context.obtainStyledAttributes(
3706                attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes);
3707
3708        Drawable background = null;
3709
3710        int leftPadding = -1;
3711        int topPadding = -1;
3712        int rightPadding = -1;
3713        int bottomPadding = -1;
3714        int startPadding = UNDEFINED_PADDING;
3715        int endPadding = UNDEFINED_PADDING;
3716
3717        int padding = -1;
3718
3719        int viewFlagValues = 0;
3720        int viewFlagMasks = 0;
3721
3722        boolean setScrollContainer = false;
3723
3724        int x = 0;
3725        int y = 0;
3726
3727        float tx = 0;
3728        float ty = 0;
3729        float tz = 0;
3730        float rotation = 0;
3731        float rotationX = 0;
3732        float rotationY = 0;
3733        float sx = 1f;
3734        float sy = 1f;
3735        boolean transformSet = false;
3736
3737        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
3738        int overScrollMode = mOverScrollMode;
3739        boolean initializeScrollbars = false;
3740
3741        boolean startPaddingDefined = false;
3742        boolean endPaddingDefined = false;
3743        boolean leftPaddingDefined = false;
3744        boolean rightPaddingDefined = false;
3745
3746        final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3747
3748        final int N = a.getIndexCount();
3749        for (int i = 0; i < N; i++) {
3750            int attr = a.getIndex(i);
3751            switch (attr) {
3752                case com.android.internal.R.styleable.View_background:
3753                    background = a.getDrawable(attr);
3754                    break;
3755                case com.android.internal.R.styleable.View_padding:
3756                    padding = a.getDimensionPixelSize(attr, -1);
3757                    mUserPaddingLeftInitial = padding;
3758                    mUserPaddingRightInitial = padding;
3759                    leftPaddingDefined = true;
3760                    rightPaddingDefined = true;
3761                    break;
3762                 case com.android.internal.R.styleable.View_paddingLeft:
3763                    leftPadding = a.getDimensionPixelSize(attr, -1);
3764                    mUserPaddingLeftInitial = leftPadding;
3765                    leftPaddingDefined = true;
3766                    break;
3767                case com.android.internal.R.styleable.View_paddingTop:
3768                    topPadding = a.getDimensionPixelSize(attr, -1);
3769                    break;
3770                case com.android.internal.R.styleable.View_paddingRight:
3771                    rightPadding = a.getDimensionPixelSize(attr, -1);
3772                    mUserPaddingRightInitial = rightPadding;
3773                    rightPaddingDefined = true;
3774                    break;
3775                case com.android.internal.R.styleable.View_paddingBottom:
3776                    bottomPadding = a.getDimensionPixelSize(attr, -1);
3777                    break;
3778                case com.android.internal.R.styleable.View_paddingStart:
3779                    startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3780                    startPaddingDefined = (startPadding != UNDEFINED_PADDING);
3781                    break;
3782                case com.android.internal.R.styleable.View_paddingEnd:
3783                    endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3784                    endPaddingDefined = (endPadding != UNDEFINED_PADDING);
3785                    break;
3786                case com.android.internal.R.styleable.View_scrollX:
3787                    x = a.getDimensionPixelOffset(attr, 0);
3788                    break;
3789                case com.android.internal.R.styleable.View_scrollY:
3790                    y = a.getDimensionPixelOffset(attr, 0);
3791                    break;
3792                case com.android.internal.R.styleable.View_alpha:
3793                    setAlpha(a.getFloat(attr, 1f));
3794                    break;
3795                case com.android.internal.R.styleable.View_transformPivotX:
3796                    setPivotX(a.getDimensionPixelOffset(attr, 0));
3797                    break;
3798                case com.android.internal.R.styleable.View_transformPivotY:
3799                    setPivotY(a.getDimensionPixelOffset(attr, 0));
3800                    break;
3801                case com.android.internal.R.styleable.View_translationX:
3802                    tx = a.getDimensionPixelOffset(attr, 0);
3803                    transformSet = true;
3804                    break;
3805                case com.android.internal.R.styleable.View_translationY:
3806                    ty = a.getDimensionPixelOffset(attr, 0);
3807                    transformSet = true;
3808                    break;
3809                case com.android.internal.R.styleable.View_translationZ:
3810                    tz = a.getDimensionPixelOffset(attr, 0);
3811                    transformSet = true;
3812                    break;
3813                case com.android.internal.R.styleable.View_rotation:
3814                    rotation = a.getFloat(attr, 0);
3815                    transformSet = true;
3816                    break;
3817                case com.android.internal.R.styleable.View_rotationX:
3818                    rotationX = a.getFloat(attr, 0);
3819                    transformSet = true;
3820                    break;
3821                case com.android.internal.R.styleable.View_rotationY:
3822                    rotationY = a.getFloat(attr, 0);
3823                    transformSet = true;
3824                    break;
3825                case com.android.internal.R.styleable.View_scaleX:
3826                    sx = a.getFloat(attr, 1f);
3827                    transformSet = true;
3828                    break;
3829                case com.android.internal.R.styleable.View_scaleY:
3830                    sy = a.getFloat(attr, 1f);
3831                    transformSet = true;
3832                    break;
3833                case com.android.internal.R.styleable.View_id:
3834                    mID = a.getResourceId(attr, NO_ID);
3835                    break;
3836                case com.android.internal.R.styleable.View_tag:
3837                    mTag = a.getText(attr);
3838                    break;
3839                case com.android.internal.R.styleable.View_fitsSystemWindows:
3840                    if (a.getBoolean(attr, false)) {
3841                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
3842                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
3843                    }
3844                    break;
3845                case com.android.internal.R.styleable.View_focusable:
3846                    if (a.getBoolean(attr, false)) {
3847                        viewFlagValues |= FOCUSABLE;
3848                        viewFlagMasks |= FOCUSABLE_MASK;
3849                    }
3850                    break;
3851                case com.android.internal.R.styleable.View_focusableInTouchMode:
3852                    if (a.getBoolean(attr, false)) {
3853                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
3854                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
3855                    }
3856                    break;
3857                case com.android.internal.R.styleable.View_clickable:
3858                    if (a.getBoolean(attr, false)) {
3859                        viewFlagValues |= CLICKABLE;
3860                        viewFlagMasks |= CLICKABLE;
3861                    }
3862                    break;
3863                case com.android.internal.R.styleable.View_longClickable:
3864                    if (a.getBoolean(attr, false)) {
3865                        viewFlagValues |= LONG_CLICKABLE;
3866                        viewFlagMasks |= LONG_CLICKABLE;
3867                    }
3868                    break;
3869                case com.android.internal.R.styleable.View_saveEnabled:
3870                    if (!a.getBoolean(attr, true)) {
3871                        viewFlagValues |= SAVE_DISABLED;
3872                        viewFlagMasks |= SAVE_DISABLED_MASK;
3873                    }
3874                    break;
3875                case com.android.internal.R.styleable.View_duplicateParentState:
3876                    if (a.getBoolean(attr, false)) {
3877                        viewFlagValues |= DUPLICATE_PARENT_STATE;
3878                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
3879                    }
3880                    break;
3881                case com.android.internal.R.styleable.View_visibility:
3882                    final int visibility = a.getInt(attr, 0);
3883                    if (visibility != 0) {
3884                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
3885                        viewFlagMasks |= VISIBILITY_MASK;
3886                    }
3887                    break;
3888                case com.android.internal.R.styleable.View_layoutDirection:
3889                    // Clear any layout direction flags (included resolved bits) already set
3890                    mPrivateFlags2 &=
3891                            ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK);
3892                    // Set the layout direction flags depending on the value of the attribute
3893                    final int layoutDirection = a.getInt(attr, -1);
3894                    final int value = (layoutDirection != -1) ?
3895                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
3896                    mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT);
3897                    break;
3898                case com.android.internal.R.styleable.View_drawingCacheQuality:
3899                    final int cacheQuality = a.getInt(attr, 0);
3900                    if (cacheQuality != 0) {
3901                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
3902                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
3903                    }
3904                    break;
3905                case com.android.internal.R.styleable.View_contentDescription:
3906                    setContentDescription(a.getString(attr));
3907                    break;
3908                case com.android.internal.R.styleable.View_labelFor:
3909                    setLabelFor(a.getResourceId(attr, NO_ID));
3910                    break;
3911                case com.android.internal.R.styleable.View_soundEffectsEnabled:
3912                    if (!a.getBoolean(attr, true)) {
3913                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
3914                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
3915                    }
3916                    break;
3917                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
3918                    if (!a.getBoolean(attr, true)) {
3919                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
3920                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
3921                    }
3922                    break;
3923                case R.styleable.View_scrollbars:
3924                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
3925                    if (scrollbars != SCROLLBARS_NONE) {
3926                        viewFlagValues |= scrollbars;
3927                        viewFlagMasks |= SCROLLBARS_MASK;
3928                        initializeScrollbars = true;
3929                    }
3930                    break;
3931                //noinspection deprecation
3932                case R.styleable.View_fadingEdge:
3933                    if (targetSdkVersion >= ICE_CREAM_SANDWICH) {
3934                        // Ignore the attribute starting with ICS
3935                        break;
3936                    }
3937                    // With builds < ICS, fall through and apply fading edges
3938                case R.styleable.View_requiresFadingEdge:
3939                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
3940                    if (fadingEdge != FADING_EDGE_NONE) {
3941                        viewFlagValues |= fadingEdge;
3942                        viewFlagMasks |= FADING_EDGE_MASK;
3943                        initializeFadingEdge(a);
3944                    }
3945                    break;
3946                case R.styleable.View_scrollbarStyle:
3947                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
3948                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3949                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
3950                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
3951                    }
3952                    break;
3953                case R.styleable.View_isScrollContainer:
3954                    setScrollContainer = true;
3955                    if (a.getBoolean(attr, false)) {
3956                        setScrollContainer(true);
3957                    }
3958                    break;
3959                case com.android.internal.R.styleable.View_keepScreenOn:
3960                    if (a.getBoolean(attr, false)) {
3961                        viewFlagValues |= KEEP_SCREEN_ON;
3962                        viewFlagMasks |= KEEP_SCREEN_ON;
3963                    }
3964                    break;
3965                case R.styleable.View_filterTouchesWhenObscured:
3966                    if (a.getBoolean(attr, false)) {
3967                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
3968                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
3969                    }
3970                    break;
3971                case R.styleable.View_nextFocusLeft:
3972                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
3973                    break;
3974                case R.styleable.View_nextFocusRight:
3975                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
3976                    break;
3977                case R.styleable.View_nextFocusUp:
3978                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
3979                    break;
3980                case R.styleable.View_nextFocusDown:
3981                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
3982                    break;
3983                case R.styleable.View_nextFocusForward:
3984                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
3985                    break;
3986                case R.styleable.View_minWidth:
3987                    mMinWidth = a.getDimensionPixelSize(attr, 0);
3988                    break;
3989                case R.styleable.View_minHeight:
3990                    mMinHeight = a.getDimensionPixelSize(attr, 0);
3991                    break;
3992                case R.styleable.View_onClick:
3993                    if (context.isRestricted()) {
3994                        throw new IllegalStateException("The android:onClick attribute cannot "
3995                                + "be used within a restricted context");
3996                    }
3997
3998                    final String handlerName = a.getString(attr);
3999                    if (handlerName != null) {
4000                        setOnClickListener(new OnClickListener() {
4001                            private Method mHandler;
4002
4003                            public void onClick(View v) {
4004                                if (mHandler == null) {
4005                                    try {
4006                                        mHandler = getContext().getClass().getMethod(handlerName,
4007                                                View.class);
4008                                    } catch (NoSuchMethodException e) {
4009                                        int id = getId();
4010                                        String idText = id == NO_ID ? "" : " with id '"
4011                                                + getContext().getResources().getResourceEntryName(
4012                                                    id) + "'";
4013                                        throw new IllegalStateException("Could not find a method " +
4014                                                handlerName + "(View) in the activity "
4015                                                + getContext().getClass() + " for onClick handler"
4016                                                + " on view " + View.this.getClass() + idText, e);
4017                                    }
4018                                }
4019
4020                                try {
4021                                    mHandler.invoke(getContext(), View.this);
4022                                } catch (IllegalAccessException e) {
4023                                    throw new IllegalStateException("Could not execute non "
4024                                            + "public method of the activity", e);
4025                                } catch (InvocationTargetException e) {
4026                                    throw new IllegalStateException("Could not execute "
4027                                            + "method of the activity", e);
4028                                }
4029                            }
4030                        });
4031                    }
4032                    break;
4033                case R.styleable.View_overScrollMode:
4034                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
4035                    break;
4036                case R.styleable.View_verticalScrollbarPosition:
4037                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
4038                    break;
4039                case R.styleable.View_layerType:
4040                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
4041                    break;
4042                case R.styleable.View_castsShadow:
4043                    if (a.getBoolean(attr, false)) {
4044                        mPrivateFlags3 |= PFLAG3_CASTS_SHADOW;
4045                    }
4046                    break;
4047                case R.styleable.View_textDirection:
4048                    // Clear any text direction flag already set
4049                    mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
4050                    // Set the text direction flags depending on the value of the attribute
4051                    final int textDirection = a.getInt(attr, -1);
4052                    if (textDirection != -1) {
4053                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection];
4054                    }
4055                    break;
4056                case R.styleable.View_textAlignment:
4057                    // Clear any text alignment flag already set
4058                    mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
4059                    // Set the text alignment flag depending on the value of the attribute
4060                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
4061                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment];
4062                    break;
4063                case R.styleable.View_importantForAccessibility:
4064                    setImportantForAccessibility(a.getInt(attr,
4065                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
4066                    break;
4067                case R.styleable.View_accessibilityLiveRegion:
4068                    setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT));
4069                    break;
4070                case R.styleable.View_sharedElementName:
4071                    setSharedElementName(a.getString(attr));
4072                    break;
4073            }
4074        }
4075
4076        setOverScrollMode(overScrollMode);
4077
4078        // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet
4079        // the resolved layout direction). Those cached values will be used later during padding
4080        // resolution.
4081        mUserPaddingStart = startPadding;
4082        mUserPaddingEnd = endPadding;
4083
4084        if (background != null) {
4085            setBackground(background);
4086        }
4087
4088        // setBackground above will record that padding is currently provided by the background.
4089        // If we have padding specified via xml, record that here instead and use it.
4090        mLeftPaddingDefined = leftPaddingDefined;
4091        mRightPaddingDefined = rightPaddingDefined;
4092
4093        if (padding >= 0) {
4094            leftPadding = padding;
4095            topPadding = padding;
4096            rightPadding = padding;
4097            bottomPadding = padding;
4098            mUserPaddingLeftInitial = padding;
4099            mUserPaddingRightInitial = padding;
4100        }
4101
4102        if (isRtlCompatibilityMode()) {
4103            // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case.
4104            // left / right padding are used if defined (meaning here nothing to do). If they are not
4105            // defined and start / end padding are defined (e.g. in Frameworks resources), then we use
4106            // start / end and resolve them as left / right (layout direction is not taken into account).
4107            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4108            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4109            // defined.
4110            if (!mLeftPaddingDefined && startPaddingDefined) {
4111                leftPadding = startPadding;
4112            }
4113            mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial;
4114            if (!mRightPaddingDefined && endPaddingDefined) {
4115                rightPadding = endPadding;
4116            }
4117            mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial;
4118        } else {
4119            // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right
4120            // values defined. Otherwise, left /right values are used.
4121            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4122            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4123            // defined.
4124            final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined;
4125
4126            if (mLeftPaddingDefined && !hasRelativePadding) {
4127                mUserPaddingLeftInitial = leftPadding;
4128            }
4129            if (mRightPaddingDefined && !hasRelativePadding) {
4130                mUserPaddingRightInitial = rightPadding;
4131            }
4132        }
4133
4134        internalSetPadding(
4135                mUserPaddingLeftInitial,
4136                topPadding >= 0 ? topPadding : mPaddingTop,
4137                mUserPaddingRightInitial,
4138                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
4139
4140        if (viewFlagMasks != 0) {
4141            setFlags(viewFlagValues, viewFlagMasks);
4142        }
4143
4144        if (initializeScrollbars) {
4145            initializeScrollbars(a);
4146        }
4147
4148        a.recycle();
4149
4150        // Needs to be called after mViewFlags is set
4151        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
4152            recomputePadding();
4153        }
4154
4155        if (x != 0 || y != 0) {
4156            scrollTo(x, y);
4157        }
4158
4159        if (transformSet) {
4160            setTranslationX(tx);
4161            setTranslationY(ty);
4162            setTranslationZ(tz);
4163            setRotation(rotation);
4164            setRotationX(rotationX);
4165            setRotationY(rotationY);
4166            setScaleX(sx);
4167            setScaleY(sy);
4168        }
4169
4170        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
4171            setScrollContainer(true);
4172        }
4173
4174        computeOpaqueFlags();
4175    }
4176
4177    /**
4178     * Non-public constructor for use in testing
4179     */
4180    View() {
4181        mResources = null;
4182    }
4183
4184    public String toString() {
4185        StringBuilder out = new StringBuilder(128);
4186        out.append(getClass().getName());
4187        out.append('{');
4188        out.append(Integer.toHexString(System.identityHashCode(this)));
4189        out.append(' ');
4190        switch (mViewFlags&VISIBILITY_MASK) {
4191            case VISIBLE: out.append('V'); break;
4192            case INVISIBLE: out.append('I'); break;
4193            case GONE: out.append('G'); break;
4194            default: out.append('.'); break;
4195        }
4196        out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.');
4197        out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.');
4198        out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D');
4199        out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.');
4200        out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.');
4201        out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.');
4202        out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.');
4203        out.append(' ');
4204        out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.');
4205        out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.');
4206        out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.');
4207        if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) {
4208            out.append('p');
4209        } else {
4210            out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.');
4211        }
4212        out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.');
4213        out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.');
4214        out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.');
4215        out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.');
4216        out.append(' ');
4217        out.append(mLeft);
4218        out.append(',');
4219        out.append(mTop);
4220        out.append('-');
4221        out.append(mRight);
4222        out.append(',');
4223        out.append(mBottom);
4224        final int id = getId();
4225        if (id != NO_ID) {
4226            out.append(" #");
4227            out.append(Integer.toHexString(id));
4228            final Resources r = mResources;
4229            if (id != 0 && r != null) {
4230                try {
4231                    String pkgname;
4232                    switch (id&0xff000000) {
4233                        case 0x7f000000:
4234                            pkgname="app";
4235                            break;
4236                        case 0x01000000:
4237                            pkgname="android";
4238                            break;
4239                        default:
4240                            pkgname = r.getResourcePackageName(id);
4241                            break;
4242                    }
4243                    String typename = r.getResourceTypeName(id);
4244                    String entryname = r.getResourceEntryName(id);
4245                    out.append(" ");
4246                    out.append(pkgname);
4247                    out.append(":");
4248                    out.append(typename);
4249                    out.append("/");
4250                    out.append(entryname);
4251                } catch (Resources.NotFoundException e) {
4252                }
4253            }
4254        }
4255        out.append("}");
4256        return out.toString();
4257    }
4258
4259    /**
4260     * <p>
4261     * Initializes the fading edges from a given set of styled attributes. This
4262     * method should be called by subclasses that need fading edges and when an
4263     * instance of these subclasses is created programmatically rather than
4264     * being inflated from XML. This method is automatically called when the XML
4265     * is inflated.
4266     * </p>
4267     *
4268     * @param a the styled attributes set to initialize the fading edges from
4269     */
4270    protected void initializeFadingEdge(TypedArray a) {
4271        initScrollCache();
4272
4273        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
4274                R.styleable.View_fadingEdgeLength,
4275                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
4276    }
4277
4278    /**
4279     * Returns the size of the vertical faded edges used to indicate that more
4280     * content in this view is visible.
4281     *
4282     * @return The size in pixels of the vertical faded edge or 0 if vertical
4283     *         faded edges are not enabled for this view.
4284     * @attr ref android.R.styleable#View_fadingEdgeLength
4285     */
4286    public int getVerticalFadingEdgeLength() {
4287        if (isVerticalFadingEdgeEnabled()) {
4288            ScrollabilityCache cache = mScrollCache;
4289            if (cache != null) {
4290                return cache.fadingEdgeLength;
4291            }
4292        }
4293        return 0;
4294    }
4295
4296    /**
4297     * Set the size of the faded edge used to indicate that more content in this
4298     * view is available.  Will not change whether the fading edge is enabled; use
4299     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
4300     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
4301     * for the vertical or horizontal fading edges.
4302     *
4303     * @param length The size in pixels of the faded edge used to indicate that more
4304     *        content in this view is visible.
4305     */
4306    public void setFadingEdgeLength(int length) {
4307        initScrollCache();
4308        mScrollCache.fadingEdgeLength = length;
4309    }
4310
4311    /**
4312     * Returns the size of the horizontal faded edges used to indicate that more
4313     * content in this view is visible.
4314     *
4315     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
4316     *         faded edges are not enabled for this view.
4317     * @attr ref android.R.styleable#View_fadingEdgeLength
4318     */
4319    public int getHorizontalFadingEdgeLength() {
4320        if (isHorizontalFadingEdgeEnabled()) {
4321            ScrollabilityCache cache = mScrollCache;
4322            if (cache != null) {
4323                return cache.fadingEdgeLength;
4324            }
4325        }
4326        return 0;
4327    }
4328
4329    /**
4330     * Returns the width of the vertical scrollbar.
4331     *
4332     * @return The width in pixels of the vertical scrollbar or 0 if there
4333     *         is no vertical scrollbar.
4334     */
4335    public int getVerticalScrollbarWidth() {
4336        ScrollabilityCache cache = mScrollCache;
4337        if (cache != null) {
4338            ScrollBarDrawable scrollBar = cache.scrollBar;
4339            if (scrollBar != null) {
4340                int size = scrollBar.getSize(true);
4341                if (size <= 0) {
4342                    size = cache.scrollBarSize;
4343                }
4344                return size;
4345            }
4346            return 0;
4347        }
4348        return 0;
4349    }
4350
4351    /**
4352     * Returns the height of the horizontal scrollbar.
4353     *
4354     * @return The height in pixels of the horizontal scrollbar or 0 if
4355     *         there is no horizontal scrollbar.
4356     */
4357    protected int getHorizontalScrollbarHeight() {
4358        ScrollabilityCache cache = mScrollCache;
4359        if (cache != null) {
4360            ScrollBarDrawable scrollBar = cache.scrollBar;
4361            if (scrollBar != null) {
4362                int size = scrollBar.getSize(false);
4363                if (size <= 0) {
4364                    size = cache.scrollBarSize;
4365                }
4366                return size;
4367            }
4368            return 0;
4369        }
4370        return 0;
4371    }
4372
4373    /**
4374     * <p>
4375     * Initializes the scrollbars from a given set of styled attributes. This
4376     * method should be called by subclasses that need scrollbars and when an
4377     * instance of these subclasses is created programmatically rather than
4378     * being inflated from XML. This method is automatically called when the XML
4379     * is inflated.
4380     * </p>
4381     *
4382     * @param a the styled attributes set to initialize the scrollbars from
4383     */
4384    protected void initializeScrollbars(TypedArray a) {
4385        initScrollCache();
4386
4387        final ScrollabilityCache scrollabilityCache = mScrollCache;
4388
4389        if (scrollabilityCache.scrollBar == null) {
4390            scrollabilityCache.scrollBar = new ScrollBarDrawable();
4391        }
4392
4393        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
4394
4395        if (!fadeScrollbars) {
4396            scrollabilityCache.state = ScrollabilityCache.ON;
4397        }
4398        scrollabilityCache.fadeScrollBars = fadeScrollbars;
4399
4400
4401        scrollabilityCache.scrollBarFadeDuration = a.getInt(
4402                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
4403                        .getScrollBarFadeDuration());
4404        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
4405                R.styleable.View_scrollbarDefaultDelayBeforeFade,
4406                ViewConfiguration.getScrollDefaultDelay());
4407
4408
4409        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
4410                com.android.internal.R.styleable.View_scrollbarSize,
4411                ViewConfiguration.get(mContext).getScaledScrollBarSize());
4412
4413        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
4414        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
4415
4416        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
4417        if (thumb != null) {
4418            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
4419        }
4420
4421        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
4422                false);
4423        if (alwaysDraw) {
4424            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
4425        }
4426
4427        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
4428        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
4429
4430        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
4431        if (thumb != null) {
4432            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
4433        }
4434
4435        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
4436                false);
4437        if (alwaysDraw) {
4438            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
4439        }
4440
4441        // Apply layout direction to the new Drawables if needed
4442        final int layoutDirection = getLayoutDirection();
4443        if (track != null) {
4444            track.setLayoutDirection(layoutDirection);
4445        }
4446        if (thumb != null) {
4447            thumb.setLayoutDirection(layoutDirection);
4448        }
4449
4450        // Re-apply user/background padding so that scrollbar(s) get added
4451        resolvePadding();
4452    }
4453
4454    /**
4455     * <p>
4456     * Initalizes the scrollability cache if necessary.
4457     * </p>
4458     */
4459    private void initScrollCache() {
4460        if (mScrollCache == null) {
4461            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
4462        }
4463    }
4464
4465    private ScrollabilityCache getScrollCache() {
4466        initScrollCache();
4467        return mScrollCache;
4468    }
4469
4470    /**
4471     * Set the position of the vertical scroll bar. Should be one of
4472     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
4473     * {@link #SCROLLBAR_POSITION_RIGHT}.
4474     *
4475     * @param position Where the vertical scroll bar should be positioned.
4476     */
4477    public void setVerticalScrollbarPosition(int position) {
4478        if (mVerticalScrollbarPosition != position) {
4479            mVerticalScrollbarPosition = position;
4480            computeOpaqueFlags();
4481            resolvePadding();
4482        }
4483    }
4484
4485    /**
4486     * @return The position where the vertical scroll bar will show, if applicable.
4487     * @see #setVerticalScrollbarPosition(int)
4488     */
4489    public int getVerticalScrollbarPosition() {
4490        return mVerticalScrollbarPosition;
4491    }
4492
4493    ListenerInfo getListenerInfo() {
4494        if (mListenerInfo != null) {
4495            return mListenerInfo;
4496        }
4497        mListenerInfo = new ListenerInfo();
4498        return mListenerInfo;
4499    }
4500
4501    /**
4502     * Register a callback to be invoked when focus of this view changed.
4503     *
4504     * @param l The callback that will run.
4505     */
4506    public void setOnFocusChangeListener(OnFocusChangeListener l) {
4507        getListenerInfo().mOnFocusChangeListener = l;
4508    }
4509
4510    /**
4511     * Add a listener that will be called when the bounds of the view change due to
4512     * layout processing.
4513     *
4514     * @param listener The listener that will be called when layout bounds change.
4515     */
4516    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
4517        ListenerInfo li = getListenerInfo();
4518        if (li.mOnLayoutChangeListeners == null) {
4519            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
4520        }
4521        if (!li.mOnLayoutChangeListeners.contains(listener)) {
4522            li.mOnLayoutChangeListeners.add(listener);
4523        }
4524    }
4525
4526    /**
4527     * Remove a listener for layout changes.
4528     *
4529     * @param listener The listener for layout bounds change.
4530     */
4531    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
4532        ListenerInfo li = mListenerInfo;
4533        if (li == null || li.mOnLayoutChangeListeners == null) {
4534            return;
4535        }
4536        li.mOnLayoutChangeListeners.remove(listener);
4537    }
4538
4539    /**
4540     * Add a listener for attach state changes.
4541     *
4542     * This listener will be called whenever this view is attached or detached
4543     * from a window. Remove the listener using
4544     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
4545     *
4546     * @param listener Listener to attach
4547     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
4548     */
4549    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4550        ListenerInfo li = getListenerInfo();
4551        if (li.mOnAttachStateChangeListeners == null) {
4552            li.mOnAttachStateChangeListeners
4553                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
4554        }
4555        li.mOnAttachStateChangeListeners.add(listener);
4556    }
4557
4558    /**
4559     * Remove a listener for attach state changes. The listener will receive no further
4560     * notification of window attach/detach events.
4561     *
4562     * @param listener Listener to remove
4563     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
4564     */
4565    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4566        ListenerInfo li = mListenerInfo;
4567        if (li == null || li.mOnAttachStateChangeListeners == null) {
4568            return;
4569        }
4570        li.mOnAttachStateChangeListeners.remove(listener);
4571    }
4572
4573    /**
4574     * Returns the focus-change callback registered for this view.
4575     *
4576     * @return The callback, or null if one is not registered.
4577     */
4578    public OnFocusChangeListener getOnFocusChangeListener() {
4579        ListenerInfo li = mListenerInfo;
4580        return li != null ? li.mOnFocusChangeListener : null;
4581    }
4582
4583    /**
4584     * Register a callback to be invoked when this view is clicked. If this view is not
4585     * clickable, it becomes clickable.
4586     *
4587     * @param l The callback that will run
4588     *
4589     * @see #setClickable(boolean)
4590     */
4591    public void setOnClickListener(OnClickListener l) {
4592        if (!isClickable()) {
4593            setClickable(true);
4594        }
4595        getListenerInfo().mOnClickListener = l;
4596    }
4597
4598    /**
4599     * Return whether this view has an attached OnClickListener.  Returns
4600     * true if there is a listener, false if there is none.
4601     */
4602    public boolean hasOnClickListeners() {
4603        ListenerInfo li = mListenerInfo;
4604        return (li != null && li.mOnClickListener != null);
4605    }
4606
4607    /**
4608     * Register a callback to be invoked when this view is clicked and held. If this view is not
4609     * long clickable, it becomes long clickable.
4610     *
4611     * @param l The callback that will run
4612     *
4613     * @see #setLongClickable(boolean)
4614     */
4615    public void setOnLongClickListener(OnLongClickListener l) {
4616        if (!isLongClickable()) {
4617            setLongClickable(true);
4618        }
4619        getListenerInfo().mOnLongClickListener = l;
4620    }
4621
4622    /**
4623     * Register a callback to be invoked when the context menu for this view is
4624     * being built. If this view is not long clickable, it becomes long clickable.
4625     *
4626     * @param l The callback that will run
4627     *
4628     */
4629    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
4630        if (!isLongClickable()) {
4631            setLongClickable(true);
4632        }
4633        getListenerInfo().mOnCreateContextMenuListener = l;
4634    }
4635
4636    /**
4637     * Call this view's OnClickListener, if it is defined.  Performs all normal
4638     * actions associated with clicking: reporting accessibility event, playing
4639     * a sound, etc.
4640     *
4641     * @return True there was an assigned OnClickListener that was called, false
4642     *         otherwise is returned.
4643     */
4644    public boolean performClick() {
4645        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
4646
4647        ListenerInfo li = mListenerInfo;
4648        if (li != null && li.mOnClickListener != null) {
4649            playSoundEffect(SoundEffectConstants.CLICK);
4650            li.mOnClickListener.onClick(this);
4651            return true;
4652        }
4653
4654        return false;
4655    }
4656
4657    /**
4658     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
4659     * this only calls the listener, and does not do any associated clicking
4660     * actions like reporting an accessibility event.
4661     *
4662     * @return True there was an assigned OnClickListener that was called, false
4663     *         otherwise is returned.
4664     */
4665    public boolean callOnClick() {
4666        ListenerInfo li = mListenerInfo;
4667        if (li != null && li.mOnClickListener != null) {
4668            li.mOnClickListener.onClick(this);
4669            return true;
4670        }
4671        return false;
4672    }
4673
4674    /**
4675     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
4676     * OnLongClickListener did not consume the event.
4677     *
4678     * @return True if one of the above receivers consumed the event, false otherwise.
4679     */
4680    public boolean performLongClick() {
4681        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
4682
4683        boolean handled = false;
4684        ListenerInfo li = mListenerInfo;
4685        if (li != null && li.mOnLongClickListener != null) {
4686            handled = li.mOnLongClickListener.onLongClick(View.this);
4687        }
4688        if (!handled) {
4689            handled = showContextMenu();
4690        }
4691        if (handled) {
4692            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
4693        }
4694        return handled;
4695    }
4696
4697    /**
4698     * Performs button-related actions during a touch down event.
4699     *
4700     * @param event The event.
4701     * @return True if the down was consumed.
4702     *
4703     * @hide
4704     */
4705    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
4706        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
4707            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
4708                return true;
4709            }
4710        }
4711        return false;
4712    }
4713
4714    /**
4715     * Bring up the context menu for this view.
4716     *
4717     * @return Whether a context menu was displayed.
4718     */
4719    public boolean showContextMenu() {
4720        return getParent().showContextMenuForChild(this);
4721    }
4722
4723    /**
4724     * Bring up the context menu for this view, referring to the item under the specified point.
4725     *
4726     * @param x The referenced x coordinate.
4727     * @param y The referenced y coordinate.
4728     * @param metaState The keyboard modifiers that were pressed.
4729     * @return Whether a context menu was displayed.
4730     *
4731     * @hide
4732     */
4733    public boolean showContextMenu(float x, float y, int metaState) {
4734        return showContextMenu();
4735    }
4736
4737    /**
4738     * Start an action mode.
4739     *
4740     * @param callback Callback that will control the lifecycle of the action mode
4741     * @return The new action mode if it is started, null otherwise
4742     *
4743     * @see ActionMode
4744     */
4745    public ActionMode startActionMode(ActionMode.Callback callback) {
4746        ViewParent parent = getParent();
4747        if (parent == null) return null;
4748        return parent.startActionModeForChild(this, callback);
4749    }
4750
4751    /**
4752     * Register a callback to be invoked when a hardware key is pressed in this view.
4753     * Key presses in software input methods will generally not trigger the methods of
4754     * this listener.
4755     * @param l the key listener to attach to this view
4756     */
4757    public void setOnKeyListener(OnKeyListener l) {
4758        getListenerInfo().mOnKeyListener = l;
4759    }
4760
4761    /**
4762     * Register a callback to be invoked when a touch event is sent to this view.
4763     * @param l the touch listener to attach to this view
4764     */
4765    public void setOnTouchListener(OnTouchListener l) {
4766        getListenerInfo().mOnTouchListener = l;
4767    }
4768
4769    /**
4770     * Register a callback to be invoked when a generic motion event is sent to this view.
4771     * @param l the generic motion listener to attach to this view
4772     */
4773    public void setOnGenericMotionListener(OnGenericMotionListener l) {
4774        getListenerInfo().mOnGenericMotionListener = l;
4775    }
4776
4777    /**
4778     * Register a callback to be invoked when a hover event is sent to this view.
4779     * @param l the hover listener to attach to this view
4780     */
4781    public void setOnHoverListener(OnHoverListener l) {
4782        getListenerInfo().mOnHoverListener = l;
4783    }
4784
4785    /**
4786     * Register a drag event listener callback object for this View. The parameter is
4787     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
4788     * View, the system calls the
4789     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
4790     * @param l An implementation of {@link android.view.View.OnDragListener}.
4791     */
4792    public void setOnDragListener(OnDragListener l) {
4793        getListenerInfo().mOnDragListener = l;
4794    }
4795
4796    /**
4797     * Give this view focus. This will cause
4798     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
4799     *
4800     * Note: this does not check whether this {@link View} should get focus, it just
4801     * gives it focus no matter what.  It should only be called internally by framework
4802     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
4803     *
4804     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
4805     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
4806     *        focus moved when requestFocus() is called. It may not always
4807     *        apply, in which case use the default View.FOCUS_DOWN.
4808     * @param previouslyFocusedRect The rectangle of the view that had focus
4809     *        prior in this View's coordinate system.
4810     */
4811    void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) {
4812        if (DBG) {
4813            System.out.println(this + " requestFocus()");
4814        }
4815
4816        if ((mPrivateFlags & PFLAG_FOCUSED) == 0) {
4817            mPrivateFlags |= PFLAG_FOCUSED;
4818
4819            View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null;
4820
4821            if (mParent != null) {
4822                mParent.requestChildFocus(this, this);
4823            }
4824
4825            if (mAttachInfo != null) {
4826                mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this);
4827            }
4828
4829            manageFocusHotspot(true, oldFocus);
4830            onFocusChanged(true, direction, previouslyFocusedRect);
4831            refreshDrawableState();
4832        }
4833    }
4834
4835    /**
4836     * Forwards focus information to the background drawable, if necessary. When
4837     * the view is gaining focus, <code>v</code> is the previous focus holder.
4838     * When the view is losing focus, <code>v</code> is the next focus holder.
4839     *
4840     * @param focused whether this view is focused
4841     * @param v previous or the next focus holder, or null if none
4842     */
4843    private void manageFocusHotspot(boolean focused, View v) {
4844        if (mBackground != null && mBackground.supportsHotspots()) {
4845            final Rect r = new Rect();
4846            if (v != null) {
4847                v.getBoundsOnScreen(r);
4848                final int[] location = new int[2];
4849                getLocationOnScreen(location);
4850                r.offset(-location[0], -location[1]);
4851            } else {
4852                r.set(mLeft, mTop, mRight, mBottom);
4853            }
4854
4855            final float x = r.exactCenterX();
4856            final float y = r.exactCenterY();
4857            mBackground.setHotspot(Drawable.HOTSPOT_FOCUS, x, y);
4858
4859            if (!focused) {
4860                mBackground.removeHotspot(Drawable.HOTSPOT_FOCUS);
4861            }
4862        }
4863    }
4864
4865    /**
4866     * Request that a rectangle of this view be visible on the screen,
4867     * scrolling if necessary just enough.
4868     *
4869     * <p>A View should call this if it maintains some notion of which part
4870     * of its content is interesting.  For example, a text editing view
4871     * should call this when its cursor moves.
4872     *
4873     * @param rectangle The rectangle.
4874     * @return Whether any parent scrolled.
4875     */
4876    public boolean requestRectangleOnScreen(Rect rectangle) {
4877        return requestRectangleOnScreen(rectangle, false);
4878    }
4879
4880    /**
4881     * Request that a rectangle of this view be visible on the screen,
4882     * scrolling if necessary just enough.
4883     *
4884     * <p>A View should call this if it maintains some notion of which part
4885     * of its content is interesting.  For example, a text editing view
4886     * should call this when its cursor moves.
4887     *
4888     * <p>When <code>immediate</code> is set to true, scrolling will not be
4889     * animated.
4890     *
4891     * @param rectangle The rectangle.
4892     * @param immediate True to forbid animated scrolling, false otherwise
4893     * @return Whether any parent scrolled.
4894     */
4895    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
4896        if (mParent == null) {
4897            return false;
4898        }
4899
4900        View child = this;
4901
4902        RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF();
4903        position.set(rectangle);
4904
4905        ViewParent parent = mParent;
4906        boolean scrolled = false;
4907        while (parent != null) {
4908            rectangle.set((int) position.left, (int) position.top,
4909                    (int) position.right, (int) position.bottom);
4910
4911            scrolled |= parent.requestChildRectangleOnScreen(child,
4912                    rectangle, immediate);
4913
4914            if (!child.hasIdentityMatrix()) {
4915                child.getMatrix().mapRect(position);
4916            }
4917
4918            position.offset(child.mLeft, child.mTop);
4919
4920            if (!(parent instanceof View)) {
4921                break;
4922            }
4923
4924            View parentView = (View) parent;
4925
4926            position.offset(-parentView.getScrollX(), -parentView.getScrollY());
4927
4928            child = parentView;
4929            parent = child.getParent();
4930        }
4931
4932        return scrolled;
4933    }
4934
4935    /**
4936     * Called when this view wants to give up focus. If focus is cleared
4937     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
4938     * <p>
4939     * <strong>Note:</strong> When a View clears focus the framework is trying
4940     * to give focus to the first focusable View from the top. Hence, if this
4941     * View is the first from the top that can take focus, then all callbacks
4942     * related to clearing focus will be invoked after wich the framework will
4943     * give focus to this view.
4944     * </p>
4945     */
4946    public void clearFocus() {
4947        if (DBG) {
4948            System.out.println(this + " clearFocus()");
4949        }
4950
4951        clearFocusInternal(null, true, true);
4952    }
4953
4954    /**
4955     * Clears focus from the view, optionally propagating the change up through
4956     * the parent hierarchy and requesting that the root view place new focus.
4957     *
4958     * @param propagate whether to propagate the change up through the parent
4959     *            hierarchy
4960     * @param refocus when propagate is true, specifies whether to request the
4961     *            root view place new focus
4962     */
4963    void clearFocusInternal(View focused, boolean propagate, boolean refocus) {
4964        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
4965            mPrivateFlags &= ~PFLAG_FOCUSED;
4966
4967            if (hasFocus()) {
4968                manageFocusHotspot(false, focused);
4969            }
4970
4971            if (propagate && mParent != null) {
4972                mParent.clearChildFocus(this);
4973            }
4974
4975            onFocusChanged(false, 0, null);
4976
4977            refreshDrawableState();
4978
4979            if (propagate && (!refocus || !rootViewRequestFocus())) {
4980                notifyGlobalFocusCleared(this);
4981            }
4982        }
4983    }
4984
4985    void notifyGlobalFocusCleared(View oldFocus) {
4986        if (oldFocus != null && mAttachInfo != null) {
4987            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
4988        }
4989    }
4990
4991    boolean rootViewRequestFocus() {
4992        final View root = getRootView();
4993        return root != null && root.requestFocus();
4994    }
4995
4996    /**
4997     * Called internally by the view system when a new view is getting focus.
4998     * This is what clears the old focus.
4999     * <p>
5000     * <b>NOTE:</b> The parent view's focused child must be updated manually
5001     * after calling this method. Otherwise, the view hierarchy may be left in
5002     * an inconstent state.
5003     */
5004    void unFocus(View focused) {
5005        if (DBG) {
5006            System.out.println(this + " unFocus()");
5007        }
5008
5009        clearFocusInternal(focused, false, false);
5010    }
5011
5012    /**
5013     * Returns true if this view has focus iteself, or is the ancestor of the
5014     * view that has focus.
5015     *
5016     * @return True if this view has or contains focus, false otherwise.
5017     */
5018    @ViewDebug.ExportedProperty(category = "focus")
5019    public boolean hasFocus() {
5020        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
5021    }
5022
5023    /**
5024     * Returns true if this view is focusable or if it contains a reachable View
5025     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
5026     * is a View whose parents do not block descendants focus.
5027     *
5028     * Only {@link #VISIBLE} views are considered focusable.
5029     *
5030     * @return True if the view is focusable or if the view contains a focusable
5031     *         View, false otherwise.
5032     *
5033     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
5034     */
5035    public boolean hasFocusable() {
5036        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
5037    }
5038
5039    /**
5040     * Called by the view system when the focus state of this view changes.
5041     * When the focus change event is caused by directional navigation, direction
5042     * and previouslyFocusedRect provide insight into where the focus is coming from.
5043     * When overriding, be sure to call up through to the super class so that
5044     * the standard focus handling will occur.
5045     *
5046     * @param gainFocus True if the View has focus; false otherwise.
5047     * @param direction The direction focus has moved when requestFocus()
5048     *                  is called to give this view focus. Values are
5049     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
5050     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
5051     *                  It may not always apply, in which case use the default.
5052     * @param previouslyFocusedRect The rectangle, in this view's coordinate
5053     *        system, of the previously focused view.  If applicable, this will be
5054     *        passed in as finer grained information about where the focus is coming
5055     *        from (in addition to direction).  Will be <code>null</code> otherwise.
5056     */
5057    protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction,
5058            @Nullable Rect previouslyFocusedRect) {
5059        if (gainFocus) {
5060            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
5061        } else {
5062            notifyViewAccessibilityStateChangedIfNeeded(
5063                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
5064        }
5065
5066        InputMethodManager imm = InputMethodManager.peekInstance();
5067        if (!gainFocus) {
5068            if (isPressed()) {
5069                setPressed(false);
5070            }
5071            if (imm != null && mAttachInfo != null
5072                    && mAttachInfo.mHasWindowFocus) {
5073                imm.focusOut(this);
5074            }
5075            onFocusLost();
5076        } else if (imm != null && mAttachInfo != null
5077                && mAttachInfo.mHasWindowFocus) {
5078            imm.focusIn(this);
5079        }
5080
5081        invalidate(true);
5082        ListenerInfo li = mListenerInfo;
5083        if (li != null && li.mOnFocusChangeListener != null) {
5084            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
5085        }
5086
5087        if (mAttachInfo != null) {
5088            mAttachInfo.mKeyDispatchState.reset(this);
5089        }
5090    }
5091
5092    /**
5093     * Sends an accessibility event of the given type. If accessibility is
5094     * not enabled this method has no effect. The default implementation calls
5095     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
5096     * to populate information about the event source (this View), then calls
5097     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
5098     * populate the text content of the event source including its descendants,
5099     * and last calls
5100     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
5101     * on its parent to resuest sending of the event to interested parties.
5102     * <p>
5103     * If an {@link AccessibilityDelegate} has been specified via calling
5104     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5105     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
5106     * responsible for handling this call.
5107     * </p>
5108     *
5109     * @param eventType The type of the event to send, as defined by several types from
5110     * {@link android.view.accessibility.AccessibilityEvent}, such as
5111     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
5112     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
5113     *
5114     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
5115     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5116     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
5117     * @see AccessibilityDelegate
5118     */
5119    public void sendAccessibilityEvent(int eventType) {
5120        // Excluded views do not send accessibility events.
5121        if (!includeForAccessibility()) {
5122            return;
5123        }
5124        if (mAccessibilityDelegate != null) {
5125            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
5126        } else {
5127            sendAccessibilityEventInternal(eventType);
5128        }
5129    }
5130
5131    /**
5132     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
5133     * {@link AccessibilityEvent} to make an announcement which is related to some
5134     * sort of a context change for which none of the events representing UI transitions
5135     * is a good fit. For example, announcing a new page in a book. If accessibility
5136     * is not enabled this method does nothing.
5137     *
5138     * @param text The announcement text.
5139     */
5140    public void announceForAccessibility(CharSequence text) {
5141        if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) {
5142            AccessibilityEvent event = AccessibilityEvent.obtain(
5143                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
5144            onInitializeAccessibilityEvent(event);
5145            event.getText().add(text);
5146            event.setContentDescription(null);
5147            mParent.requestSendAccessibilityEvent(this, event);
5148        }
5149    }
5150
5151    /**
5152     * @see #sendAccessibilityEvent(int)
5153     *
5154     * Note: Called from the default {@link AccessibilityDelegate}.
5155     */
5156    void sendAccessibilityEventInternal(int eventType) {
5157        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
5158            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
5159        }
5160    }
5161
5162    /**
5163     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
5164     * takes as an argument an empty {@link AccessibilityEvent} and does not
5165     * perform a check whether accessibility is enabled.
5166     * <p>
5167     * If an {@link AccessibilityDelegate} has been specified via calling
5168     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5169     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
5170     * is responsible for handling this call.
5171     * </p>
5172     *
5173     * @param event The event to send.
5174     *
5175     * @see #sendAccessibilityEvent(int)
5176     */
5177    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
5178        if (mAccessibilityDelegate != null) {
5179            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
5180        } else {
5181            sendAccessibilityEventUncheckedInternal(event);
5182        }
5183    }
5184
5185    /**
5186     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
5187     *
5188     * Note: Called from the default {@link AccessibilityDelegate}.
5189     */
5190    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
5191        if (!isShown()) {
5192            return;
5193        }
5194        onInitializeAccessibilityEvent(event);
5195        // Only a subset of accessibility events populates text content.
5196        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
5197            dispatchPopulateAccessibilityEvent(event);
5198        }
5199        // In the beginning we called #isShown(), so we know that getParent() is not null.
5200        getParent().requestSendAccessibilityEvent(this, event);
5201    }
5202
5203    /**
5204     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
5205     * to its children for adding their text content to the event. Note that the
5206     * event text is populated in a separate dispatch path since we add to the
5207     * event not only the text of the source but also the text of all its descendants.
5208     * A typical implementation will call
5209     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
5210     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
5211     * on each child. Override this method if custom population of the event text
5212     * content is required.
5213     * <p>
5214     * If an {@link AccessibilityDelegate} has been specified via calling
5215     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5216     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
5217     * is responsible for handling this call.
5218     * </p>
5219     * <p>
5220     * <em>Note:</em> Accessibility events of certain types are not dispatched for
5221     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
5222     * </p>
5223     *
5224     * @param event The event.
5225     *
5226     * @return True if the event population was completed.
5227     */
5228    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
5229        if (mAccessibilityDelegate != null) {
5230            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
5231        } else {
5232            return dispatchPopulateAccessibilityEventInternal(event);
5233        }
5234    }
5235
5236    /**
5237     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5238     *
5239     * Note: Called from the default {@link AccessibilityDelegate}.
5240     */
5241    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
5242        onPopulateAccessibilityEvent(event);
5243        return false;
5244    }
5245
5246    /**
5247     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
5248     * giving a chance to this View to populate the accessibility event with its
5249     * text content. While this method is free to modify event
5250     * attributes other than text content, doing so should normally be performed in
5251     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
5252     * <p>
5253     * Example: Adding formatted date string to an accessibility event in addition
5254     *          to the text added by the super implementation:
5255     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
5256     *     super.onPopulateAccessibilityEvent(event);
5257     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
5258     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
5259     *         mCurrentDate.getTimeInMillis(), flags);
5260     *     event.getText().add(selectedDateUtterance);
5261     * }</pre>
5262     * <p>
5263     * If an {@link AccessibilityDelegate} has been specified via calling
5264     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5265     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
5266     * is responsible for handling this call.
5267     * </p>
5268     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
5269     * information to the event, in case the default implementation has basic information to add.
5270     * </p>
5271     *
5272     * @param event The accessibility event which to populate.
5273     *
5274     * @see #sendAccessibilityEvent(int)
5275     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5276     */
5277    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
5278        if (mAccessibilityDelegate != null) {
5279            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
5280        } else {
5281            onPopulateAccessibilityEventInternal(event);
5282        }
5283    }
5284
5285    /**
5286     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
5287     *
5288     * Note: Called from the default {@link AccessibilityDelegate}.
5289     */
5290    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
5291    }
5292
5293    /**
5294     * Initializes an {@link AccessibilityEvent} with information about
5295     * this View which is the event source. In other words, the source of
5296     * an accessibility event is the view whose state change triggered firing
5297     * the event.
5298     * <p>
5299     * Example: Setting the password property of an event in addition
5300     *          to properties set by the super implementation:
5301     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
5302     *     super.onInitializeAccessibilityEvent(event);
5303     *     event.setPassword(true);
5304     * }</pre>
5305     * <p>
5306     * If an {@link AccessibilityDelegate} has been specified via calling
5307     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5308     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
5309     * is responsible for handling this call.
5310     * </p>
5311     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
5312     * information to the event, in case the default implementation has basic information to add.
5313     * </p>
5314     * @param event The event to initialize.
5315     *
5316     * @see #sendAccessibilityEvent(int)
5317     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5318     */
5319    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
5320        if (mAccessibilityDelegate != null) {
5321            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
5322        } else {
5323            onInitializeAccessibilityEventInternal(event);
5324        }
5325    }
5326
5327    /**
5328     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
5329     *
5330     * Note: Called from the default {@link AccessibilityDelegate}.
5331     */
5332    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
5333        event.setSource(this);
5334        event.setClassName(View.class.getName());
5335        event.setPackageName(getContext().getPackageName());
5336        event.setEnabled(isEnabled());
5337        event.setContentDescription(mContentDescription);
5338
5339        switch (event.getEventType()) {
5340            case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
5341                ArrayList<View> focusablesTempList = (mAttachInfo != null)
5342                        ? mAttachInfo.mTempArrayList : new ArrayList<View>();
5343                getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
5344                event.setItemCount(focusablesTempList.size());
5345                event.setCurrentItemIndex(focusablesTempList.indexOf(this));
5346                if (mAttachInfo != null) {
5347                    focusablesTempList.clear();
5348                }
5349            } break;
5350            case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: {
5351                CharSequence text = getIterableTextForAccessibility();
5352                if (text != null && text.length() > 0) {
5353                    event.setFromIndex(getAccessibilitySelectionStart());
5354                    event.setToIndex(getAccessibilitySelectionEnd());
5355                    event.setItemCount(text.length());
5356                }
5357            } break;
5358        }
5359    }
5360
5361    /**
5362     * Returns an {@link AccessibilityNodeInfo} representing this view from the
5363     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
5364     * This method is responsible for obtaining an accessibility node info from a
5365     * pool of reusable instances and calling
5366     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
5367     * initialize the former.
5368     * <p>
5369     * Note: The client is responsible for recycling the obtained instance by calling
5370     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
5371     * </p>
5372     *
5373     * @return A populated {@link AccessibilityNodeInfo}.
5374     *
5375     * @see AccessibilityNodeInfo
5376     */
5377    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
5378        if (mAccessibilityDelegate != null) {
5379            return mAccessibilityDelegate.createAccessibilityNodeInfo(this);
5380        } else {
5381            return createAccessibilityNodeInfoInternal();
5382        }
5383    }
5384
5385    /**
5386     * @see #createAccessibilityNodeInfo()
5387     */
5388    AccessibilityNodeInfo createAccessibilityNodeInfoInternal() {
5389        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
5390        if (provider != null) {
5391            return provider.createAccessibilityNodeInfo(View.NO_ID);
5392        } else {
5393            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
5394            onInitializeAccessibilityNodeInfo(info);
5395            return info;
5396        }
5397    }
5398
5399    /**
5400     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
5401     * The base implementation sets:
5402     * <ul>
5403     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
5404     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
5405     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
5406     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
5407     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
5408     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
5409     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
5410     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
5411     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
5412     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
5413     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
5414     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
5415     * </ul>
5416     * <p>
5417     * Subclasses should override this method, call the super implementation,
5418     * and set additional attributes.
5419     * </p>
5420     * <p>
5421     * If an {@link AccessibilityDelegate} has been specified via calling
5422     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5423     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
5424     * is responsible for handling this call.
5425     * </p>
5426     *
5427     * @param info The instance to initialize.
5428     */
5429    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
5430        if (mAccessibilityDelegate != null) {
5431            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
5432        } else {
5433            onInitializeAccessibilityNodeInfoInternal(info);
5434        }
5435    }
5436
5437    /**
5438     * Gets the location of this view in screen coordintates.
5439     *
5440     * @param outRect The output location
5441     */
5442    void getBoundsOnScreen(Rect outRect) {
5443        if (mAttachInfo == null) {
5444            return;
5445        }
5446
5447        RectF position = mAttachInfo.mTmpTransformRect;
5448        position.set(0, 0, mRight - mLeft, mBottom - mTop);
5449
5450        if (!hasIdentityMatrix()) {
5451            getMatrix().mapRect(position);
5452        }
5453
5454        position.offset(mLeft, mTop);
5455
5456        ViewParent parent = mParent;
5457        while (parent instanceof View) {
5458            View parentView = (View) parent;
5459
5460            position.offset(-parentView.mScrollX, -parentView.mScrollY);
5461
5462            if (!parentView.hasIdentityMatrix()) {
5463                parentView.getMatrix().mapRect(position);
5464            }
5465
5466            position.offset(parentView.mLeft, parentView.mTop);
5467
5468            parent = parentView.mParent;
5469        }
5470
5471        if (parent instanceof ViewRootImpl) {
5472            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
5473            position.offset(0, -viewRootImpl.mCurScrollY);
5474        }
5475
5476        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
5477
5478        outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f),
5479                (int) (position.right + 0.5f), (int) (position.bottom + 0.5f));
5480    }
5481
5482    /**
5483     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
5484     *
5485     * Note: Called from the default {@link AccessibilityDelegate}.
5486     */
5487    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
5488        Rect bounds = mAttachInfo.mTmpInvalRect;
5489
5490        getDrawingRect(bounds);
5491        info.setBoundsInParent(bounds);
5492
5493        getBoundsOnScreen(bounds);
5494        info.setBoundsInScreen(bounds);
5495
5496        ViewParent parent = getParentForAccessibility();
5497        if (parent instanceof View) {
5498            info.setParent((View) parent);
5499        }
5500
5501        if (mID != View.NO_ID) {
5502            View rootView = getRootView();
5503            if (rootView == null) {
5504                rootView = this;
5505            }
5506            View label = rootView.findLabelForView(this, mID);
5507            if (label != null) {
5508                info.setLabeledBy(label);
5509            }
5510
5511            if ((mAttachInfo.mAccessibilityFetchFlags
5512                    & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0
5513                    && Resources.resourceHasPackage(mID)) {
5514                try {
5515                    String viewId = getResources().getResourceName(mID);
5516                    info.setViewIdResourceName(viewId);
5517                } catch (Resources.NotFoundException nfe) {
5518                    /* ignore */
5519                }
5520            }
5521        }
5522
5523        if (mLabelForId != View.NO_ID) {
5524            View rootView = getRootView();
5525            if (rootView == null) {
5526                rootView = this;
5527            }
5528            View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId);
5529            if (labeled != null) {
5530                info.setLabelFor(labeled);
5531            }
5532        }
5533
5534        info.setVisibleToUser(isVisibleToUser());
5535
5536        info.setPackageName(mContext.getPackageName());
5537        info.setClassName(View.class.getName());
5538        info.setContentDescription(getContentDescription());
5539
5540        info.setEnabled(isEnabled());
5541        info.setClickable(isClickable());
5542        info.setFocusable(isFocusable());
5543        info.setFocused(isFocused());
5544        info.setAccessibilityFocused(isAccessibilityFocused());
5545        info.setSelected(isSelected());
5546        info.setLongClickable(isLongClickable());
5547        info.setLiveRegion(getAccessibilityLiveRegion());
5548
5549        // TODO: These make sense only if we are in an AdapterView but all
5550        // views can be selected. Maybe from accessibility perspective
5551        // we should report as selectable view in an AdapterView.
5552        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
5553        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
5554
5555        if (isFocusable()) {
5556            if (isFocused()) {
5557                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
5558            } else {
5559                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
5560            }
5561        }
5562
5563        if (!isAccessibilityFocused()) {
5564            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
5565        } else {
5566            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
5567        }
5568
5569        if (isClickable() && isEnabled()) {
5570            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
5571        }
5572
5573        if (isLongClickable() && isEnabled()) {
5574            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
5575        }
5576
5577        CharSequence text = getIterableTextForAccessibility();
5578        if (text != null && text.length() > 0) {
5579            info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd());
5580
5581            info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION);
5582            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
5583            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
5584            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
5585                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
5586                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
5587        }
5588    }
5589
5590    private View findLabelForView(View view, int labeledId) {
5591        if (mMatchLabelForPredicate == null) {
5592            mMatchLabelForPredicate = new MatchLabelForPredicate();
5593        }
5594        mMatchLabelForPredicate.mLabeledId = labeledId;
5595        return findViewByPredicateInsideOut(view, mMatchLabelForPredicate);
5596    }
5597
5598    /**
5599     * Computes whether this view is visible to the user. Such a view is
5600     * attached, visible, all its predecessors are visible, it is not clipped
5601     * entirely by its predecessors, and has an alpha greater than zero.
5602     *
5603     * @return Whether the view is visible on the screen.
5604     *
5605     * @hide
5606     */
5607    protected boolean isVisibleToUser() {
5608        return isVisibleToUser(null);
5609    }
5610
5611    /**
5612     * Computes whether the given portion of this view is visible to the user.
5613     * Such a view is attached, visible, all its predecessors are visible,
5614     * has an alpha greater than zero, and the specified portion is not
5615     * clipped entirely by its predecessors.
5616     *
5617     * @param boundInView the portion of the view to test; coordinates should be relative; may be
5618     *                    <code>null</code>, and the entire view will be tested in this case.
5619     *                    When <code>true</code> is returned by the function, the actual visible
5620     *                    region will be stored in this parameter; that is, if boundInView is fully
5621     *                    contained within the view, no modification will be made, otherwise regions
5622     *                    outside of the visible area of the view will be clipped.
5623     *
5624     * @return Whether the specified portion of the view is visible on the screen.
5625     *
5626     * @hide
5627     */
5628    protected boolean isVisibleToUser(Rect boundInView) {
5629        if (mAttachInfo != null) {
5630            // Attached to invisible window means this view is not visible.
5631            if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
5632                return false;
5633            }
5634            // An invisible predecessor or one with alpha zero means
5635            // that this view is not visible to the user.
5636            Object current = this;
5637            while (current instanceof View) {
5638                View view = (View) current;
5639                // We have attach info so this view is attached and there is no
5640                // need to check whether we reach to ViewRootImpl on the way up.
5641                if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 ||
5642                        view.getVisibility() != VISIBLE) {
5643                    return false;
5644                }
5645                current = view.mParent;
5646            }
5647            // Check if the view is entirely covered by its predecessors.
5648            Rect visibleRect = mAttachInfo.mTmpInvalRect;
5649            Point offset = mAttachInfo.mPoint;
5650            if (!getGlobalVisibleRect(visibleRect, offset)) {
5651                return false;
5652            }
5653            // Check if the visible portion intersects the rectangle of interest.
5654            if (boundInView != null) {
5655                visibleRect.offset(-offset.x, -offset.y);
5656                return boundInView.intersect(visibleRect);
5657            }
5658            return true;
5659        }
5660        return false;
5661    }
5662
5663    /**
5664     * Returns the delegate for implementing accessibility support via
5665     * composition. For more details see {@link AccessibilityDelegate}.
5666     *
5667     * @return The delegate, or null if none set.
5668     *
5669     * @hide
5670     */
5671    public AccessibilityDelegate getAccessibilityDelegate() {
5672        return mAccessibilityDelegate;
5673    }
5674
5675    /**
5676     * Sets a delegate for implementing accessibility support via composition as
5677     * opposed to inheritance. The delegate's primary use is for implementing
5678     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
5679     *
5680     * @param delegate The delegate instance.
5681     *
5682     * @see AccessibilityDelegate
5683     */
5684    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
5685        mAccessibilityDelegate = delegate;
5686    }
5687
5688    /**
5689     * Gets the provider for managing a virtual view hierarchy rooted at this View
5690     * and reported to {@link android.accessibilityservice.AccessibilityService}s
5691     * that explore the window content.
5692     * <p>
5693     * If this method returns an instance, this instance is responsible for managing
5694     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
5695     * View including the one representing the View itself. Similarly the returned
5696     * instance is responsible for performing accessibility actions on any virtual
5697     * view or the root view itself.
5698     * </p>
5699     * <p>
5700     * If an {@link AccessibilityDelegate} has been specified via calling
5701     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5702     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
5703     * is responsible for handling this call.
5704     * </p>
5705     *
5706     * @return The provider.
5707     *
5708     * @see AccessibilityNodeProvider
5709     */
5710    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
5711        if (mAccessibilityDelegate != null) {
5712            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
5713        } else {
5714            return null;
5715        }
5716    }
5717
5718    /**
5719     * Gets the unique identifier of this view on the screen for accessibility purposes.
5720     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
5721     *
5722     * @return The view accessibility id.
5723     *
5724     * @hide
5725     */
5726    public int getAccessibilityViewId() {
5727        if (mAccessibilityViewId == NO_ID) {
5728            mAccessibilityViewId = sNextAccessibilityViewId++;
5729        }
5730        return mAccessibilityViewId;
5731    }
5732
5733    /**
5734     * Gets the unique identifier of the window in which this View reseides.
5735     *
5736     * @return The window accessibility id.
5737     *
5738     * @hide
5739     */
5740    public int getAccessibilityWindowId() {
5741        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID;
5742    }
5743
5744    /**
5745     * Gets the {@link View} description. It briefly describes the view and is
5746     * primarily used for accessibility support. Set this property to enable
5747     * better accessibility support for your application. This is especially
5748     * true for views that do not have textual representation (For example,
5749     * ImageButton).
5750     *
5751     * @return The content description.
5752     *
5753     * @attr ref android.R.styleable#View_contentDescription
5754     */
5755    @ViewDebug.ExportedProperty(category = "accessibility")
5756    public CharSequence getContentDescription() {
5757        return mContentDescription;
5758    }
5759
5760    /**
5761     * Sets the {@link View} description. It briefly describes the view and is
5762     * primarily used for accessibility support. Set this property to enable
5763     * better accessibility support for your application. This is especially
5764     * true for views that do not have textual representation (For example,
5765     * ImageButton).
5766     *
5767     * @param contentDescription The content description.
5768     *
5769     * @attr ref android.R.styleable#View_contentDescription
5770     */
5771    @RemotableViewMethod
5772    public void setContentDescription(CharSequence contentDescription) {
5773        if (mContentDescription == null) {
5774            if (contentDescription == null) {
5775                return;
5776            }
5777        } else if (mContentDescription.equals(contentDescription)) {
5778            return;
5779        }
5780        mContentDescription = contentDescription;
5781        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
5782        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
5783            setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
5784            notifySubtreeAccessibilityStateChangedIfNeeded();
5785        } else {
5786            notifyViewAccessibilityStateChangedIfNeeded(
5787                    AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION);
5788        }
5789    }
5790
5791    /**
5792     * Gets the id of a view for which this view serves as a label for
5793     * accessibility purposes.
5794     *
5795     * @return The labeled view id.
5796     */
5797    @ViewDebug.ExportedProperty(category = "accessibility")
5798    public int getLabelFor() {
5799        return mLabelForId;
5800    }
5801
5802    /**
5803     * Sets the id of a view for which this view serves as a label for
5804     * accessibility purposes.
5805     *
5806     * @param id The labeled view id.
5807     */
5808    @RemotableViewMethod
5809    public void setLabelFor(int id) {
5810        mLabelForId = id;
5811        if (mLabelForId != View.NO_ID
5812                && mID == View.NO_ID) {
5813            mID = generateViewId();
5814        }
5815    }
5816
5817    /**
5818     * Invoked whenever this view loses focus, either by losing window focus or by losing
5819     * focus within its window. This method can be used to clear any state tied to the
5820     * focus. For instance, if a button is held pressed with the trackball and the window
5821     * loses focus, this method can be used to cancel the press.
5822     *
5823     * Subclasses of View overriding this method should always call super.onFocusLost().
5824     *
5825     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
5826     * @see #onWindowFocusChanged(boolean)
5827     *
5828     * @hide pending API council approval
5829     */
5830    protected void onFocusLost() {
5831        resetPressedState();
5832    }
5833
5834    private void resetPressedState() {
5835        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
5836            return;
5837        }
5838
5839        if (isPressed()) {
5840            setPressed(false);
5841
5842            if (!mHasPerformedLongPress) {
5843                removeLongPressCallback();
5844            }
5845        }
5846    }
5847
5848    /**
5849     * Returns true if this view has focus
5850     *
5851     * @return True if this view has focus, false otherwise.
5852     */
5853    @ViewDebug.ExportedProperty(category = "focus")
5854    public boolean isFocused() {
5855        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
5856    }
5857
5858    /**
5859     * Find the view in the hierarchy rooted at this view that currently has
5860     * focus.
5861     *
5862     * @return The view that currently has focus, or null if no focused view can
5863     *         be found.
5864     */
5865    public View findFocus() {
5866        return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
5867    }
5868
5869    /**
5870     * Indicates whether this view is one of the set of scrollable containers in
5871     * its window.
5872     *
5873     * @return whether this view is one of the set of scrollable containers in
5874     * its window
5875     *
5876     * @attr ref android.R.styleable#View_isScrollContainer
5877     */
5878    public boolean isScrollContainer() {
5879        return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0;
5880    }
5881
5882    /**
5883     * Change whether this view is one of the set of scrollable containers in
5884     * its window.  This will be used to determine whether the window can
5885     * resize or must pan when a soft input area is open -- scrollable
5886     * containers allow the window to use resize mode since the container
5887     * will appropriately shrink.
5888     *
5889     * @attr ref android.R.styleable#View_isScrollContainer
5890     */
5891    public void setScrollContainer(boolean isScrollContainer) {
5892        if (isScrollContainer) {
5893            if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) {
5894                mAttachInfo.mScrollContainers.add(this);
5895                mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
5896            }
5897            mPrivateFlags |= PFLAG_SCROLL_CONTAINER;
5898        } else {
5899            if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
5900                mAttachInfo.mScrollContainers.remove(this);
5901            }
5902            mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED);
5903        }
5904    }
5905
5906    /**
5907     * Returns the quality of the drawing cache.
5908     *
5909     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5910     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5911     *
5912     * @see #setDrawingCacheQuality(int)
5913     * @see #setDrawingCacheEnabled(boolean)
5914     * @see #isDrawingCacheEnabled()
5915     *
5916     * @attr ref android.R.styleable#View_drawingCacheQuality
5917     */
5918    @DrawingCacheQuality
5919    public int getDrawingCacheQuality() {
5920        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
5921    }
5922
5923    /**
5924     * Set the drawing cache quality of this view. This value is used only when the
5925     * drawing cache is enabled
5926     *
5927     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5928     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5929     *
5930     * @see #getDrawingCacheQuality()
5931     * @see #setDrawingCacheEnabled(boolean)
5932     * @see #isDrawingCacheEnabled()
5933     *
5934     * @attr ref android.R.styleable#View_drawingCacheQuality
5935     */
5936    public void setDrawingCacheQuality(@DrawingCacheQuality int quality) {
5937        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
5938    }
5939
5940    /**
5941     * Returns whether the screen should remain on, corresponding to the current
5942     * value of {@link #KEEP_SCREEN_ON}.
5943     *
5944     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
5945     *
5946     * @see #setKeepScreenOn(boolean)
5947     *
5948     * @attr ref android.R.styleable#View_keepScreenOn
5949     */
5950    public boolean getKeepScreenOn() {
5951        return (mViewFlags & KEEP_SCREEN_ON) != 0;
5952    }
5953
5954    /**
5955     * Controls whether the screen should remain on, modifying the
5956     * value of {@link #KEEP_SCREEN_ON}.
5957     *
5958     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
5959     *
5960     * @see #getKeepScreenOn()
5961     *
5962     * @attr ref android.R.styleable#View_keepScreenOn
5963     */
5964    public void setKeepScreenOn(boolean keepScreenOn) {
5965        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
5966    }
5967
5968    /**
5969     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5970     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5971     *
5972     * @attr ref android.R.styleable#View_nextFocusLeft
5973     */
5974    public int getNextFocusLeftId() {
5975        return mNextFocusLeftId;
5976    }
5977
5978    /**
5979     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5980     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
5981     * decide automatically.
5982     *
5983     * @attr ref android.R.styleable#View_nextFocusLeft
5984     */
5985    public void setNextFocusLeftId(int nextFocusLeftId) {
5986        mNextFocusLeftId = nextFocusLeftId;
5987    }
5988
5989    /**
5990     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5991     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5992     *
5993     * @attr ref android.R.styleable#View_nextFocusRight
5994     */
5995    public int getNextFocusRightId() {
5996        return mNextFocusRightId;
5997    }
5998
5999    /**
6000     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
6001     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
6002     * decide automatically.
6003     *
6004     * @attr ref android.R.styleable#View_nextFocusRight
6005     */
6006    public void setNextFocusRightId(int nextFocusRightId) {
6007        mNextFocusRightId = nextFocusRightId;
6008    }
6009
6010    /**
6011     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
6012     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6013     *
6014     * @attr ref android.R.styleable#View_nextFocusUp
6015     */
6016    public int getNextFocusUpId() {
6017        return mNextFocusUpId;
6018    }
6019
6020    /**
6021     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
6022     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
6023     * decide automatically.
6024     *
6025     * @attr ref android.R.styleable#View_nextFocusUp
6026     */
6027    public void setNextFocusUpId(int nextFocusUpId) {
6028        mNextFocusUpId = nextFocusUpId;
6029    }
6030
6031    /**
6032     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
6033     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6034     *
6035     * @attr ref android.R.styleable#View_nextFocusDown
6036     */
6037    public int getNextFocusDownId() {
6038        return mNextFocusDownId;
6039    }
6040
6041    /**
6042     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
6043     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
6044     * decide automatically.
6045     *
6046     * @attr ref android.R.styleable#View_nextFocusDown
6047     */
6048    public void setNextFocusDownId(int nextFocusDownId) {
6049        mNextFocusDownId = nextFocusDownId;
6050    }
6051
6052    /**
6053     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
6054     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6055     *
6056     * @attr ref android.R.styleable#View_nextFocusForward
6057     */
6058    public int getNextFocusForwardId() {
6059        return mNextFocusForwardId;
6060    }
6061
6062    /**
6063     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
6064     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
6065     * decide automatically.
6066     *
6067     * @attr ref android.R.styleable#View_nextFocusForward
6068     */
6069    public void setNextFocusForwardId(int nextFocusForwardId) {
6070        mNextFocusForwardId = nextFocusForwardId;
6071    }
6072
6073    /**
6074     * Returns the visibility of this view and all of its ancestors
6075     *
6076     * @return True if this view and all of its ancestors are {@link #VISIBLE}
6077     */
6078    public boolean isShown() {
6079        View current = this;
6080        //noinspection ConstantConditions
6081        do {
6082            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6083                return false;
6084            }
6085            ViewParent parent = current.mParent;
6086            if (parent == null) {
6087                return false; // We are not attached to the view root
6088            }
6089            if (!(parent instanceof View)) {
6090                return true;
6091            }
6092            current = (View) parent;
6093        } while (current != null);
6094
6095        return false;
6096    }
6097
6098    /**
6099     * Called by the view hierarchy when the content insets for a window have
6100     * changed, to allow it to adjust its content to fit within those windows.
6101     * The content insets tell you the space that the status bar, input method,
6102     * and other system windows infringe on the application's window.
6103     *
6104     * <p>You do not normally need to deal with this function, since the default
6105     * window decoration given to applications takes care of applying it to the
6106     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
6107     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
6108     * and your content can be placed under those system elements.  You can then
6109     * use this method within your view hierarchy if you have parts of your UI
6110     * which you would like to ensure are not being covered.
6111     *
6112     * <p>The default implementation of this method simply applies the content
6113     * insets to the view's padding, consuming that content (modifying the
6114     * insets to be 0), and returning true.  This behavior is off by default, but can
6115     * be enabled through {@link #setFitsSystemWindows(boolean)}.
6116     *
6117     * <p>This function's traversal down the hierarchy is depth-first.  The same content
6118     * insets object is propagated down the hierarchy, so any changes made to it will
6119     * be seen by all following views (including potentially ones above in
6120     * the hierarchy since this is a depth-first traversal).  The first view
6121     * that returns true will abort the entire traversal.
6122     *
6123     * <p>The default implementation works well for a situation where it is
6124     * used with a container that covers the entire window, allowing it to
6125     * apply the appropriate insets to its content on all edges.  If you need
6126     * a more complicated layout (such as two different views fitting system
6127     * windows, one on the top of the window, and one on the bottom),
6128     * you can override the method and handle the insets however you would like.
6129     * Note that the insets provided by the framework are always relative to the
6130     * far edges of the window, not accounting for the location of the called view
6131     * within that window.  (In fact when this method is called you do not yet know
6132     * where the layout will place the view, as it is done before layout happens.)
6133     *
6134     * <p>Note: unlike many View methods, there is no dispatch phase to this
6135     * call.  If you are overriding it in a ViewGroup and want to allow the
6136     * call to continue to your children, you must be sure to call the super
6137     * implementation.
6138     *
6139     * <p>Here is a sample layout that makes use of fitting system windows
6140     * to have controls for a video view placed inside of the window decorations
6141     * that it hides and shows.  This can be used with code like the second
6142     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
6143     *
6144     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
6145     *
6146     * @param insets Current content insets of the window.  Prior to
6147     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
6148     * the insets or else you and Android will be unhappy.
6149     *
6150     * @return {@code true} if this view applied the insets and it should not
6151     * continue propagating further down the hierarchy, {@code false} otherwise.
6152     * @see #getFitsSystemWindows()
6153     * @see #setFitsSystemWindows(boolean)
6154     * @see #setSystemUiVisibility(int)
6155     *
6156     * @deprecated As of API XX use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply
6157     * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use
6158     * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)}
6159     * to implement handling their own insets.
6160     */
6161    protected boolean fitSystemWindows(Rect insets) {
6162        if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) {
6163            // If we're not in the process of dispatching the newer apply insets call,
6164            // that means we're not in the compatibility path. Dispatch into the newer
6165            // apply insets path and take things from there.
6166            try {
6167                mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS;
6168                return !dispatchApplyWindowInsets(new WindowInsets(insets)).hasInsets();
6169            } finally {
6170                mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS;
6171            }
6172        } else {
6173            // We're being called from the newer apply insets path.
6174            // Perform the standard fallback behavior.
6175            return fitSystemWindowsInt(insets);
6176        }
6177    }
6178
6179    private boolean fitSystemWindowsInt(Rect insets) {
6180        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
6181            mUserPaddingStart = UNDEFINED_PADDING;
6182            mUserPaddingEnd = UNDEFINED_PADDING;
6183            Rect localInsets = sThreadLocal.get();
6184            if (localInsets == null) {
6185                localInsets = new Rect();
6186                sThreadLocal.set(localInsets);
6187            }
6188            boolean res = computeFitSystemWindows(insets, localInsets);
6189            mUserPaddingLeftInitial = localInsets.left;
6190            mUserPaddingRightInitial = localInsets.right;
6191            internalSetPadding(localInsets.left, localInsets.top,
6192                    localInsets.right, localInsets.bottom);
6193            return res;
6194        }
6195        return false;
6196    }
6197
6198    /**
6199     * Called when the view should apply {@link WindowInsets} according to its internal policy.
6200     *
6201     * <p>This method should be overridden by views that wish to apply a policy different from or
6202     * in addition to the default behavior. Clients that wish to force a view subtree
6203     * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p>
6204     *
6205     * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set
6206     * it will be called during dispatch instead of this method. The listener may optionally
6207     * call this method from its own implementation if it wishes to apply the view's default
6208     * insets policy in addition to its own.</p>
6209     *
6210     * <p>Implementations of this method should either return the insets parameter unchanged
6211     * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed
6212     * that this view applied itself. This allows new inset types added in future platform
6213     * versions to pass through existing implementations unchanged without being erroneously
6214     * consumed.</p>
6215     *
6216     * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows}
6217     * property is set then the view will consume the system window insets and apply them
6218     * as padding for the view.</p>
6219     *
6220     * @param insets Insets to apply
6221     * @return The supplied insets with any applied insets consumed
6222     */
6223    public WindowInsets onApplyWindowInsets(WindowInsets insets) {
6224        if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) {
6225            // We weren't called from within a direct call to fitSystemWindows,
6226            // call into it as a fallback in case we're in a class that overrides it
6227            // and has logic to perform.
6228            if (fitSystemWindows(insets.getSystemWindowInsets())) {
6229                return insets.cloneWithSystemWindowInsetsConsumed();
6230            }
6231        } else {
6232            // We were called from within a direct call to fitSystemWindows.
6233            if (fitSystemWindowsInt(insets.getSystemWindowInsets())) {
6234                return insets.cloneWithSystemWindowInsetsConsumed();
6235            }
6236        }
6237        return insets;
6238    }
6239
6240    /**
6241     * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying
6242     * window insets to this view. The listener's
6243     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
6244     * method will be called instead of the view's
6245     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
6246     *
6247     * @param listener Listener to set
6248     *
6249     * @see #onApplyWindowInsets(WindowInsets)
6250     */
6251    public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) {
6252        getListenerInfo().mOnApplyWindowInsetsListener = listener;
6253    }
6254
6255    /**
6256     * Request to apply the given window insets to this view or another view in its subtree.
6257     *
6258     * <p>This method should be called by clients wishing to apply insets corresponding to areas
6259     * obscured by window decorations or overlays. This can include the status and navigation bars,
6260     * action bars, input methods and more. New inset categories may be added in the future.
6261     * The method returns the insets provided minus any that were applied by this view or its
6262     * children.</p>
6263     *
6264     * <p>Clients wishing to provide custom behavior should override the
6265     * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a
6266     * {@link OnApplyWindowInsetsListener} via the
6267     * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener}
6268     * method.</p>
6269     *
6270     * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method.
6271     * </p>
6272     *
6273     * @param insets Insets to apply
6274     * @return The provided insets minus the insets that were consumed
6275     */
6276    public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) {
6277        try {
6278            mPrivateFlags3 |= PFLAG3_APPLYING_INSETS;
6279            if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) {
6280                return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets);
6281            } else {
6282                return onApplyWindowInsets(insets);
6283            }
6284        } finally {
6285            mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS;
6286        }
6287    }
6288
6289    /**
6290     * @hide Compute the insets that should be consumed by this view and the ones
6291     * that should propagate to those under it.
6292     */
6293    protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) {
6294        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
6295                || mAttachInfo == null
6296                || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0
6297                        && !mAttachInfo.mOverscanRequested)) {
6298            outLocalInsets.set(inoutInsets);
6299            inoutInsets.set(0, 0, 0, 0);
6300            return true;
6301        } else {
6302            // The application wants to take care of fitting system window for
6303            // the content...  however we still need to take care of any overscan here.
6304            final Rect overscan = mAttachInfo.mOverscanInsets;
6305            outLocalInsets.set(overscan);
6306            inoutInsets.left -= overscan.left;
6307            inoutInsets.top -= overscan.top;
6308            inoutInsets.right -= overscan.right;
6309            inoutInsets.bottom -= overscan.bottom;
6310            return false;
6311        }
6312    }
6313
6314    /**
6315     * Sets whether or not this view should account for system screen decorations
6316     * such as the status bar and inset its content; that is, controlling whether
6317     * the default implementation of {@link #fitSystemWindows(Rect)} will be
6318     * executed.  See that method for more details.
6319     *
6320     * <p>Note that if you are providing your own implementation of
6321     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
6322     * flag to true -- your implementation will be overriding the default
6323     * implementation that checks this flag.
6324     *
6325     * @param fitSystemWindows If true, then the default implementation of
6326     * {@link #fitSystemWindows(Rect)} will be executed.
6327     *
6328     * @attr ref android.R.styleable#View_fitsSystemWindows
6329     * @see #getFitsSystemWindows()
6330     * @see #fitSystemWindows(Rect)
6331     * @see #setSystemUiVisibility(int)
6332     */
6333    public void setFitsSystemWindows(boolean fitSystemWindows) {
6334        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
6335    }
6336
6337    /**
6338     * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method
6339     * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)}
6340     * will be executed.
6341     *
6342     * @return {@code true} if the default implementation of
6343     * {@link #fitSystemWindows(Rect)} will be executed.
6344     *
6345     * @attr ref android.R.styleable#View_fitsSystemWindows
6346     * @see #setFitsSystemWindows(boolean)
6347     * @see #fitSystemWindows(Rect)
6348     * @see #setSystemUiVisibility(int)
6349     */
6350    public boolean getFitsSystemWindows() {
6351        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
6352    }
6353
6354    /** @hide */
6355    public boolean fitsSystemWindows() {
6356        return getFitsSystemWindows();
6357    }
6358
6359    /**
6360     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
6361     * @deprecated Use {@link #requestApplyInsets()} for newer platform versions.
6362     */
6363    public void requestFitSystemWindows() {
6364        if (mParent != null) {
6365            mParent.requestFitSystemWindows();
6366        }
6367    }
6368
6369    /**
6370     * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed.
6371     */
6372    public void requestApplyInsets() {
6373        requestFitSystemWindows();
6374    }
6375
6376    /**
6377     * For use by PhoneWindow to make its own system window fitting optional.
6378     * @hide
6379     */
6380    public void makeOptionalFitsSystemWindows() {
6381        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
6382    }
6383
6384    /**
6385     * Returns the visibility status for this view.
6386     *
6387     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
6388     * @attr ref android.R.styleable#View_visibility
6389     */
6390    @ViewDebug.ExportedProperty(mapping = {
6391        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
6392        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
6393        @ViewDebug.IntToString(from = GONE,      to = "GONE")
6394    })
6395    @Visibility
6396    public int getVisibility() {
6397        return mViewFlags & VISIBILITY_MASK;
6398    }
6399
6400    /**
6401     * Set the enabled state of this view.
6402     *
6403     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
6404     * @attr ref android.R.styleable#View_visibility
6405     */
6406    @RemotableViewMethod
6407    public void setVisibility(@Visibility int visibility) {
6408        setFlags(visibility, VISIBILITY_MASK);
6409        if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false);
6410    }
6411
6412    /**
6413     * Returns the enabled status for this view. The interpretation of the
6414     * enabled state varies by subclass.
6415     *
6416     * @return True if this view is enabled, false otherwise.
6417     */
6418    @ViewDebug.ExportedProperty
6419    public boolean isEnabled() {
6420        return (mViewFlags & ENABLED_MASK) == ENABLED;
6421    }
6422
6423    /**
6424     * Set the enabled state of this view. The interpretation of the enabled
6425     * state varies by subclass.
6426     *
6427     * @param enabled True if this view is enabled, false otherwise.
6428     */
6429    @RemotableViewMethod
6430    public void setEnabled(boolean enabled) {
6431        if (enabled == isEnabled()) return;
6432
6433        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
6434
6435        /*
6436         * The View most likely has to change its appearance, so refresh
6437         * the drawable state.
6438         */
6439        refreshDrawableState();
6440
6441        // Invalidate too, since the default behavior for views is to be
6442        // be drawn at 50% alpha rather than to change the drawable.
6443        invalidate(true);
6444
6445        if (!enabled) {
6446            cancelPendingInputEvents();
6447        }
6448    }
6449
6450    /**
6451     * Set whether this view can receive the focus.
6452     *
6453     * Setting this to false will also ensure that this view is not focusable
6454     * in touch mode.
6455     *
6456     * @param focusable If true, this view can receive the focus.
6457     *
6458     * @see #setFocusableInTouchMode(boolean)
6459     * @attr ref android.R.styleable#View_focusable
6460     */
6461    public void setFocusable(boolean focusable) {
6462        if (!focusable) {
6463            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
6464        }
6465        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
6466    }
6467
6468    /**
6469     * Set whether this view can receive focus while in touch mode.
6470     *
6471     * Setting this to true will also ensure that this view is focusable.
6472     *
6473     * @param focusableInTouchMode If true, this view can receive the focus while
6474     *   in touch mode.
6475     *
6476     * @see #setFocusable(boolean)
6477     * @attr ref android.R.styleable#View_focusableInTouchMode
6478     */
6479    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
6480        // Focusable in touch mode should always be set before the focusable flag
6481        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
6482        // which, in touch mode, will not successfully request focus on this view
6483        // because the focusable in touch mode flag is not set
6484        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
6485        if (focusableInTouchMode) {
6486            setFlags(FOCUSABLE, FOCUSABLE_MASK);
6487        }
6488    }
6489
6490    /**
6491     * Set whether this view should have sound effects enabled for events such as
6492     * clicking and touching.
6493     *
6494     * <p>You may wish to disable sound effects for a view if you already play sounds,
6495     * for instance, a dial key that plays dtmf tones.
6496     *
6497     * @param soundEffectsEnabled whether sound effects are enabled for this view.
6498     * @see #isSoundEffectsEnabled()
6499     * @see #playSoundEffect(int)
6500     * @attr ref android.R.styleable#View_soundEffectsEnabled
6501     */
6502    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
6503        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
6504    }
6505
6506    /**
6507     * @return whether this view should have sound effects enabled for events such as
6508     *     clicking and touching.
6509     *
6510     * @see #setSoundEffectsEnabled(boolean)
6511     * @see #playSoundEffect(int)
6512     * @attr ref android.R.styleable#View_soundEffectsEnabled
6513     */
6514    @ViewDebug.ExportedProperty
6515    public boolean isSoundEffectsEnabled() {
6516        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
6517    }
6518
6519    /**
6520     * Set whether this view should have haptic feedback for events such as
6521     * long presses.
6522     *
6523     * <p>You may wish to disable haptic feedback if your view already controls
6524     * its own haptic feedback.
6525     *
6526     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
6527     * @see #isHapticFeedbackEnabled()
6528     * @see #performHapticFeedback(int)
6529     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
6530     */
6531    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
6532        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
6533    }
6534
6535    /**
6536     * @return whether this view should have haptic feedback enabled for events
6537     * long presses.
6538     *
6539     * @see #setHapticFeedbackEnabled(boolean)
6540     * @see #performHapticFeedback(int)
6541     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
6542     */
6543    @ViewDebug.ExportedProperty
6544    public boolean isHapticFeedbackEnabled() {
6545        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
6546    }
6547
6548    /**
6549     * Returns the layout direction for this view.
6550     *
6551     * @return One of {@link #LAYOUT_DIRECTION_LTR},
6552     *   {@link #LAYOUT_DIRECTION_RTL},
6553     *   {@link #LAYOUT_DIRECTION_INHERIT} or
6554     *   {@link #LAYOUT_DIRECTION_LOCALE}.
6555     *
6556     * @attr ref android.R.styleable#View_layoutDirection
6557     *
6558     * @hide
6559     */
6560    @ViewDebug.ExportedProperty(category = "layout", mapping = {
6561        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
6562        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
6563        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
6564        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
6565    })
6566    @LayoutDir
6567    public int getRawLayoutDirection() {
6568        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
6569    }
6570
6571    /**
6572     * Set the layout direction for this view. This will propagate a reset of layout direction
6573     * resolution to the view's children and resolve layout direction for this view.
6574     *
6575     * @param layoutDirection the layout direction to set. Should be one of:
6576     *
6577     * {@link #LAYOUT_DIRECTION_LTR},
6578     * {@link #LAYOUT_DIRECTION_RTL},
6579     * {@link #LAYOUT_DIRECTION_INHERIT},
6580     * {@link #LAYOUT_DIRECTION_LOCALE}.
6581     *
6582     * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution
6583     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
6584     * will return the default {@link #LAYOUT_DIRECTION_LTR}.
6585     *
6586     * @attr ref android.R.styleable#View_layoutDirection
6587     */
6588    @RemotableViewMethod
6589    public void setLayoutDirection(@LayoutDir int layoutDirection) {
6590        if (getRawLayoutDirection() != layoutDirection) {
6591            // Reset the current layout direction and the resolved one
6592            mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK;
6593            resetRtlProperties();
6594            // Set the new layout direction (filtered)
6595            mPrivateFlags2 |=
6596                    ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK);
6597            // We need to resolve all RTL properties as they all depend on layout direction
6598            resolveRtlPropertiesIfNeeded();
6599            requestLayout();
6600            invalidate(true);
6601        }
6602    }
6603
6604    /**
6605     * Returns the resolved layout direction for this view.
6606     *
6607     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
6608     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
6609     *
6610     * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version
6611     * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}.
6612     *
6613     * @attr ref android.R.styleable#View_layoutDirection
6614     */
6615    @ViewDebug.ExportedProperty(category = "layout", mapping = {
6616        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
6617        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
6618    })
6619    @ResolvedLayoutDir
6620    public int getLayoutDirection() {
6621        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
6622        if (targetSdkVersion < JELLY_BEAN_MR1) {
6623            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
6624            return LAYOUT_DIRECTION_RESOLVED_DEFAULT;
6625        }
6626        return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ==
6627                PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
6628    }
6629
6630    /**
6631     * Indicates whether or not this view's layout is right-to-left. This is resolved from
6632     * layout attribute and/or the inherited value from the parent
6633     *
6634     * @return true if the layout is right-to-left.
6635     *
6636     * @hide
6637     */
6638    @ViewDebug.ExportedProperty(category = "layout")
6639    public boolean isLayoutRtl() {
6640        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
6641    }
6642
6643    /**
6644     * Indicates whether the view is currently tracking transient state that the
6645     * app should not need to concern itself with saving and restoring, but that
6646     * the framework should take special note to preserve when possible.
6647     *
6648     * <p>A view with transient state cannot be trivially rebound from an external
6649     * data source, such as an adapter binding item views in a list. This may be
6650     * because the view is performing an animation, tracking user selection
6651     * of content, or similar.</p>
6652     *
6653     * @return true if the view has transient state
6654     */
6655    @ViewDebug.ExportedProperty(category = "layout")
6656    public boolean hasTransientState() {
6657        return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE;
6658    }
6659
6660    /**
6661     * Set whether this view is currently tracking transient state that the
6662     * framework should attempt to preserve when possible. This flag is reference counted,
6663     * so every call to setHasTransientState(true) should be paired with a later call
6664     * to setHasTransientState(false).
6665     *
6666     * <p>A view with transient state cannot be trivially rebound from an external
6667     * data source, such as an adapter binding item views in a list. This may be
6668     * because the view is performing an animation, tracking user selection
6669     * of content, or similar.</p>
6670     *
6671     * @param hasTransientState true if this view has transient state
6672     */
6673    public void setHasTransientState(boolean hasTransientState) {
6674        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
6675                mTransientStateCount - 1;
6676        if (mTransientStateCount < 0) {
6677            mTransientStateCount = 0;
6678            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
6679                    "unmatched pair of setHasTransientState calls");
6680        } else if ((hasTransientState && mTransientStateCount == 1) ||
6681                (!hasTransientState && mTransientStateCount == 0)) {
6682            // update flag if we've just incremented up from 0 or decremented down to 0
6683            mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) |
6684                    (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0);
6685            if (mParent != null) {
6686                try {
6687                    mParent.childHasTransientStateChanged(this, hasTransientState);
6688                } catch (AbstractMethodError e) {
6689                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
6690                            " does not fully implement ViewParent", e);
6691                }
6692            }
6693        }
6694    }
6695
6696    /**
6697     * Returns true if this view is currently attached to a window.
6698     */
6699    public boolean isAttachedToWindow() {
6700        return mAttachInfo != null;
6701    }
6702
6703    /**
6704     * Returns true if this view has been through at least one layout since it
6705     * was last attached to or detached from a window.
6706     */
6707    public boolean isLaidOut() {
6708        return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT;
6709    }
6710
6711    /**
6712     * If this view doesn't do any drawing on its own, set this flag to
6713     * allow further optimizations. By default, this flag is not set on
6714     * View, but could be set on some View subclasses such as ViewGroup.
6715     *
6716     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
6717     * you should clear this flag.
6718     *
6719     * @param willNotDraw whether or not this View draw on its own
6720     */
6721    public void setWillNotDraw(boolean willNotDraw) {
6722        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
6723    }
6724
6725    /**
6726     * Returns whether or not this View draws on its own.
6727     *
6728     * @return true if this view has nothing to draw, false otherwise
6729     */
6730    @ViewDebug.ExportedProperty(category = "drawing")
6731    public boolean willNotDraw() {
6732        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
6733    }
6734
6735    /**
6736     * When a View's drawing cache is enabled, drawing is redirected to an
6737     * offscreen bitmap. Some views, like an ImageView, must be able to
6738     * bypass this mechanism if they already draw a single bitmap, to avoid
6739     * unnecessary usage of the memory.
6740     *
6741     * @param willNotCacheDrawing true if this view does not cache its
6742     *        drawing, false otherwise
6743     */
6744    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
6745        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
6746    }
6747
6748    /**
6749     * Returns whether or not this View can cache its drawing or not.
6750     *
6751     * @return true if this view does not cache its drawing, false otherwise
6752     */
6753    @ViewDebug.ExportedProperty(category = "drawing")
6754    public boolean willNotCacheDrawing() {
6755        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
6756    }
6757
6758    /**
6759     * Indicates whether this view reacts to click events or not.
6760     *
6761     * @return true if the view is clickable, false otherwise
6762     *
6763     * @see #setClickable(boolean)
6764     * @attr ref android.R.styleable#View_clickable
6765     */
6766    @ViewDebug.ExportedProperty
6767    public boolean isClickable() {
6768        return (mViewFlags & CLICKABLE) == CLICKABLE;
6769    }
6770
6771    /**
6772     * Enables or disables click events for this view. When a view
6773     * is clickable it will change its state to "pressed" on every click.
6774     * Subclasses should set the view clickable to visually react to
6775     * user's clicks.
6776     *
6777     * @param clickable true to make the view clickable, false otherwise
6778     *
6779     * @see #isClickable()
6780     * @attr ref android.R.styleable#View_clickable
6781     */
6782    public void setClickable(boolean clickable) {
6783        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
6784    }
6785
6786    /**
6787     * Indicates whether this view reacts to long click events or not.
6788     *
6789     * @return true if the view is long clickable, false otherwise
6790     *
6791     * @see #setLongClickable(boolean)
6792     * @attr ref android.R.styleable#View_longClickable
6793     */
6794    public boolean isLongClickable() {
6795        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
6796    }
6797
6798    /**
6799     * Enables or disables long click events for this view. When a view is long
6800     * clickable it reacts to the user holding down the button for a longer
6801     * duration than a tap. This event can either launch the listener or a
6802     * context menu.
6803     *
6804     * @param longClickable true to make the view long clickable, false otherwise
6805     * @see #isLongClickable()
6806     * @attr ref android.R.styleable#View_longClickable
6807     */
6808    public void setLongClickable(boolean longClickable) {
6809        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
6810    }
6811
6812    /**
6813     * Sets the pressed state for this view.
6814     *
6815     * @see #isClickable()
6816     * @see #setClickable(boolean)
6817     *
6818     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
6819     *        the View's internal state from a previously set "pressed" state.
6820     */
6821    public void setPressed(boolean pressed) {
6822        final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
6823
6824        if (pressed) {
6825            mPrivateFlags |= PFLAG_PRESSED;
6826        } else {
6827            mPrivateFlags &= ~PFLAG_PRESSED;
6828        }
6829
6830        if (needsRefresh) {
6831            refreshDrawableState();
6832        }
6833        dispatchSetPressed(pressed);
6834    }
6835
6836    /**
6837     * Dispatch setPressed to all of this View's children.
6838     *
6839     * @see #setPressed(boolean)
6840     *
6841     * @param pressed The new pressed state
6842     */
6843    protected void dispatchSetPressed(boolean pressed) {
6844    }
6845
6846    /**
6847     * Indicates whether the view is currently in pressed state. Unless
6848     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
6849     * the pressed state.
6850     *
6851     * @see #setPressed(boolean)
6852     * @see #isClickable()
6853     * @see #setClickable(boolean)
6854     *
6855     * @return true if the view is currently pressed, false otherwise
6856     */
6857    public boolean isPressed() {
6858        return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED;
6859    }
6860
6861    /**
6862     * Indicates whether this view will save its state (that is,
6863     * whether its {@link #onSaveInstanceState} method will be called).
6864     *
6865     * @return Returns true if the view state saving is enabled, else false.
6866     *
6867     * @see #setSaveEnabled(boolean)
6868     * @attr ref android.R.styleable#View_saveEnabled
6869     */
6870    public boolean isSaveEnabled() {
6871        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
6872    }
6873
6874    /**
6875     * Controls whether the saving of this view's state is
6876     * enabled (that is, whether its {@link #onSaveInstanceState} method
6877     * will be called).  Note that even if freezing is enabled, the
6878     * view still must have an id assigned to it (via {@link #setId(int)})
6879     * for its state to be saved.  This flag can only disable the
6880     * saving of this view; any child views may still have their state saved.
6881     *
6882     * @param enabled Set to false to <em>disable</em> state saving, or true
6883     * (the default) to allow it.
6884     *
6885     * @see #isSaveEnabled()
6886     * @see #setId(int)
6887     * @see #onSaveInstanceState()
6888     * @attr ref android.R.styleable#View_saveEnabled
6889     */
6890    public void setSaveEnabled(boolean enabled) {
6891        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
6892    }
6893
6894    /**
6895     * Gets whether the framework should discard touches when the view's
6896     * window is obscured by another visible window.
6897     * Refer to the {@link View} security documentation for more details.
6898     *
6899     * @return True if touch filtering is enabled.
6900     *
6901     * @see #setFilterTouchesWhenObscured(boolean)
6902     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
6903     */
6904    @ViewDebug.ExportedProperty
6905    public boolean getFilterTouchesWhenObscured() {
6906        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
6907    }
6908
6909    /**
6910     * Sets whether the framework should discard touches when the view's
6911     * window is obscured by another visible window.
6912     * Refer to the {@link View} security documentation for more details.
6913     *
6914     * @param enabled True if touch filtering should be enabled.
6915     *
6916     * @see #getFilterTouchesWhenObscured
6917     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
6918     */
6919    public void setFilterTouchesWhenObscured(boolean enabled) {
6920        setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
6921                FILTER_TOUCHES_WHEN_OBSCURED);
6922    }
6923
6924    /**
6925     * Indicates whether the entire hierarchy under this view will save its
6926     * state when a state saving traversal occurs from its parent.  The default
6927     * is true; if false, these views will not be saved unless
6928     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
6929     *
6930     * @return Returns true if the view state saving from parent is enabled, else false.
6931     *
6932     * @see #setSaveFromParentEnabled(boolean)
6933     */
6934    public boolean isSaveFromParentEnabled() {
6935        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
6936    }
6937
6938    /**
6939     * Controls whether the entire hierarchy under this view will save its
6940     * state when a state saving traversal occurs from its parent.  The default
6941     * is true; if false, these views will not be saved unless
6942     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
6943     *
6944     * @param enabled Set to false to <em>disable</em> state saving, or true
6945     * (the default) to allow it.
6946     *
6947     * @see #isSaveFromParentEnabled()
6948     * @see #setId(int)
6949     * @see #onSaveInstanceState()
6950     */
6951    public void setSaveFromParentEnabled(boolean enabled) {
6952        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
6953    }
6954
6955
6956    /**
6957     * Returns whether this View is able to take focus.
6958     *
6959     * @return True if this view can take focus, or false otherwise.
6960     * @attr ref android.R.styleable#View_focusable
6961     */
6962    @ViewDebug.ExportedProperty(category = "focus")
6963    public final boolean isFocusable() {
6964        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
6965    }
6966
6967    /**
6968     * When a view is focusable, it may not want to take focus when in touch mode.
6969     * For example, a button would like focus when the user is navigating via a D-pad
6970     * so that the user can click on it, but once the user starts touching the screen,
6971     * the button shouldn't take focus
6972     * @return Whether the view is focusable in touch mode.
6973     * @attr ref android.R.styleable#View_focusableInTouchMode
6974     */
6975    @ViewDebug.ExportedProperty
6976    public final boolean isFocusableInTouchMode() {
6977        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
6978    }
6979
6980    /**
6981     * Find the nearest view in the specified direction that can take focus.
6982     * This does not actually give focus to that view.
6983     *
6984     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6985     *
6986     * @return The nearest focusable in the specified direction, or null if none
6987     *         can be found.
6988     */
6989    public View focusSearch(@FocusRealDirection int direction) {
6990        if (mParent != null) {
6991            return mParent.focusSearch(this, direction);
6992        } else {
6993            return null;
6994        }
6995    }
6996
6997    /**
6998     * This method is the last chance for the focused view and its ancestors to
6999     * respond to an arrow key. This is called when the focused view did not
7000     * consume the key internally, nor could the view system find a new view in
7001     * the requested direction to give focus to.
7002     *
7003     * @param focused The currently focused view.
7004     * @param direction The direction focus wants to move. One of FOCUS_UP,
7005     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
7006     * @return True if the this view consumed this unhandled move.
7007     */
7008    public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) {
7009        return false;
7010    }
7011
7012    /**
7013     * If a user manually specified the next view id for a particular direction,
7014     * use the root to look up the view.
7015     * @param root The root view of the hierarchy containing this view.
7016     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
7017     * or FOCUS_BACKWARD.
7018     * @return The user specified next view, or null if there is none.
7019     */
7020    View findUserSetNextFocus(View root, @FocusDirection int direction) {
7021        switch (direction) {
7022            case FOCUS_LEFT:
7023                if (mNextFocusLeftId == View.NO_ID) return null;
7024                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
7025            case FOCUS_RIGHT:
7026                if (mNextFocusRightId == View.NO_ID) return null;
7027                return findViewInsideOutShouldExist(root, mNextFocusRightId);
7028            case FOCUS_UP:
7029                if (mNextFocusUpId == View.NO_ID) return null;
7030                return findViewInsideOutShouldExist(root, mNextFocusUpId);
7031            case FOCUS_DOWN:
7032                if (mNextFocusDownId == View.NO_ID) return null;
7033                return findViewInsideOutShouldExist(root, mNextFocusDownId);
7034            case FOCUS_FORWARD:
7035                if (mNextFocusForwardId == View.NO_ID) return null;
7036                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
7037            case FOCUS_BACKWARD: {
7038                if (mID == View.NO_ID) return null;
7039                final int id = mID;
7040                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
7041                    @Override
7042                    public boolean apply(View t) {
7043                        return t.mNextFocusForwardId == id;
7044                    }
7045                });
7046            }
7047        }
7048        return null;
7049    }
7050
7051    private View findViewInsideOutShouldExist(View root, int id) {
7052        if (mMatchIdPredicate == null) {
7053            mMatchIdPredicate = new MatchIdPredicate();
7054        }
7055        mMatchIdPredicate.mId = id;
7056        View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate);
7057        if (result == null) {
7058            Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id);
7059        }
7060        return result;
7061    }
7062
7063    /**
7064     * Find and return all focusable views that are descendants of this view,
7065     * possibly including this view if it is focusable itself.
7066     *
7067     * @param direction The direction of the focus
7068     * @return A list of focusable views
7069     */
7070    public ArrayList<View> getFocusables(@FocusDirection int direction) {
7071        ArrayList<View> result = new ArrayList<View>(24);
7072        addFocusables(result, direction);
7073        return result;
7074    }
7075
7076    /**
7077     * Add any focusable views that are descendants of this view (possibly
7078     * including this view if it is focusable itself) to views.  If we are in touch mode,
7079     * only add views that are also focusable in touch mode.
7080     *
7081     * @param views Focusable views found so far
7082     * @param direction The direction of the focus
7083     */
7084    public void addFocusables(ArrayList<View> views, @FocusDirection int direction) {
7085        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
7086    }
7087
7088    /**
7089     * Adds any focusable views that are descendants of this view (possibly
7090     * including this view if it is focusable itself) to views. This method
7091     * adds all focusable views regardless if we are in touch mode or
7092     * only views focusable in touch mode if we are in touch mode or
7093     * only views that can take accessibility focus if accessibility is enabeld
7094     * depending on the focusable mode paramater.
7095     *
7096     * @param views Focusable views found so far or null if all we are interested is
7097     *        the number of focusables.
7098     * @param direction The direction of the focus.
7099     * @param focusableMode The type of focusables to be added.
7100     *
7101     * @see #FOCUSABLES_ALL
7102     * @see #FOCUSABLES_TOUCH_MODE
7103     */
7104    public void addFocusables(ArrayList<View> views, @FocusDirection int direction,
7105            @FocusableMode int focusableMode) {
7106        if (views == null) {
7107            return;
7108        }
7109        if (!isFocusable()) {
7110            return;
7111        }
7112        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
7113                && isInTouchMode() && !isFocusableInTouchMode()) {
7114            return;
7115        }
7116        views.add(this);
7117    }
7118
7119    /**
7120     * Finds the Views that contain given text. The containment is case insensitive.
7121     * The search is performed by either the text that the View renders or the content
7122     * description that describes the view for accessibility purposes and the view does
7123     * not render or both. Clients can specify how the search is to be performed via
7124     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
7125     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
7126     *
7127     * @param outViews The output list of matching Views.
7128     * @param searched The text to match against.
7129     *
7130     * @see #FIND_VIEWS_WITH_TEXT
7131     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
7132     * @see #setContentDescription(CharSequence)
7133     */
7134    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched,
7135            @FindViewFlags int flags) {
7136        if (getAccessibilityNodeProvider() != null) {
7137            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
7138                outViews.add(this);
7139            }
7140        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
7141                && (searched != null && searched.length() > 0)
7142                && (mContentDescription != null && mContentDescription.length() > 0)) {
7143            String searchedLowerCase = searched.toString().toLowerCase();
7144            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
7145            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
7146                outViews.add(this);
7147            }
7148        }
7149    }
7150
7151    /**
7152     * Find and return all touchable views that are descendants of this view,
7153     * possibly including this view if it is touchable itself.
7154     *
7155     * @return A list of touchable views
7156     */
7157    public ArrayList<View> getTouchables() {
7158        ArrayList<View> result = new ArrayList<View>();
7159        addTouchables(result);
7160        return result;
7161    }
7162
7163    /**
7164     * Add any touchable views that are descendants of this view (possibly
7165     * including this view if it is touchable itself) to views.
7166     *
7167     * @param views Touchable views found so far
7168     */
7169    public void addTouchables(ArrayList<View> views) {
7170        final int viewFlags = mViewFlags;
7171
7172        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
7173                && (viewFlags & ENABLED_MASK) == ENABLED) {
7174            views.add(this);
7175        }
7176    }
7177
7178    /**
7179     * Returns whether this View is accessibility focused.
7180     *
7181     * @return True if this View is accessibility focused.
7182     */
7183    public boolean isAccessibilityFocused() {
7184        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
7185    }
7186
7187    /**
7188     * Call this to try to give accessibility focus to this view.
7189     *
7190     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
7191     * returns false or the view is no visible or the view already has accessibility
7192     * focus.
7193     *
7194     * See also {@link #focusSearch(int)}, which is what you call to say that you
7195     * have focus, and you want your parent to look for the next one.
7196     *
7197     * @return Whether this view actually took accessibility focus.
7198     *
7199     * @hide
7200     */
7201    public boolean requestAccessibilityFocus() {
7202        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
7203        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
7204            return false;
7205        }
7206        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
7207            return false;
7208        }
7209        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
7210            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
7211            ViewRootImpl viewRootImpl = getViewRootImpl();
7212            if (viewRootImpl != null) {
7213                viewRootImpl.setAccessibilityFocus(this, null);
7214            }
7215            invalidate();
7216            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
7217            return true;
7218        }
7219        return false;
7220    }
7221
7222    /**
7223     * Call this to try to clear accessibility focus of this view.
7224     *
7225     * See also {@link #focusSearch(int)}, which is what you call to say that you
7226     * have focus, and you want your parent to look for the next one.
7227     *
7228     * @hide
7229     */
7230    public void clearAccessibilityFocus() {
7231        clearAccessibilityFocusNoCallbacks();
7232        // Clear the global reference of accessibility focus if this
7233        // view or any of its descendants had accessibility focus.
7234        ViewRootImpl viewRootImpl = getViewRootImpl();
7235        if (viewRootImpl != null) {
7236            View focusHost = viewRootImpl.getAccessibilityFocusedHost();
7237            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
7238                viewRootImpl.setAccessibilityFocus(null, null);
7239            }
7240        }
7241    }
7242
7243    private void sendAccessibilityHoverEvent(int eventType) {
7244        // Since we are not delivering to a client accessibility events from not
7245        // important views (unless the clinet request that) we need to fire the
7246        // event from the deepest view exposed to the client. As a consequence if
7247        // the user crosses a not exposed view the client will see enter and exit
7248        // of the exposed predecessor followed by and enter and exit of that same
7249        // predecessor when entering and exiting the not exposed descendant. This
7250        // is fine since the client has a clear idea which view is hovered at the
7251        // price of a couple more events being sent. This is a simple and
7252        // working solution.
7253        View source = this;
7254        while (true) {
7255            if (source.includeForAccessibility()) {
7256                source.sendAccessibilityEvent(eventType);
7257                return;
7258            }
7259            ViewParent parent = source.getParent();
7260            if (parent instanceof View) {
7261                source = (View) parent;
7262            } else {
7263                return;
7264            }
7265        }
7266    }
7267
7268    /**
7269     * Clears accessibility focus without calling any callback methods
7270     * normally invoked in {@link #clearAccessibilityFocus()}. This method
7271     * is used for clearing accessibility focus when giving this focus to
7272     * another view.
7273     */
7274    void clearAccessibilityFocusNoCallbacks() {
7275        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
7276            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
7277            invalidate();
7278            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
7279        }
7280    }
7281
7282    /**
7283     * Call this to try to give focus to a specific view or to one of its
7284     * descendants.
7285     *
7286     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7287     * false), or if it is focusable and it is not focusable in touch mode
7288     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7289     *
7290     * See also {@link #focusSearch(int)}, which is what you call to say that you
7291     * have focus, and you want your parent to look for the next one.
7292     *
7293     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
7294     * {@link #FOCUS_DOWN} and <code>null</code>.
7295     *
7296     * @return Whether this view or one of its descendants actually took focus.
7297     */
7298    public final boolean requestFocus() {
7299        return requestFocus(View.FOCUS_DOWN);
7300    }
7301
7302    /**
7303     * Call this to try to give focus to a specific view or to one of its
7304     * descendants and give it a hint about what direction focus is heading.
7305     *
7306     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7307     * false), or if it is focusable and it is not focusable in touch mode
7308     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7309     *
7310     * See also {@link #focusSearch(int)}, which is what you call to say that you
7311     * have focus, and you want your parent to look for the next one.
7312     *
7313     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
7314     * <code>null</code> set for the previously focused rectangle.
7315     *
7316     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
7317     * @return Whether this view or one of its descendants actually took focus.
7318     */
7319    public final boolean requestFocus(int direction) {
7320        return requestFocus(direction, null);
7321    }
7322
7323    /**
7324     * Call this to try to give focus to a specific view or to one of its descendants
7325     * and give it hints about the direction and a specific rectangle that the focus
7326     * is coming from.  The rectangle can help give larger views a finer grained hint
7327     * about where focus is coming from, and therefore, where to show selection, or
7328     * forward focus change internally.
7329     *
7330     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7331     * false), or if it is focusable and it is not focusable in touch mode
7332     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7333     *
7334     * A View will not take focus if it is not visible.
7335     *
7336     * A View will not take focus if one of its parents has
7337     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
7338     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
7339     *
7340     * See also {@link #focusSearch(int)}, which is what you call to say that you
7341     * have focus, and you want your parent to look for the next one.
7342     *
7343     * You may wish to override this method if your custom {@link View} has an internal
7344     * {@link View} that it wishes to forward the request to.
7345     *
7346     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
7347     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
7348     *        to give a finer grained hint about where focus is coming from.  May be null
7349     *        if there is no hint.
7350     * @return Whether this view or one of its descendants actually took focus.
7351     */
7352    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
7353        return requestFocusNoSearch(direction, previouslyFocusedRect);
7354    }
7355
7356    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
7357        // need to be focusable
7358        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
7359                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
7360            return false;
7361        }
7362
7363        // need to be focusable in touch mode if in touch mode
7364        if (isInTouchMode() &&
7365            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
7366               return false;
7367        }
7368
7369        // need to not have any parents blocking us
7370        if (hasAncestorThatBlocksDescendantFocus()) {
7371            return false;
7372        }
7373
7374        handleFocusGainInternal(direction, previouslyFocusedRect);
7375        return true;
7376    }
7377
7378    /**
7379     * Call this to try to give focus to a specific view or to one of its descendants. This is a
7380     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
7381     * touch mode to request focus when they are touched.
7382     *
7383     * @return Whether this view or one of its descendants actually took focus.
7384     *
7385     * @see #isInTouchMode()
7386     *
7387     */
7388    public final boolean requestFocusFromTouch() {
7389        // Leave touch mode if we need to
7390        if (isInTouchMode()) {
7391            ViewRootImpl viewRoot = getViewRootImpl();
7392            if (viewRoot != null) {
7393                viewRoot.ensureTouchMode(false);
7394            }
7395        }
7396        return requestFocus(View.FOCUS_DOWN);
7397    }
7398
7399    /**
7400     * @return Whether any ancestor of this view blocks descendant focus.
7401     */
7402    private boolean hasAncestorThatBlocksDescendantFocus() {
7403        ViewParent ancestor = mParent;
7404        while (ancestor instanceof ViewGroup) {
7405            final ViewGroup vgAncestor = (ViewGroup) ancestor;
7406            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
7407                return true;
7408            } else {
7409                ancestor = vgAncestor.getParent();
7410            }
7411        }
7412        return false;
7413    }
7414
7415    /**
7416     * Gets the mode for determining whether this View is important for accessibility
7417     * which is if it fires accessibility events and if it is reported to
7418     * accessibility services that query the screen.
7419     *
7420     * @return The mode for determining whether a View is important for accessibility.
7421     *
7422     * @attr ref android.R.styleable#View_importantForAccessibility
7423     *
7424     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
7425     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
7426     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
7427     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
7428     */
7429    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
7430            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
7431            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
7432            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"),
7433            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS,
7434                    to = "noHideDescendants")
7435        })
7436    public int getImportantForAccessibility() {
7437        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
7438                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
7439    }
7440
7441    /**
7442     * Sets the live region mode for this view. This indicates to accessibility
7443     * services whether they should automatically notify the user about changes
7444     * to the view's content description or text, or to the content descriptions
7445     * or text of the view's children (where applicable).
7446     * <p>
7447     * For example, in a login screen with a TextView that displays an "incorrect
7448     * password" notification, that view should be marked as a live region with
7449     * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
7450     * <p>
7451     * To disable change notifications for this view, use
7452     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region
7453     * mode for most views.
7454     * <p>
7455     * To indicate that the user should be notified of changes, use
7456     * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
7457     * <p>
7458     * If the view's changes should interrupt ongoing speech and notify the user
7459     * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}.
7460     *
7461     * @param mode The live region mode for this view, one of:
7462     *        <ul>
7463     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE}
7464     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE}
7465     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}
7466     *        </ul>
7467     * @attr ref android.R.styleable#View_accessibilityLiveRegion
7468     */
7469    public void setAccessibilityLiveRegion(int mode) {
7470        if (mode != getAccessibilityLiveRegion()) {
7471            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
7472            mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT)
7473                    & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
7474            notifyViewAccessibilityStateChangedIfNeeded(
7475                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7476        }
7477    }
7478
7479    /**
7480     * Gets the live region mode for this View.
7481     *
7482     * @return The live region mode for the view.
7483     *
7484     * @attr ref android.R.styleable#View_accessibilityLiveRegion
7485     *
7486     * @see #setAccessibilityLiveRegion(int)
7487     */
7488    public int getAccessibilityLiveRegion() {
7489        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK)
7490                >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
7491    }
7492
7493    /**
7494     * Sets how to determine whether this view is important for accessibility
7495     * which is if it fires accessibility events and if it is reported to
7496     * accessibility services that query the screen.
7497     *
7498     * @param mode How to determine whether this view is important for accessibility.
7499     *
7500     * @attr ref android.R.styleable#View_importantForAccessibility
7501     *
7502     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
7503     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
7504     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
7505     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
7506     */
7507    public void setImportantForAccessibility(int mode) {
7508        final int oldMode = getImportantForAccessibility();
7509        if (mode != oldMode) {
7510            // If we're moving between AUTO and another state, we might not need
7511            // to send a subtree changed notification. We'll store the computed
7512            // importance, since we'll need to check it later to make sure.
7513            final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO
7514                    || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO;
7515            final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility();
7516            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
7517            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
7518                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
7519            if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) {
7520                notifySubtreeAccessibilityStateChangedIfNeeded();
7521            } else {
7522                notifyViewAccessibilityStateChangedIfNeeded(
7523                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7524            }
7525        }
7526    }
7527
7528    /**
7529     * Computes whether this view should be exposed for accessibility. In
7530     * general, views that are interactive or provide information are exposed
7531     * while views that serve only as containers are hidden.
7532     * <p>
7533     * If an ancestor of this view has importance
7534     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method
7535     * returns <code>false</code>.
7536     * <p>
7537     * Otherwise, the value is computed according to the view's
7538     * {@link #getImportantForAccessibility()} value:
7539     * <ol>
7540     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or
7541     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false
7542     * </code>
7543     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code>
7544     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if
7545     * view satisfies any of the following:
7546     * <ul>
7547     * <li>Is actionable, e.g. {@link #isClickable()},
7548     * {@link #isLongClickable()}, or {@link #isFocusable()}
7549     * <li>Has an {@link AccessibilityDelegate}
7550     * <li>Has an interaction listener, e.g. {@link OnTouchListener},
7551     * {@link OnKeyListener}, etc.
7552     * <li>Is an accessibility live region, e.g.
7553     * {@link #getAccessibilityLiveRegion()} is not
7554     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}.
7555     * </ul>
7556     * </ol>
7557     *
7558     * @return Whether the view is exposed for accessibility.
7559     * @see #setImportantForAccessibility(int)
7560     * @see #getImportantForAccessibility()
7561     */
7562    public boolean isImportantForAccessibility() {
7563        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
7564                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
7565        if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO
7566                || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
7567            return false;
7568        }
7569
7570        // Check parent mode to ensure we're not hidden.
7571        ViewParent parent = mParent;
7572        while (parent instanceof View) {
7573            if (((View) parent).getImportantForAccessibility()
7574                    == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
7575                return false;
7576            }
7577            parent = parent.getParent();
7578        }
7579
7580        return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility()
7581                || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null
7582                || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE;
7583    }
7584
7585    /**
7586     * Gets the parent for accessibility purposes. Note that the parent for
7587     * accessibility is not necessary the immediate parent. It is the first
7588     * predecessor that is important for accessibility.
7589     *
7590     * @return The parent for accessibility purposes.
7591     */
7592    public ViewParent getParentForAccessibility() {
7593        if (mParent instanceof View) {
7594            View parentView = (View) mParent;
7595            if (parentView.includeForAccessibility()) {
7596                return mParent;
7597            } else {
7598                return mParent.getParentForAccessibility();
7599            }
7600        }
7601        return null;
7602    }
7603
7604    /**
7605     * Adds the children of a given View for accessibility. Since some Views are
7606     * not important for accessibility the children for accessibility are not
7607     * necessarily direct children of the view, rather they are the first level of
7608     * descendants important for accessibility.
7609     *
7610     * @param children The list of children for accessibility.
7611     */
7612    public void addChildrenForAccessibility(ArrayList<View> children) {
7613
7614    }
7615
7616    /**
7617     * Whether to regard this view for accessibility. A view is regarded for
7618     * accessibility if it is important for accessibility or the querying
7619     * accessibility service has explicitly requested that view not
7620     * important for accessibility are regarded.
7621     *
7622     * @return Whether to regard the view for accessibility.
7623     *
7624     * @hide
7625     */
7626    public boolean includeForAccessibility() {
7627        if (mAttachInfo != null) {
7628            return (mAttachInfo.mAccessibilityFetchFlags
7629                    & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0
7630                    || isImportantForAccessibility();
7631        }
7632        return false;
7633    }
7634
7635    /**
7636     * Returns whether the View is considered actionable from
7637     * accessibility perspective. Such view are important for
7638     * accessibility.
7639     *
7640     * @return True if the view is actionable for accessibility.
7641     *
7642     * @hide
7643     */
7644    public boolean isActionableForAccessibility() {
7645        return (isClickable() || isLongClickable() || isFocusable());
7646    }
7647
7648    /**
7649     * Returns whether the View has registered callbacks which makes it
7650     * important for accessibility.
7651     *
7652     * @return True if the view is actionable for accessibility.
7653     */
7654    private boolean hasListenersForAccessibility() {
7655        ListenerInfo info = getListenerInfo();
7656        return mTouchDelegate != null || info.mOnKeyListener != null
7657                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
7658                || info.mOnHoverListener != null || info.mOnDragListener != null;
7659    }
7660
7661    /**
7662     * Notifies that the accessibility state of this view changed. The change
7663     * is local to this view and does not represent structural changes such
7664     * as children and parent. For example, the view became focusable. The
7665     * notification is at at most once every
7666     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
7667     * to avoid unnecessary load to the system. Also once a view has a pending
7668     * notification this method is a NOP until the notification has been sent.
7669     *
7670     * @hide
7671     */
7672    public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) {
7673        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
7674            return;
7675        }
7676        if (mSendViewStateChangedAccessibilityEvent == null) {
7677            mSendViewStateChangedAccessibilityEvent =
7678                    new SendViewStateChangedAccessibilityEvent();
7679        }
7680        mSendViewStateChangedAccessibilityEvent.runOrPost(changeType);
7681    }
7682
7683    /**
7684     * Notifies that the accessibility state of this view changed. The change
7685     * is *not* local to this view and does represent structural changes such
7686     * as children and parent. For example, the view size changed. The
7687     * notification is at at most once every
7688     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
7689     * to avoid unnecessary load to the system. Also once a view has a pending
7690     * notifucation this method is a NOP until the notification has been sent.
7691     *
7692     * @hide
7693     */
7694    public void notifySubtreeAccessibilityStateChangedIfNeeded() {
7695        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
7696            return;
7697        }
7698        if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) {
7699            mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
7700            if (mParent != null) {
7701                try {
7702                    mParent.notifySubtreeAccessibilityStateChanged(
7703                            this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
7704                } catch (AbstractMethodError e) {
7705                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
7706                            " does not fully implement ViewParent", e);
7707                }
7708            }
7709        }
7710    }
7711
7712    /**
7713     * Reset the flag indicating the accessibility state of the subtree rooted
7714     * at this view changed.
7715     */
7716    void resetSubtreeAccessibilityStateChanged() {
7717        mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
7718    }
7719
7720    /**
7721     * Performs the specified accessibility action on the view. For
7722     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
7723     * <p>
7724     * If an {@link AccessibilityDelegate} has been specified via calling
7725     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
7726     * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
7727     * is responsible for handling this call.
7728     * </p>
7729     *
7730     * @param action The action to perform.
7731     * @param arguments Optional action arguments.
7732     * @return Whether the action was performed.
7733     */
7734    public boolean performAccessibilityAction(int action, Bundle arguments) {
7735      if (mAccessibilityDelegate != null) {
7736          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
7737      } else {
7738          return performAccessibilityActionInternal(action, arguments);
7739      }
7740    }
7741
7742   /**
7743    * @see #performAccessibilityAction(int, Bundle)
7744    *
7745    * Note: Called from the default {@link AccessibilityDelegate}.
7746    */
7747    boolean performAccessibilityActionInternal(int action, Bundle arguments) {
7748        switch (action) {
7749            case AccessibilityNodeInfo.ACTION_CLICK: {
7750                if (isClickable()) {
7751                    performClick();
7752                    return true;
7753                }
7754            } break;
7755            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
7756                if (isLongClickable()) {
7757                    performLongClick();
7758                    return true;
7759                }
7760            } break;
7761            case AccessibilityNodeInfo.ACTION_FOCUS: {
7762                if (!hasFocus()) {
7763                    // Get out of touch mode since accessibility
7764                    // wants to move focus around.
7765                    getViewRootImpl().ensureTouchMode(false);
7766                    return requestFocus();
7767                }
7768            } break;
7769            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
7770                if (hasFocus()) {
7771                    clearFocus();
7772                    return !isFocused();
7773                }
7774            } break;
7775            case AccessibilityNodeInfo.ACTION_SELECT: {
7776                if (!isSelected()) {
7777                    setSelected(true);
7778                    return isSelected();
7779                }
7780            } break;
7781            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
7782                if (isSelected()) {
7783                    setSelected(false);
7784                    return !isSelected();
7785                }
7786            } break;
7787            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
7788                if (!isAccessibilityFocused()) {
7789                    return requestAccessibilityFocus();
7790                }
7791            } break;
7792            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
7793                if (isAccessibilityFocused()) {
7794                    clearAccessibilityFocus();
7795                    return true;
7796                }
7797            } break;
7798            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
7799                if (arguments != null) {
7800                    final int granularity = arguments.getInt(
7801                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
7802                    final boolean extendSelection = arguments.getBoolean(
7803                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
7804                    return traverseAtGranularity(granularity, true, extendSelection);
7805                }
7806            } break;
7807            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
7808                if (arguments != null) {
7809                    final int granularity = arguments.getInt(
7810                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
7811                    final boolean extendSelection = arguments.getBoolean(
7812                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
7813                    return traverseAtGranularity(granularity, false, extendSelection);
7814                }
7815            } break;
7816            case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
7817                CharSequence text = getIterableTextForAccessibility();
7818                if (text == null) {
7819                    return false;
7820                }
7821                final int start = (arguments != null) ? arguments.getInt(
7822                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1;
7823                final int end = (arguments != null) ? arguments.getInt(
7824                AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1;
7825                // Only cursor position can be specified (selection length == 0)
7826                if ((getAccessibilitySelectionStart() != start
7827                        || getAccessibilitySelectionEnd() != end)
7828                        && (start == end)) {
7829                    setAccessibilitySelection(start, end);
7830                    notifyViewAccessibilityStateChangedIfNeeded(
7831                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7832                    return true;
7833                }
7834            } break;
7835        }
7836        return false;
7837    }
7838
7839    private boolean traverseAtGranularity(int granularity, boolean forward,
7840            boolean extendSelection) {
7841        CharSequence text = getIterableTextForAccessibility();
7842        if (text == null || text.length() == 0) {
7843            return false;
7844        }
7845        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
7846        if (iterator == null) {
7847            return false;
7848        }
7849        int current = getAccessibilitySelectionEnd();
7850        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7851            current = forward ? 0 : text.length();
7852        }
7853        final int[] range = forward ? iterator.following(current) : iterator.preceding(current);
7854        if (range == null) {
7855            return false;
7856        }
7857        final int segmentStart = range[0];
7858        final int segmentEnd = range[1];
7859        int selectionStart;
7860        int selectionEnd;
7861        if (extendSelection && isAccessibilitySelectionExtendable()) {
7862            selectionStart = getAccessibilitySelectionStart();
7863            if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7864                selectionStart = forward ? segmentStart : segmentEnd;
7865            }
7866            selectionEnd = forward ? segmentEnd : segmentStart;
7867        } else {
7868            selectionStart = selectionEnd= forward ? segmentEnd : segmentStart;
7869        }
7870        setAccessibilitySelection(selectionStart, selectionEnd);
7871        final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY
7872                : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY;
7873        sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd);
7874        return true;
7875    }
7876
7877    /**
7878     * Gets the text reported for accessibility purposes.
7879     *
7880     * @return The accessibility text.
7881     *
7882     * @hide
7883     */
7884    public CharSequence getIterableTextForAccessibility() {
7885        return getContentDescription();
7886    }
7887
7888    /**
7889     * Gets whether accessibility selection can be extended.
7890     *
7891     * @return If selection is extensible.
7892     *
7893     * @hide
7894     */
7895    public boolean isAccessibilitySelectionExtendable() {
7896        return false;
7897    }
7898
7899    /**
7900     * @hide
7901     */
7902    public int getAccessibilitySelectionStart() {
7903        return mAccessibilityCursorPosition;
7904    }
7905
7906    /**
7907     * @hide
7908     */
7909    public int getAccessibilitySelectionEnd() {
7910        return getAccessibilitySelectionStart();
7911    }
7912
7913    /**
7914     * @hide
7915     */
7916    public void setAccessibilitySelection(int start, int end) {
7917        if (start ==  end && end == mAccessibilityCursorPosition) {
7918            return;
7919        }
7920        if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) {
7921            mAccessibilityCursorPosition = start;
7922        } else {
7923            mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
7924        }
7925        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
7926    }
7927
7928    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
7929            int fromIndex, int toIndex) {
7930        if (mParent == null) {
7931            return;
7932        }
7933        AccessibilityEvent event = AccessibilityEvent.obtain(
7934                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
7935        onInitializeAccessibilityEvent(event);
7936        onPopulateAccessibilityEvent(event);
7937        event.setFromIndex(fromIndex);
7938        event.setToIndex(toIndex);
7939        event.setAction(action);
7940        event.setMovementGranularity(granularity);
7941        mParent.requestSendAccessibilityEvent(this, event);
7942    }
7943
7944    /**
7945     * @hide
7946     */
7947    public TextSegmentIterator getIteratorForGranularity(int granularity) {
7948        switch (granularity) {
7949            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
7950                CharSequence text = getIterableTextForAccessibility();
7951                if (text != null && text.length() > 0) {
7952                    CharacterTextSegmentIterator iterator =
7953                        CharacterTextSegmentIterator.getInstance(
7954                                mContext.getResources().getConfiguration().locale);
7955                    iterator.initialize(text.toString());
7956                    return iterator;
7957                }
7958            } break;
7959            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
7960                CharSequence text = getIterableTextForAccessibility();
7961                if (text != null && text.length() > 0) {
7962                    WordTextSegmentIterator iterator =
7963                        WordTextSegmentIterator.getInstance(
7964                                mContext.getResources().getConfiguration().locale);
7965                    iterator.initialize(text.toString());
7966                    return iterator;
7967                }
7968            } break;
7969            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
7970                CharSequence text = getIterableTextForAccessibility();
7971                if (text != null && text.length() > 0) {
7972                    ParagraphTextSegmentIterator iterator =
7973                        ParagraphTextSegmentIterator.getInstance();
7974                    iterator.initialize(text.toString());
7975                    return iterator;
7976                }
7977            } break;
7978        }
7979        return null;
7980    }
7981
7982    /**
7983     * @hide
7984     */
7985    public void dispatchStartTemporaryDetach() {
7986        onStartTemporaryDetach();
7987    }
7988
7989    /**
7990     * This is called when a container is going to temporarily detach a child, with
7991     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
7992     * It will either be followed by {@link #onFinishTemporaryDetach()} or
7993     * {@link #onDetachedFromWindow()} when the container is done.
7994     */
7995    public void onStartTemporaryDetach() {
7996        removeUnsetPressCallback();
7997        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
7998    }
7999
8000    /**
8001     * @hide
8002     */
8003    public void dispatchFinishTemporaryDetach() {
8004        onFinishTemporaryDetach();
8005    }
8006
8007    /**
8008     * Called after {@link #onStartTemporaryDetach} when the container is done
8009     * changing the view.
8010     */
8011    public void onFinishTemporaryDetach() {
8012    }
8013
8014    /**
8015     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
8016     * for this view's window.  Returns null if the view is not currently attached
8017     * to the window.  Normally you will not need to use this directly, but
8018     * just use the standard high-level event callbacks like
8019     * {@link #onKeyDown(int, KeyEvent)}.
8020     */
8021    public KeyEvent.DispatcherState getKeyDispatcherState() {
8022        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
8023    }
8024
8025    /**
8026     * Dispatch a key event before it is processed by any input method
8027     * associated with the view hierarchy.  This can be used to intercept
8028     * key events in special situations before the IME consumes them; a
8029     * typical example would be handling the BACK key to update the application's
8030     * UI instead of allowing the IME to see it and close itself.
8031     *
8032     * @param event The key event to be dispatched.
8033     * @return True if the event was handled, false otherwise.
8034     */
8035    public boolean dispatchKeyEventPreIme(KeyEvent event) {
8036        return onKeyPreIme(event.getKeyCode(), event);
8037    }
8038
8039    /**
8040     * Dispatch a key event to the next view on the focus path. This path runs
8041     * from the top of the view tree down to the currently focused view. If this
8042     * view has focus, it will dispatch to itself. Otherwise it will dispatch
8043     * the next node down the focus path. This method also fires any key
8044     * listeners.
8045     *
8046     * @param event The key event to be dispatched.
8047     * @return True if the event was handled, false otherwise.
8048     */
8049    public boolean dispatchKeyEvent(KeyEvent event) {
8050        if (mInputEventConsistencyVerifier != null) {
8051            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
8052        }
8053
8054        // Give any attached key listener a first crack at the event.
8055        //noinspection SimplifiableIfStatement
8056        ListenerInfo li = mListenerInfo;
8057        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
8058                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
8059            return true;
8060        }
8061
8062        if (event.dispatch(this, mAttachInfo != null
8063                ? mAttachInfo.mKeyDispatchState : null, this)) {
8064            return true;
8065        }
8066
8067        if (mInputEventConsistencyVerifier != null) {
8068            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8069        }
8070        return false;
8071    }
8072
8073    /**
8074     * Dispatches a key shortcut event.
8075     *
8076     * @param event The key event to be dispatched.
8077     * @return True if the event was handled by the view, false otherwise.
8078     */
8079    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
8080        return onKeyShortcut(event.getKeyCode(), event);
8081    }
8082
8083    /**
8084     * Pass the touch screen motion event down to the target view, or this
8085     * view if it is the target.
8086     *
8087     * @param event The motion event to be dispatched.
8088     * @return True if the event was handled by the view, false otherwise.
8089     */
8090    public boolean dispatchTouchEvent(MotionEvent event) {
8091        if (mInputEventConsistencyVerifier != null) {
8092            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
8093        }
8094
8095        if (onFilterTouchEventForSecurity(event)) {
8096            //noinspection SimplifiableIfStatement
8097            ListenerInfo li = mListenerInfo;
8098            if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
8099                    && li.mOnTouchListener.onTouch(this, event)) {
8100                return true;
8101            }
8102
8103            if (onTouchEvent(event)) {
8104                return true;
8105            }
8106        }
8107
8108        if (mInputEventConsistencyVerifier != null) {
8109            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8110        }
8111        return false;
8112    }
8113
8114    /**
8115     * Filter the touch event to apply security policies.
8116     *
8117     * @param event The motion event to be filtered.
8118     * @return True if the event should be dispatched, false if the event should be dropped.
8119     *
8120     * @see #getFilterTouchesWhenObscured
8121     */
8122    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
8123        //noinspection RedundantIfStatement
8124        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
8125                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
8126            // Window is obscured, drop this touch.
8127            return false;
8128        }
8129        return true;
8130    }
8131
8132    /**
8133     * Pass a trackball motion event down to the focused view.
8134     *
8135     * @param event The motion event to be dispatched.
8136     * @return True if the event was handled by the view, false otherwise.
8137     */
8138    public boolean dispatchTrackballEvent(MotionEvent event) {
8139        if (mInputEventConsistencyVerifier != null) {
8140            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
8141        }
8142
8143        return onTrackballEvent(event);
8144    }
8145
8146    /**
8147     * Dispatch a generic motion event.
8148     * <p>
8149     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
8150     * are delivered to the view under the pointer.  All other generic motion events are
8151     * delivered to the focused view.  Hover events are handled specially and are delivered
8152     * to {@link #onHoverEvent(MotionEvent)}.
8153     * </p>
8154     *
8155     * @param event The motion event to be dispatched.
8156     * @return True if the event was handled by the view, false otherwise.
8157     */
8158    public boolean dispatchGenericMotionEvent(MotionEvent event) {
8159        if (mInputEventConsistencyVerifier != null) {
8160            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
8161        }
8162
8163        final int source = event.getSource();
8164        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
8165            final int action = event.getAction();
8166            if (action == MotionEvent.ACTION_HOVER_ENTER
8167                    || action == MotionEvent.ACTION_HOVER_MOVE
8168                    || action == MotionEvent.ACTION_HOVER_EXIT) {
8169                if (dispatchHoverEvent(event)) {
8170                    return true;
8171                }
8172            } else if (dispatchGenericPointerEvent(event)) {
8173                return true;
8174            }
8175        } else if (dispatchGenericFocusedEvent(event)) {
8176            return true;
8177        }
8178
8179        if (dispatchGenericMotionEventInternal(event)) {
8180            return true;
8181        }
8182
8183        if (mInputEventConsistencyVerifier != null) {
8184            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8185        }
8186        return false;
8187    }
8188
8189    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
8190        //noinspection SimplifiableIfStatement
8191        ListenerInfo li = mListenerInfo;
8192        if (li != null && li.mOnGenericMotionListener != null
8193                && (mViewFlags & ENABLED_MASK) == ENABLED
8194                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
8195            return true;
8196        }
8197
8198        if (onGenericMotionEvent(event)) {
8199            return true;
8200        }
8201
8202        if (mInputEventConsistencyVerifier != null) {
8203            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8204        }
8205        return false;
8206    }
8207
8208    /**
8209     * Dispatch a hover event.
8210     * <p>
8211     * Do not call this method directly.
8212     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8213     * </p>
8214     *
8215     * @param event The motion event to be dispatched.
8216     * @return True if the event was handled by the view, false otherwise.
8217     */
8218    protected boolean dispatchHoverEvent(MotionEvent event) {
8219        ListenerInfo li = mListenerInfo;
8220        //noinspection SimplifiableIfStatement
8221        if (li != null && li.mOnHoverListener != null
8222                && (mViewFlags & ENABLED_MASK) == ENABLED
8223                && li.mOnHoverListener.onHover(this, event)) {
8224            return true;
8225        }
8226
8227        return onHoverEvent(event);
8228    }
8229
8230    /**
8231     * Returns true if the view has a child to which it has recently sent
8232     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
8233     * it does not have a hovered child, then it must be the innermost hovered view.
8234     * @hide
8235     */
8236    protected boolean hasHoveredChild() {
8237        return false;
8238    }
8239
8240    /**
8241     * Dispatch a generic motion event to the view under the first pointer.
8242     * <p>
8243     * Do not call this method directly.
8244     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8245     * </p>
8246     *
8247     * @param event The motion event to be dispatched.
8248     * @return True if the event was handled by the view, false otherwise.
8249     */
8250    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
8251        return false;
8252    }
8253
8254    /**
8255     * Dispatch a generic motion event to the currently focused view.
8256     * <p>
8257     * Do not call this method directly.
8258     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8259     * </p>
8260     *
8261     * @param event The motion event to be dispatched.
8262     * @return True if the event was handled by the view, false otherwise.
8263     */
8264    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
8265        return false;
8266    }
8267
8268    /**
8269     * Dispatch a pointer event.
8270     * <p>
8271     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
8272     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
8273     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
8274     * and should not be expected to handle other pointing device features.
8275     * </p>
8276     *
8277     * @param event The motion event to be dispatched.
8278     * @return True if the event was handled by the view, false otherwise.
8279     * @hide
8280     */
8281    public final boolean dispatchPointerEvent(MotionEvent event) {
8282        if (event.isTouchEvent()) {
8283            return dispatchTouchEvent(event);
8284        } else {
8285            return dispatchGenericMotionEvent(event);
8286        }
8287    }
8288
8289    /**
8290     * Called when the window containing this view gains or loses window focus.
8291     * ViewGroups should override to route to their children.
8292     *
8293     * @param hasFocus True if the window containing this view now has focus,
8294     *        false otherwise.
8295     */
8296    public void dispatchWindowFocusChanged(boolean hasFocus) {
8297        onWindowFocusChanged(hasFocus);
8298    }
8299
8300    /**
8301     * Called when the window containing this view gains or loses focus.  Note
8302     * that this is separate from view focus: to receive key events, both
8303     * your view and its window must have focus.  If a window is displayed
8304     * on top of yours that takes input focus, then your own window will lose
8305     * focus but the view focus will remain unchanged.
8306     *
8307     * @param hasWindowFocus True if the window containing this view now has
8308     *        focus, false otherwise.
8309     */
8310    public void onWindowFocusChanged(boolean hasWindowFocus) {
8311        InputMethodManager imm = InputMethodManager.peekInstance();
8312        if (!hasWindowFocus) {
8313            if (isPressed()) {
8314                setPressed(false);
8315            }
8316            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
8317                imm.focusOut(this);
8318            }
8319            removeLongPressCallback();
8320            removeTapCallback();
8321            onFocusLost();
8322        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
8323            imm.focusIn(this);
8324        }
8325        refreshDrawableState();
8326    }
8327
8328    /**
8329     * Returns true if this view is in a window that currently has window focus.
8330     * Note that this is not the same as the view itself having focus.
8331     *
8332     * @return True if this view is in a window that currently has window focus.
8333     */
8334    public boolean hasWindowFocus() {
8335        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
8336    }
8337
8338    /**
8339     * Dispatch a view visibility change down the view hierarchy.
8340     * ViewGroups should override to route to their children.
8341     * @param changedView The view whose visibility changed. Could be 'this' or
8342     * an ancestor view.
8343     * @param visibility The new visibility of changedView: {@link #VISIBLE},
8344     * {@link #INVISIBLE} or {@link #GONE}.
8345     */
8346    protected void dispatchVisibilityChanged(@NonNull View changedView,
8347            @Visibility int visibility) {
8348        onVisibilityChanged(changedView, visibility);
8349    }
8350
8351    /**
8352     * Called when the visibility of the view or an ancestor of the view is changed.
8353     * @param changedView The view whose visibility changed. Could be 'this' or
8354     * an ancestor view.
8355     * @param visibility The new visibility of changedView: {@link #VISIBLE},
8356     * {@link #INVISIBLE} or {@link #GONE}.
8357     */
8358    protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) {
8359        if (visibility == VISIBLE) {
8360            if (mAttachInfo != null) {
8361                initialAwakenScrollBars();
8362            } else {
8363                mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
8364            }
8365        }
8366    }
8367
8368    /**
8369     * Dispatch a hint about whether this view is displayed. For instance, when
8370     * a View moves out of the screen, it might receives a display hint indicating
8371     * the view is not displayed. Applications should not <em>rely</em> on this hint
8372     * as there is no guarantee that they will receive one.
8373     *
8374     * @param hint A hint about whether or not this view is displayed:
8375     * {@link #VISIBLE} or {@link #INVISIBLE}.
8376     */
8377    public void dispatchDisplayHint(@Visibility int hint) {
8378        onDisplayHint(hint);
8379    }
8380
8381    /**
8382     * Gives this view a hint about whether is displayed or not. For instance, when
8383     * a View moves out of the screen, it might receives a display hint indicating
8384     * the view is not displayed. Applications should not <em>rely</em> on this hint
8385     * as there is no guarantee that they will receive one.
8386     *
8387     * @param hint A hint about whether or not this view is displayed:
8388     * {@link #VISIBLE} or {@link #INVISIBLE}.
8389     */
8390    protected void onDisplayHint(@Visibility int hint) {
8391    }
8392
8393    /**
8394     * Dispatch a window visibility change down the view hierarchy.
8395     * ViewGroups should override to route to their children.
8396     *
8397     * @param visibility The new visibility of the window.
8398     *
8399     * @see #onWindowVisibilityChanged(int)
8400     */
8401    public void dispatchWindowVisibilityChanged(@Visibility int visibility) {
8402        onWindowVisibilityChanged(visibility);
8403    }
8404
8405    /**
8406     * Called when the window containing has change its visibility
8407     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
8408     * that this tells you whether or not your window is being made visible
8409     * to the window manager; this does <em>not</em> tell you whether or not
8410     * your window is obscured by other windows on the screen, even if it
8411     * is itself visible.
8412     *
8413     * @param visibility The new visibility of the window.
8414     */
8415    protected void onWindowVisibilityChanged(@Visibility int visibility) {
8416        if (visibility == VISIBLE) {
8417            initialAwakenScrollBars();
8418        }
8419    }
8420
8421    /**
8422     * Returns the current visibility of the window this view is attached to
8423     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
8424     *
8425     * @return Returns the current visibility of the view's window.
8426     */
8427    @Visibility
8428    public int getWindowVisibility() {
8429        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
8430    }
8431
8432    /**
8433     * Retrieve the overall visible display size in which the window this view is
8434     * attached to has been positioned in.  This takes into account screen
8435     * decorations above the window, for both cases where the window itself
8436     * is being position inside of them or the window is being placed under
8437     * then and covered insets are used for the window to position its content
8438     * inside.  In effect, this tells you the available area where content can
8439     * be placed and remain visible to users.
8440     *
8441     * <p>This function requires an IPC back to the window manager to retrieve
8442     * the requested information, so should not be used in performance critical
8443     * code like drawing.
8444     *
8445     * @param outRect Filled in with the visible display frame.  If the view
8446     * is not attached to a window, this is simply the raw display size.
8447     */
8448    public void getWindowVisibleDisplayFrame(Rect outRect) {
8449        if (mAttachInfo != null) {
8450            try {
8451                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
8452            } catch (RemoteException e) {
8453                return;
8454            }
8455            // XXX This is really broken, and probably all needs to be done
8456            // in the window manager, and we need to know more about whether
8457            // we want the area behind or in front of the IME.
8458            final Rect insets = mAttachInfo.mVisibleInsets;
8459            outRect.left += insets.left;
8460            outRect.top += insets.top;
8461            outRect.right -= insets.right;
8462            outRect.bottom -= insets.bottom;
8463            return;
8464        }
8465        // The view is not attached to a display so we don't have a context.
8466        // Make a best guess about the display size.
8467        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
8468        d.getRectSize(outRect);
8469    }
8470
8471    /**
8472     * Dispatch a notification about a resource configuration change down
8473     * the view hierarchy.
8474     * ViewGroups should override to route to their children.
8475     *
8476     * @param newConfig The new resource configuration.
8477     *
8478     * @see #onConfigurationChanged(android.content.res.Configuration)
8479     */
8480    public void dispatchConfigurationChanged(Configuration newConfig) {
8481        onConfigurationChanged(newConfig);
8482    }
8483
8484    /**
8485     * Called when the current configuration of the resources being used
8486     * by the application have changed.  You can use this to decide when
8487     * to reload resources that can changed based on orientation and other
8488     * configuration characterstics.  You only need to use this if you are
8489     * not relying on the normal {@link android.app.Activity} mechanism of
8490     * recreating the activity instance upon a configuration change.
8491     *
8492     * @param newConfig The new resource configuration.
8493     */
8494    protected void onConfigurationChanged(Configuration newConfig) {
8495    }
8496
8497    /**
8498     * Private function to aggregate all per-view attributes in to the view
8499     * root.
8500     */
8501    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
8502        performCollectViewAttributes(attachInfo, visibility);
8503    }
8504
8505    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
8506        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
8507            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
8508                attachInfo.mKeepScreenOn = true;
8509            }
8510            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
8511            ListenerInfo li = mListenerInfo;
8512            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
8513                attachInfo.mHasSystemUiListeners = true;
8514            }
8515        }
8516    }
8517
8518    void needGlobalAttributesUpdate(boolean force) {
8519        final AttachInfo ai = mAttachInfo;
8520        if (ai != null && !ai.mRecomputeGlobalAttributes) {
8521            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
8522                    || ai.mHasSystemUiListeners) {
8523                ai.mRecomputeGlobalAttributes = true;
8524            }
8525        }
8526    }
8527
8528    /**
8529     * Returns whether the device is currently in touch mode.  Touch mode is entered
8530     * once the user begins interacting with the device by touch, and affects various
8531     * things like whether focus is always visible to the user.
8532     *
8533     * @return Whether the device is in touch mode.
8534     */
8535    @ViewDebug.ExportedProperty
8536    public boolean isInTouchMode() {
8537        if (mAttachInfo != null) {
8538            return mAttachInfo.mInTouchMode;
8539        } else {
8540            return ViewRootImpl.isInTouchMode();
8541        }
8542    }
8543
8544    /**
8545     * Returns the context the view is running in, through which it can
8546     * access the current theme, resources, etc.
8547     *
8548     * @return The view's Context.
8549     */
8550    @ViewDebug.CapturedViewProperty
8551    public final Context getContext() {
8552        return mContext;
8553    }
8554
8555    /**
8556     * Handle a key event before it is processed by any input method
8557     * associated with the view hierarchy.  This can be used to intercept
8558     * key events in special situations before the IME consumes them; a
8559     * typical example would be handling the BACK key to update the application's
8560     * UI instead of allowing the IME to see it and close itself.
8561     *
8562     * @param keyCode The value in event.getKeyCode().
8563     * @param event Description of the key event.
8564     * @return If you handled the event, return true. If you want to allow the
8565     *         event to be handled by the next receiver, return false.
8566     */
8567    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
8568        return false;
8569    }
8570
8571    /**
8572     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
8573     * KeyEvent.Callback.onKeyDown()}: perform press of the view
8574     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
8575     * is released, if the view is enabled and clickable.
8576     *
8577     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8578     * although some may elect to do so in some situations. Do not rely on this to
8579     * catch software key presses.
8580     *
8581     * @param keyCode A key code that represents the button pressed, from
8582     *                {@link android.view.KeyEvent}.
8583     * @param event   The KeyEvent object that defines the button action.
8584     */
8585    public boolean onKeyDown(int keyCode, KeyEvent event) {
8586        boolean result = false;
8587
8588        if (KeyEvent.isConfirmKey(keyCode)) {
8589            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
8590                return true;
8591            }
8592            // Long clickable items don't necessarily have to be clickable
8593            if (((mViewFlags & CLICKABLE) == CLICKABLE ||
8594                    (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
8595                    (event.getRepeatCount() == 0)) {
8596                setPressed(true);
8597                checkForLongClick(0);
8598                return true;
8599            }
8600        }
8601        return result;
8602    }
8603
8604    /**
8605     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
8606     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
8607     * the event).
8608     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8609     * although some may elect to do so in some situations. Do not rely on this to
8610     * catch software key presses.
8611     */
8612    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
8613        return false;
8614    }
8615
8616    /**
8617     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
8618     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
8619     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
8620     * {@link KeyEvent#KEYCODE_ENTER} is released.
8621     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8622     * although some may elect to do so in some situations. Do not rely on this to
8623     * catch software key presses.
8624     *
8625     * @param keyCode A key code that represents the button pressed, from
8626     *                {@link android.view.KeyEvent}.
8627     * @param event   The KeyEvent object that defines the button action.
8628     */
8629    public boolean onKeyUp(int keyCode, KeyEvent event) {
8630        if (KeyEvent.isConfirmKey(keyCode)) {
8631            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
8632                return true;
8633            }
8634            if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
8635                setPressed(false);
8636
8637                if (!mHasPerformedLongPress) {
8638                    // This is a tap, so remove the longpress check
8639                    removeLongPressCallback();
8640                    return performClick();
8641                }
8642            }
8643        }
8644        return false;
8645    }
8646
8647    /**
8648     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
8649     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
8650     * the event).
8651     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8652     * although some may elect to do so in some situations. Do not rely on this to
8653     * catch software key presses.
8654     *
8655     * @param keyCode     A key code that represents the button pressed, from
8656     *                    {@link android.view.KeyEvent}.
8657     * @param repeatCount The number of times the action was made.
8658     * @param event       The KeyEvent object that defines the button action.
8659     */
8660    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
8661        return false;
8662    }
8663
8664    /**
8665     * Called on the focused view when a key shortcut event is not handled.
8666     * Override this method to implement local key shortcuts for the View.
8667     * Key shortcuts can also be implemented by setting the
8668     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
8669     *
8670     * @param keyCode The value in event.getKeyCode().
8671     * @param event Description of the key event.
8672     * @return If you handled the event, return true. If you want to allow the
8673     *         event to be handled by the next receiver, return false.
8674     */
8675    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
8676        return false;
8677    }
8678
8679    /**
8680     * Check whether the called view is a text editor, in which case it
8681     * would make sense to automatically display a soft input window for
8682     * it.  Subclasses should override this if they implement
8683     * {@link #onCreateInputConnection(EditorInfo)} to return true if
8684     * a call on that method would return a non-null InputConnection, and
8685     * they are really a first-class editor that the user would normally
8686     * start typing on when the go into a window containing your view.
8687     *
8688     * <p>The default implementation always returns false.  This does
8689     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
8690     * will not be called or the user can not otherwise perform edits on your
8691     * view; it is just a hint to the system that this is not the primary
8692     * purpose of this view.
8693     *
8694     * @return Returns true if this view is a text editor, else false.
8695     */
8696    public boolean onCheckIsTextEditor() {
8697        return false;
8698    }
8699
8700    /**
8701     * Create a new InputConnection for an InputMethod to interact
8702     * with the view.  The default implementation returns null, since it doesn't
8703     * support input methods.  You can override this to implement such support.
8704     * This is only needed for views that take focus and text input.
8705     *
8706     * <p>When implementing this, you probably also want to implement
8707     * {@link #onCheckIsTextEditor()} to indicate you will return a
8708     * non-null InputConnection.
8709     *
8710     * @param outAttrs Fill in with attribute information about the connection.
8711     */
8712    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
8713        return null;
8714    }
8715
8716    /**
8717     * Called by the {@link android.view.inputmethod.InputMethodManager}
8718     * when a view who is not the current
8719     * input connection target is trying to make a call on the manager.  The
8720     * default implementation returns false; you can override this to return
8721     * true for certain views if you are performing InputConnection proxying
8722     * to them.
8723     * @param view The View that is making the InputMethodManager call.
8724     * @return Return true to allow the call, false to reject.
8725     */
8726    public boolean checkInputConnectionProxy(View view) {
8727        return false;
8728    }
8729
8730    /**
8731     * Show the context menu for this view. It is not safe to hold on to the
8732     * menu after returning from this method.
8733     *
8734     * You should normally not overload this method. Overload
8735     * {@link #onCreateContextMenu(ContextMenu)} or define an
8736     * {@link OnCreateContextMenuListener} to add items to the context menu.
8737     *
8738     * @param menu The context menu to populate
8739     */
8740    public void createContextMenu(ContextMenu menu) {
8741        ContextMenuInfo menuInfo = getContextMenuInfo();
8742
8743        // Sets the current menu info so all items added to menu will have
8744        // my extra info set.
8745        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
8746
8747        onCreateContextMenu(menu);
8748        ListenerInfo li = mListenerInfo;
8749        if (li != null && li.mOnCreateContextMenuListener != null) {
8750            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
8751        }
8752
8753        // Clear the extra information so subsequent items that aren't mine don't
8754        // have my extra info.
8755        ((MenuBuilder)menu).setCurrentMenuInfo(null);
8756
8757        if (mParent != null) {
8758            mParent.createContextMenu(menu);
8759        }
8760    }
8761
8762    /**
8763     * Views should implement this if they have extra information to associate
8764     * with the context menu. The return result is supplied as a parameter to
8765     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
8766     * callback.
8767     *
8768     * @return Extra information about the item for which the context menu
8769     *         should be shown. This information will vary across different
8770     *         subclasses of View.
8771     */
8772    protected ContextMenuInfo getContextMenuInfo() {
8773        return null;
8774    }
8775
8776    /**
8777     * Views should implement this if the view itself is going to add items to
8778     * the context menu.
8779     *
8780     * @param menu the context menu to populate
8781     */
8782    protected void onCreateContextMenu(ContextMenu menu) {
8783    }
8784
8785    /**
8786     * Implement this method to handle trackball motion events.  The
8787     * <em>relative</em> movement of the trackball since the last event
8788     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
8789     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
8790     * that a movement of 1 corresponds to the user pressing one DPAD key (so
8791     * they will often be fractional values, representing the more fine-grained
8792     * movement information available from a trackball).
8793     *
8794     * @param event The motion event.
8795     * @return True if the event was handled, false otherwise.
8796     */
8797    public boolean onTrackballEvent(MotionEvent event) {
8798        return false;
8799    }
8800
8801    /**
8802     * Implement this method to handle generic motion events.
8803     * <p>
8804     * Generic motion events describe joystick movements, mouse hovers, track pad
8805     * touches, scroll wheel movements and other input events.  The
8806     * {@link MotionEvent#getSource() source} of the motion event specifies
8807     * the class of input that was received.  Implementations of this method
8808     * must examine the bits in the source before processing the event.
8809     * The following code example shows how this is done.
8810     * </p><p>
8811     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
8812     * are delivered to the view under the pointer.  All other generic motion events are
8813     * delivered to the focused view.
8814     * </p>
8815     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
8816     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {
8817     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
8818     *             // process the joystick movement...
8819     *             return true;
8820     *         }
8821     *     }
8822     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
8823     *         switch (event.getAction()) {
8824     *             case MotionEvent.ACTION_HOVER_MOVE:
8825     *                 // process the mouse hover movement...
8826     *                 return true;
8827     *             case MotionEvent.ACTION_SCROLL:
8828     *                 // process the scroll wheel movement...
8829     *                 return true;
8830     *         }
8831     *     }
8832     *     return super.onGenericMotionEvent(event);
8833     * }</pre>
8834     *
8835     * @param event The generic motion event being processed.
8836     * @return True if the event was handled, false otherwise.
8837     */
8838    public boolean onGenericMotionEvent(MotionEvent event) {
8839        return false;
8840    }
8841
8842    /**
8843     * Implement this method to handle hover events.
8844     * <p>
8845     * This method is called whenever a pointer is hovering into, over, or out of the
8846     * bounds of a view and the view is not currently being touched.
8847     * Hover events are represented as pointer events with action
8848     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
8849     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
8850     * </p>
8851     * <ul>
8852     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
8853     * when the pointer enters the bounds of the view.</li>
8854     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
8855     * when the pointer has already entered the bounds of the view and has moved.</li>
8856     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
8857     * when the pointer has exited the bounds of the view or when the pointer is
8858     * about to go down due to a button click, tap, or similar user action that
8859     * causes the view to be touched.</li>
8860     * </ul>
8861     * <p>
8862     * The view should implement this method to return true to indicate that it is
8863     * handling the hover event, such as by changing its drawable state.
8864     * </p><p>
8865     * The default implementation calls {@link #setHovered} to update the hovered state
8866     * of the view when a hover enter or hover exit event is received, if the view
8867     * is enabled and is clickable.  The default implementation also sends hover
8868     * accessibility events.
8869     * </p>
8870     *
8871     * @param event The motion event that describes the hover.
8872     * @return True if the view handled the hover event.
8873     *
8874     * @see #isHovered
8875     * @see #setHovered
8876     * @see #onHoverChanged
8877     */
8878    public boolean onHoverEvent(MotionEvent event) {
8879        // The root view may receive hover (or touch) events that are outside the bounds of
8880        // the window.  This code ensures that we only send accessibility events for
8881        // hovers that are actually within the bounds of the root view.
8882        final int action = event.getActionMasked();
8883        if (!mSendingHoverAccessibilityEvents) {
8884            if ((action == MotionEvent.ACTION_HOVER_ENTER
8885                    || action == MotionEvent.ACTION_HOVER_MOVE)
8886                    && !hasHoveredChild()
8887                    && pointInView(event.getX(), event.getY())) {
8888                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
8889                mSendingHoverAccessibilityEvents = true;
8890            }
8891        } else {
8892            if (action == MotionEvent.ACTION_HOVER_EXIT
8893                    || (action == MotionEvent.ACTION_MOVE
8894                            && !pointInView(event.getX(), event.getY()))) {
8895                mSendingHoverAccessibilityEvents = false;
8896                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
8897                // If the window does not have input focus we take away accessibility
8898                // focus as soon as the user stop hovering over the view.
8899                if (mAttachInfo != null && !mAttachInfo.mHasWindowFocus) {
8900                    getViewRootImpl().setAccessibilityFocus(null, null);
8901                }
8902            }
8903        }
8904
8905        if (isHoverable()) {
8906            switch (action) {
8907                case MotionEvent.ACTION_HOVER_ENTER:
8908                    setHovered(true);
8909                    break;
8910                case MotionEvent.ACTION_HOVER_EXIT:
8911                    setHovered(false);
8912                    break;
8913            }
8914
8915            // Dispatch the event to onGenericMotionEvent before returning true.
8916            // This is to provide compatibility with existing applications that
8917            // handled HOVER_MOVE events in onGenericMotionEvent and that would
8918            // break because of the new default handling for hoverable views
8919            // in onHoverEvent.
8920            // Note that onGenericMotionEvent will be called by default when
8921            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
8922            dispatchGenericMotionEventInternal(event);
8923            // The event was already handled by calling setHovered(), so always
8924            // return true.
8925            return true;
8926        }
8927
8928        return false;
8929    }
8930
8931    /**
8932     * Returns true if the view should handle {@link #onHoverEvent}
8933     * by calling {@link #setHovered} to change its hovered state.
8934     *
8935     * @return True if the view is hoverable.
8936     */
8937    private boolean isHoverable() {
8938        final int viewFlags = mViewFlags;
8939        if ((viewFlags & ENABLED_MASK) == DISABLED) {
8940            return false;
8941        }
8942
8943        return (viewFlags & CLICKABLE) == CLICKABLE
8944                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
8945    }
8946
8947    /**
8948     * Returns true if the view is currently hovered.
8949     *
8950     * @return True if the view is currently hovered.
8951     *
8952     * @see #setHovered
8953     * @see #onHoverChanged
8954     */
8955    @ViewDebug.ExportedProperty
8956    public boolean isHovered() {
8957        return (mPrivateFlags & PFLAG_HOVERED) != 0;
8958    }
8959
8960    /**
8961     * Sets whether the view is currently hovered.
8962     * <p>
8963     * Calling this method also changes the drawable state of the view.  This
8964     * enables the view to react to hover by using different drawable resources
8965     * to change its appearance.
8966     * </p><p>
8967     * The {@link #onHoverChanged} method is called when the hovered state changes.
8968     * </p>
8969     *
8970     * @param hovered True if the view is hovered.
8971     *
8972     * @see #isHovered
8973     * @see #onHoverChanged
8974     */
8975    public void setHovered(boolean hovered) {
8976        if (hovered) {
8977            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
8978                mPrivateFlags |= PFLAG_HOVERED;
8979                refreshDrawableState();
8980                onHoverChanged(true);
8981            }
8982        } else {
8983            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
8984                mPrivateFlags &= ~PFLAG_HOVERED;
8985                refreshDrawableState();
8986                onHoverChanged(false);
8987            }
8988        }
8989    }
8990
8991    /**
8992     * Implement this method to handle hover state changes.
8993     * <p>
8994     * This method is called whenever the hover state changes as a result of a
8995     * call to {@link #setHovered}.
8996     * </p>
8997     *
8998     * @param hovered The current hover state, as returned by {@link #isHovered}.
8999     *
9000     * @see #isHovered
9001     * @see #setHovered
9002     */
9003    public void onHoverChanged(boolean hovered) {
9004    }
9005
9006    /**
9007     * Implement this method to handle touch screen motion events.
9008     * <p>
9009     * If this method is used to detect click actions, it is recommended that
9010     * the actions be performed by implementing and calling
9011     * {@link #performClick()}. This will ensure consistent system behavior,
9012     * including:
9013     * <ul>
9014     * <li>obeying click sound preferences
9015     * <li>dispatching OnClickListener calls
9016     * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when
9017     * accessibility features are enabled
9018     * </ul>
9019     *
9020     * @param event The motion event.
9021     * @return True if the event was handled, false otherwise.
9022     */
9023    public boolean onTouchEvent(MotionEvent event) {
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);
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                        removeTapCallback();
9093                    }
9094                    break;
9095
9096                case MotionEvent.ACTION_DOWN:
9097                    mHasPerformedLongPress = false;
9098
9099                    if (performButtonActionOnTouchDown(event)) {
9100                        break;
9101                    }
9102
9103                    // Walk up the hierarchy to determine if we're inside a scrolling container.
9104                    boolean isInScrollingContainer = isInScrollingContainer();
9105
9106                    // For views inside a scrolling container, delay the pressed feedback for
9107                    // a short period in case this is a scroll.
9108                    if (isInScrollingContainer) {
9109                        mPrivateFlags |= PFLAG_PREPRESSED;
9110                        if (mPendingCheckForTap == null) {
9111                            mPendingCheckForTap = new CheckForTap();
9112                        }
9113                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
9114                    } else {
9115                        // Not inside a scrolling container, so show the feedback right away
9116                        setPressed(true);
9117                        checkForLongClick(0);
9118                    }
9119                    break;
9120
9121                case MotionEvent.ACTION_CANCEL:
9122                    setPressed(false);
9123                    removeTapCallback();
9124                    removeLongPressCallback();
9125                    break;
9126
9127                case MotionEvent.ACTION_MOVE:
9128                    final int x = (int) event.getX();
9129                    final int y = (int) event.getY();
9130
9131                    // Be lenient about moving outside of buttons
9132                    if (!pointInView(x, y, mTouchSlop)) {
9133                        // Outside button
9134                        removeTapCallback();
9135                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
9136                            // Remove any future long press/tap checks
9137                            removeLongPressCallback();
9138
9139                            setPressed(false);
9140                        }
9141                    }
9142                    break;
9143            }
9144
9145            if (mBackground != null && mBackground.supportsHotspots()) {
9146                manageTouchHotspot(event);
9147            }
9148
9149            return true;
9150        }
9151
9152        return false;
9153    }
9154
9155    private void manageTouchHotspot(MotionEvent event) {
9156        switch (event.getAction()) {
9157            case MotionEvent.ACTION_DOWN:
9158            case MotionEvent.ACTION_POINTER_DOWN: {
9159                final int index = event.getActionIndex();
9160                setPointerHotspot(event, index);
9161            } break;
9162            case MotionEvent.ACTION_MOVE: {
9163                final int count = event.getPointerCount();
9164                for (int index = 0; index < count; index++) {
9165                    setPointerHotspot(event, index);
9166                }
9167            } break;
9168            case MotionEvent.ACTION_POINTER_UP: {
9169                final int actionIndex = event.getActionIndex();
9170                final int pointerId = event.getPointerId(actionIndex);
9171                mBackground.removeHotspot(pointerId);
9172            } break;
9173            case MotionEvent.ACTION_UP:
9174            case MotionEvent.ACTION_CANCEL:
9175                mBackground.clearHotspots();
9176                break;
9177        }
9178    }
9179
9180    private void setPointerHotspot(MotionEvent event, int index) {
9181        final int id = event.getPointerId(index);
9182        final float x = event.getX(index);
9183        final float y = event.getY(index);
9184        mBackground.setHotspot(id, x, y);
9185    }
9186
9187    /**
9188     * @hide
9189     */
9190    public boolean isInScrollingContainer() {
9191        ViewParent p = getParent();
9192        while (p != null && p instanceof ViewGroup) {
9193            if (((ViewGroup) p).shouldDelayChildPressedState()) {
9194                return true;
9195            }
9196            p = p.getParent();
9197        }
9198        return false;
9199    }
9200
9201    /**
9202     * Remove the longpress detection timer.
9203     */
9204    private void removeLongPressCallback() {
9205        if (mPendingCheckForLongPress != null) {
9206          removeCallbacks(mPendingCheckForLongPress);
9207        }
9208    }
9209
9210    /**
9211     * Remove the pending click action
9212     */
9213    private void removePerformClickCallback() {
9214        if (mPerformClick != null) {
9215            removeCallbacks(mPerformClick);
9216        }
9217    }
9218
9219    /**
9220     * Remove the prepress detection timer.
9221     */
9222    private void removeUnsetPressCallback() {
9223        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
9224            setPressed(false);
9225            removeCallbacks(mUnsetPressedState);
9226        }
9227    }
9228
9229    /**
9230     * Remove the tap detection timer.
9231     */
9232    private void removeTapCallback() {
9233        if (mPendingCheckForTap != null) {
9234            mPrivateFlags &= ~PFLAG_PREPRESSED;
9235            removeCallbacks(mPendingCheckForTap);
9236        }
9237    }
9238
9239    /**
9240     * Cancels a pending long press.  Your subclass can use this if you
9241     * want the context menu to come up if the user presses and holds
9242     * at the same place, but you don't want it to come up if they press
9243     * and then move around enough to cause scrolling.
9244     */
9245    public void cancelLongPress() {
9246        removeLongPressCallback();
9247
9248        /*
9249         * The prepressed state handled by the tap callback is a display
9250         * construct, but the tap callback will post a long press callback
9251         * less its own timeout. Remove it here.
9252         */
9253        removeTapCallback();
9254    }
9255
9256    /**
9257     * Remove the pending callback for sending a
9258     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
9259     */
9260    private void removeSendViewScrolledAccessibilityEventCallback() {
9261        if (mSendViewScrolledAccessibilityEvent != null) {
9262            removeCallbacks(mSendViewScrolledAccessibilityEvent);
9263            mSendViewScrolledAccessibilityEvent.mIsPending = false;
9264        }
9265    }
9266
9267    /**
9268     * Sets the TouchDelegate for this View.
9269     */
9270    public void setTouchDelegate(TouchDelegate delegate) {
9271        mTouchDelegate = delegate;
9272    }
9273
9274    /**
9275     * Gets the TouchDelegate for this View.
9276     */
9277    public TouchDelegate getTouchDelegate() {
9278        return mTouchDelegate;
9279    }
9280
9281    /**
9282     * Set flags controlling behavior of this view.
9283     *
9284     * @param flags Constant indicating the value which should be set
9285     * @param mask Constant indicating the bit range that should be changed
9286     */
9287    void setFlags(int flags, int mask) {
9288        final boolean accessibilityEnabled =
9289                AccessibilityManager.getInstance(mContext).isEnabled();
9290        final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility();
9291
9292        int old = mViewFlags;
9293        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
9294
9295        int changed = mViewFlags ^ old;
9296        if (changed == 0) {
9297            return;
9298        }
9299        int privateFlags = mPrivateFlags;
9300
9301        /* Check if the FOCUSABLE bit has changed */
9302        if (((changed & FOCUSABLE_MASK) != 0) &&
9303                ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) {
9304            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
9305                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
9306                /* Give up focus if we are no longer focusable */
9307                clearFocus();
9308            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
9309                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
9310                /*
9311                 * Tell the view system that we are now available to take focus
9312                 * if no one else already has it.
9313                 */
9314                if (mParent != null) mParent.focusableViewAvailable(this);
9315            }
9316        }
9317
9318        final int newVisibility = flags & VISIBILITY_MASK;
9319        if (newVisibility == VISIBLE) {
9320            if ((changed & VISIBILITY_MASK) != 0) {
9321                /*
9322                 * If this view is becoming visible, invalidate it in case it changed while
9323                 * it was not visible. Marking it drawn ensures that the invalidation will
9324                 * go through.
9325                 */
9326                mPrivateFlags |= PFLAG_DRAWN;
9327                invalidate(true);
9328
9329                needGlobalAttributesUpdate(true);
9330
9331                // a view becoming visible is worth notifying the parent
9332                // about in case nothing has focus.  even if this specific view
9333                // isn't focusable, it may contain something that is, so let
9334                // the root view try to give this focus if nothing else does.
9335                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
9336                    mParent.focusableViewAvailable(this);
9337                }
9338            }
9339        }
9340
9341        /* Check if the GONE bit has changed */
9342        if ((changed & GONE) != 0) {
9343            needGlobalAttributesUpdate(false);
9344            requestLayout();
9345
9346            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
9347                if (hasFocus()) clearFocus();
9348                clearAccessibilityFocus();
9349                destroyDrawingCache();
9350                if (mParent instanceof View) {
9351                    // GONE views noop invalidation, so invalidate the parent
9352                    ((View) mParent).invalidate(true);
9353                }
9354                // Mark the view drawn to ensure that it gets invalidated properly the next
9355                // time it is visible and gets invalidated
9356                mPrivateFlags |= PFLAG_DRAWN;
9357            }
9358            if (mAttachInfo != null) {
9359                mAttachInfo.mViewVisibilityChanged = true;
9360            }
9361        }
9362
9363        /* Check if the VISIBLE bit has changed */
9364        if ((changed & INVISIBLE) != 0) {
9365            needGlobalAttributesUpdate(false);
9366            /*
9367             * If this view is becoming invisible, set the DRAWN flag so that
9368             * the next invalidate() will not be skipped.
9369             */
9370            mPrivateFlags |= PFLAG_DRAWN;
9371
9372            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) {
9373                // root view becoming invisible shouldn't clear focus and accessibility focus
9374                if (getRootView() != this) {
9375                    if (hasFocus()) clearFocus();
9376                    clearAccessibilityFocus();
9377                }
9378            }
9379            if (mAttachInfo != null) {
9380                mAttachInfo.mViewVisibilityChanged = true;
9381            }
9382        }
9383
9384        if ((changed & VISIBILITY_MASK) != 0) {
9385            // If the view is invisible, cleanup its display list to free up resources
9386            if (newVisibility != VISIBLE && mAttachInfo != null) {
9387                cleanupDraw();
9388            }
9389
9390            if (mParent instanceof ViewGroup) {
9391                ((ViewGroup) mParent).onChildVisibilityChanged(this,
9392                        (changed & VISIBILITY_MASK), newVisibility);
9393                ((View) mParent).invalidate(true);
9394            } else if (mParent != null) {
9395                mParent.invalidateChild(this, null);
9396            }
9397            dispatchVisibilityChanged(this, newVisibility);
9398        }
9399
9400        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
9401            destroyDrawingCache();
9402        }
9403
9404        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
9405            destroyDrawingCache();
9406            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
9407            invalidateParentCaches();
9408        }
9409
9410        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
9411            destroyDrawingCache();
9412            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
9413        }
9414
9415        if ((changed & DRAW_MASK) != 0) {
9416            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
9417                if (mBackground != null) {
9418                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
9419                    mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
9420                } else {
9421                    mPrivateFlags |= PFLAG_SKIP_DRAW;
9422                }
9423            } else {
9424                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
9425            }
9426            requestLayout();
9427            invalidate(true);
9428        }
9429
9430        if ((changed & KEEP_SCREEN_ON) != 0) {
9431            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
9432                mParent.recomputeViewAttributes(this);
9433            }
9434        }
9435
9436        if (accessibilityEnabled) {
9437            if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0
9438                    || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0) {
9439                if (oldIncludeForAccessibility != includeForAccessibility()) {
9440                    notifySubtreeAccessibilityStateChangedIfNeeded();
9441                } else {
9442                    notifyViewAccessibilityStateChangedIfNeeded(
9443                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9444                }
9445            } else if ((changed & ENABLED_MASK) != 0) {
9446                notifyViewAccessibilityStateChangedIfNeeded(
9447                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9448            }
9449        }
9450    }
9451
9452    /**
9453     * Change the view's z order in the tree, so it's on top of other sibling
9454     * views. This ordering change may affect layout, if the parent container
9455     * uses an order-dependent layout scheme (e.g., LinearLayout). Prior
9456     * to {@link android.os.Build.VERSION_CODES#KITKAT} this
9457     * method should be followed by calls to {@link #requestLayout()} and
9458     * {@link View#invalidate()} on the view's parent to force the parent to redraw
9459     * with the new child ordering.
9460     *
9461     * @see ViewGroup#bringChildToFront(View)
9462     */
9463    public void bringToFront() {
9464        if (mParent != null) {
9465            mParent.bringChildToFront(this);
9466        }
9467    }
9468
9469    /**
9470     * This is called in response to an internal scroll in this view (i.e., the
9471     * view scrolled its own contents). This is typically as a result of
9472     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
9473     * called.
9474     *
9475     * @param l Current horizontal scroll origin.
9476     * @param t Current vertical scroll origin.
9477     * @param oldl Previous horizontal scroll origin.
9478     * @param oldt Previous vertical scroll origin.
9479     */
9480    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
9481        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
9482            postSendViewScrolledAccessibilityEventCallback();
9483        }
9484
9485        mBackgroundSizeChanged = true;
9486
9487        final AttachInfo ai = mAttachInfo;
9488        if (ai != null) {
9489            ai.mViewScrollChanged = true;
9490        }
9491    }
9492
9493    /**
9494     * Interface definition for a callback to be invoked when the layout bounds of a view
9495     * changes due to layout processing.
9496     */
9497    public interface OnLayoutChangeListener {
9498        /**
9499         * Called when the layout bounds of a view changes due to layout processing.
9500         *
9501         * @param v The view whose bounds have changed.
9502         * @param left The new value of the view's left property.
9503         * @param top The new value of the view's top property.
9504         * @param right The new value of the view's right property.
9505         * @param bottom The new value of the view's bottom property.
9506         * @param oldLeft The previous value of the view's left property.
9507         * @param oldTop The previous value of the view's top property.
9508         * @param oldRight The previous value of the view's right property.
9509         * @param oldBottom The previous value of the view's bottom property.
9510         */
9511        void onLayoutChange(View v, int left, int top, int right, int bottom,
9512            int oldLeft, int oldTop, int oldRight, int oldBottom);
9513    }
9514
9515    /**
9516     * This is called during layout when the size of this view has changed. If
9517     * you were just added to the view hierarchy, you're called with the old
9518     * values of 0.
9519     *
9520     * @param w Current width of this view.
9521     * @param h Current height of this view.
9522     * @param oldw Old width of this view.
9523     * @param oldh Old height of this view.
9524     */
9525    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
9526    }
9527
9528    /**
9529     * Called by draw to draw the child views. This may be overridden
9530     * by derived classes to gain control just before its children are drawn
9531     * (but after its own view has been drawn).
9532     * @param canvas the canvas on which to draw the view
9533     */
9534    protected void dispatchDraw(Canvas canvas) {
9535
9536    }
9537
9538    /**
9539     * Gets the parent of this view. Note that the parent is a
9540     * ViewParent and not necessarily a View.
9541     *
9542     * @return Parent of this view.
9543     */
9544    public final ViewParent getParent() {
9545        return mParent;
9546    }
9547
9548    /**
9549     * Set the horizontal scrolled position of your view. This will cause a call to
9550     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9551     * invalidated.
9552     * @param value the x position to scroll to
9553     */
9554    public void setScrollX(int value) {
9555        scrollTo(value, mScrollY);
9556    }
9557
9558    /**
9559     * Set the vertical scrolled position of your view. This will cause a call to
9560     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9561     * invalidated.
9562     * @param value the y position to scroll to
9563     */
9564    public void setScrollY(int value) {
9565        scrollTo(mScrollX, value);
9566    }
9567
9568    /**
9569     * Return the scrolled left position of this view. This is the left edge of
9570     * the displayed part of your view. You do not need to draw any pixels
9571     * farther left, since those are outside of the frame of your view on
9572     * screen.
9573     *
9574     * @return The left edge of the displayed part of your view, in pixels.
9575     */
9576    public final int getScrollX() {
9577        return mScrollX;
9578    }
9579
9580    /**
9581     * Return the scrolled top position of this view. This is the top edge of
9582     * the displayed part of your view. You do not need to draw any pixels above
9583     * it, since those are outside of the frame of your view on screen.
9584     *
9585     * @return The top edge of the displayed part of your view, in pixels.
9586     */
9587    public final int getScrollY() {
9588        return mScrollY;
9589    }
9590
9591    /**
9592     * Return the width of the your view.
9593     *
9594     * @return The width of your view, in pixels.
9595     */
9596    @ViewDebug.ExportedProperty(category = "layout")
9597    public final int getWidth() {
9598        return mRight - mLeft;
9599    }
9600
9601    /**
9602     * Return the height of your view.
9603     *
9604     * @return The height of your view, in pixels.
9605     */
9606    @ViewDebug.ExportedProperty(category = "layout")
9607    public final int getHeight() {
9608        return mBottom - mTop;
9609    }
9610
9611    /**
9612     * Return the visible drawing bounds of your view. Fills in the output
9613     * rectangle with the values from getScrollX(), getScrollY(),
9614     * getWidth(), and getHeight(). These bounds do not account for any
9615     * transformation properties currently set on the view, such as
9616     * {@link #setScaleX(float)} or {@link #setRotation(float)}.
9617     *
9618     * @param outRect The (scrolled) drawing bounds of the view.
9619     */
9620    public void getDrawingRect(Rect outRect) {
9621        outRect.left = mScrollX;
9622        outRect.top = mScrollY;
9623        outRect.right = mScrollX + (mRight - mLeft);
9624        outRect.bottom = mScrollY + (mBottom - mTop);
9625    }
9626
9627    /**
9628     * Like {@link #getMeasuredWidthAndState()}, but only returns the
9629     * raw width component (that is the result is masked by
9630     * {@link #MEASURED_SIZE_MASK}).
9631     *
9632     * @return The raw measured width of this view.
9633     */
9634    public final int getMeasuredWidth() {
9635        return mMeasuredWidth & MEASURED_SIZE_MASK;
9636    }
9637
9638    /**
9639     * Return the full width measurement information for this view as computed
9640     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
9641     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
9642     * This should be used during measurement and layout calculations only. Use
9643     * {@link #getWidth()} to see how wide a view is after layout.
9644     *
9645     * @return The measured width of this view as a bit mask.
9646     */
9647    public final int getMeasuredWidthAndState() {
9648        return mMeasuredWidth;
9649    }
9650
9651    /**
9652     * Like {@link #getMeasuredHeightAndState()}, but only returns the
9653     * raw width component (that is the result is masked by
9654     * {@link #MEASURED_SIZE_MASK}).
9655     *
9656     * @return The raw measured height of this view.
9657     */
9658    public final int getMeasuredHeight() {
9659        return mMeasuredHeight & MEASURED_SIZE_MASK;
9660    }
9661
9662    /**
9663     * Return the full height measurement information for this view as computed
9664     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
9665     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
9666     * This should be used during measurement and layout calculations only. Use
9667     * {@link #getHeight()} to see how wide a view is after layout.
9668     *
9669     * @return The measured width of this view as a bit mask.
9670     */
9671    public final int getMeasuredHeightAndState() {
9672        return mMeasuredHeight;
9673    }
9674
9675    /**
9676     * Return only the state bits of {@link #getMeasuredWidthAndState()}
9677     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
9678     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
9679     * and the height component is at the shifted bits
9680     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
9681     */
9682    public final int getMeasuredState() {
9683        return (mMeasuredWidth&MEASURED_STATE_MASK)
9684                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
9685                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
9686    }
9687
9688    /**
9689     * The transform matrix of this view, which is calculated based on the current
9690     * roation, scale, and pivot properties.
9691     *
9692     * @see #getRotation()
9693     * @see #getScaleX()
9694     * @see #getScaleY()
9695     * @see #getPivotX()
9696     * @see #getPivotY()
9697     * @return The current transform matrix for the view
9698     */
9699    public Matrix getMatrix() {
9700        if (mTransformationInfo != null) {
9701            updateMatrix();
9702            return mTransformationInfo.mMatrix;
9703        }
9704        return Matrix.IDENTITY_MATRIX;
9705    }
9706
9707    /**
9708     * Utility function to determine if the value is far enough away from zero to be
9709     * considered non-zero.
9710     * @param value A floating point value to check for zero-ness
9711     * @return whether the passed-in value is far enough away from zero to be considered non-zero
9712     */
9713    private static boolean nonzero(float value) {
9714        return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
9715    }
9716
9717    /**
9718     * Returns true if the transform matrix is the identity matrix.
9719     * Recomputes the matrix if necessary.
9720     *
9721     * @return True if the transform matrix is the identity matrix, false otherwise.
9722     */
9723    final boolean hasIdentityMatrix() {
9724        if (mTransformationInfo != null) {
9725            updateMatrix();
9726            return mTransformationInfo.mMatrixIsIdentity;
9727        }
9728        return true;
9729    }
9730
9731    void ensureTransformationInfo() {
9732        if (mTransformationInfo == null) {
9733            mTransformationInfo = new TransformationInfo();
9734        }
9735    }
9736
9737    /**
9738     * Recomputes the transform matrix if necessary.
9739     */
9740    private void updateMatrix() {
9741        final TransformationInfo info = mTransformationInfo;
9742        if (info == null) {
9743            return;
9744        }
9745        if (info.mMatrixDirty) {
9746            // transform-related properties have changed since the last time someone
9747            // asked for the matrix; recalculate it with the current values
9748
9749            // Figure out if we need to update the pivot point
9750            if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9751                if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) {
9752                    info.mPrevWidth = mRight - mLeft;
9753                    info.mPrevHeight = mBottom - mTop;
9754                    info.mPivotX = info.mPrevWidth / 2f;
9755                    info.mPivotY = info.mPrevHeight / 2f;
9756                }
9757            }
9758            info.mMatrix.reset();
9759            if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) {
9760                info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY);
9761                info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY);
9762                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
9763            } else {
9764                if (info.mCamera == null) {
9765                    info.mCamera = new Camera();
9766                    info.matrix3D = new Matrix();
9767                }
9768                info.mCamera.save();
9769                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
9770                info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation);
9771                info.mCamera.getMatrix(info.matrix3D);
9772                info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY);
9773                info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX,
9774                        info.mPivotY + info.mTranslationY);
9775                info.mMatrix.postConcat(info.matrix3D);
9776                info.mCamera.restore();
9777            }
9778            info.mMatrixDirty = false;
9779            info.mMatrixIsIdentity = info.mMatrix.isIdentity();
9780            info.mInverseMatrixDirty = true;
9781        }
9782    }
9783
9784   /**
9785     * Utility method to retrieve the inverse of the current mMatrix property.
9786     * We cache the matrix to avoid recalculating it when transform properties
9787     * have not changed.
9788     *
9789     * @return The inverse of the current matrix of this view.
9790     */
9791    final Matrix getInverseMatrix() {
9792        final TransformationInfo info = mTransformationInfo;
9793        if (info != null) {
9794            updateMatrix();
9795            if (info.mInverseMatrixDirty) {
9796                if (info.mInverseMatrix == null) {
9797                    info.mInverseMatrix = new Matrix();
9798                }
9799                info.mMatrix.invert(info.mInverseMatrix);
9800                info.mInverseMatrixDirty = false;
9801            }
9802            return info.mInverseMatrix;
9803        }
9804        return Matrix.IDENTITY_MATRIX;
9805    }
9806
9807    /**
9808     * Gets the distance along the Z axis from the camera to this view.
9809     *
9810     * @see #setCameraDistance(float)
9811     *
9812     * @return The distance along the Z axis.
9813     */
9814    public float getCameraDistance() {
9815        ensureTransformationInfo();
9816        final float dpi = mResources.getDisplayMetrics().densityDpi;
9817        final TransformationInfo info = mTransformationInfo;
9818        if (info.mCamera == null) {
9819            info.mCamera = new Camera();
9820            info.matrix3D = new Matrix();
9821        }
9822        return -(info.mCamera.getLocationZ() * dpi);
9823    }
9824
9825    /**
9826     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
9827     * views are drawn) from the camera to this view. The camera's distance
9828     * affects 3D transformations, for instance rotations around the X and Y
9829     * axis. If the rotationX or rotationY properties are changed and this view is
9830     * large (more than half the size of the screen), it is recommended to always
9831     * use a camera distance that's greater than the height (X axis rotation) or
9832     * the width (Y axis rotation) of this view.</p>
9833     *
9834     * <p>The distance of the camera from the view plane can have an affect on the
9835     * perspective distortion of the view when it is rotated around the x or y axis.
9836     * For example, a large distance will result in a large viewing angle, and there
9837     * will not be much perspective distortion of the view as it rotates. A short
9838     * distance may cause much more perspective distortion upon rotation, and can
9839     * also result in some drawing artifacts if the rotated view ends up partially
9840     * behind the camera (which is why the recommendation is to use a distance at
9841     * least as far as the size of the view, if the view is to be rotated.)</p>
9842     *
9843     * <p>The distance is expressed in "depth pixels." The default distance depends
9844     * on the screen density. For instance, on a medium density display, the
9845     * default distance is 1280. On a high density display, the default distance
9846     * is 1920.</p>
9847     *
9848     * <p>If you want to specify a distance that leads to visually consistent
9849     * results across various densities, use the following formula:</p>
9850     * <pre>
9851     * float scale = context.getResources().getDisplayMetrics().density;
9852     * view.setCameraDistance(distance * scale);
9853     * </pre>
9854     *
9855     * <p>The density scale factor of a high density display is 1.5,
9856     * and 1920 = 1280 * 1.5.</p>
9857     *
9858     * @param distance The distance in "depth pixels", if negative the opposite
9859     *        value is used
9860     *
9861     * @see #setRotationX(float)
9862     * @see #setRotationY(float)
9863     */
9864    public void setCameraDistance(float distance) {
9865        invalidateViewProperty(true, false);
9866
9867        ensureTransformationInfo();
9868        final float dpi = mResources.getDisplayMetrics().densityDpi;
9869        final TransformationInfo info = mTransformationInfo;
9870        if (info.mCamera == null) {
9871            info.mCamera = new Camera();
9872            info.matrix3D = new Matrix();
9873        }
9874
9875        info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi);
9876        info.mMatrixDirty = true;
9877
9878        invalidateViewProperty(false, false);
9879        if (mDisplayList != null) {
9880            mDisplayList.setCameraDistance(-Math.abs(distance) / dpi);
9881        }
9882        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9883            // View was rejected last time it was drawn by its parent; this may have changed
9884            invalidateParentIfNeeded();
9885        }
9886    }
9887
9888    /**
9889     * The degrees that the view is rotated around the pivot point.
9890     *
9891     * @see #setRotation(float)
9892     * @see #getPivotX()
9893     * @see #getPivotY()
9894     *
9895     * @return The degrees of rotation.
9896     */
9897    @ViewDebug.ExportedProperty(category = "drawing")
9898    public float getRotation() {
9899        return mTransformationInfo != null ? mTransformationInfo.mRotation : 0;
9900    }
9901
9902    /**
9903     * Sets the degrees that the view is rotated around the pivot point. Increasing values
9904     * result in clockwise rotation.
9905     *
9906     * @param rotation The degrees of rotation.
9907     *
9908     * @see #getRotation()
9909     * @see #getPivotX()
9910     * @see #getPivotY()
9911     * @see #setRotationX(float)
9912     * @see #setRotationY(float)
9913     *
9914     * @attr ref android.R.styleable#View_rotation
9915     */
9916    public void setRotation(float rotation) {
9917        ensureTransformationInfo();
9918        final TransformationInfo info = mTransformationInfo;
9919        if (info.mRotation != rotation) {
9920            // Double-invalidation is necessary to capture view's old and new areas
9921            invalidateViewProperty(true, false);
9922            info.mRotation = rotation;
9923            info.mMatrixDirty = true;
9924            invalidateViewProperty(false, true);
9925            if (mDisplayList != null) {
9926                mDisplayList.setRotation(rotation);
9927            }
9928            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9929                // View was rejected last time it was drawn by its parent; this may have changed
9930                invalidateParentIfNeeded();
9931            }
9932        }
9933    }
9934
9935    /**
9936     * The degrees that the view is rotated around the vertical axis through the pivot point.
9937     *
9938     * @see #getPivotX()
9939     * @see #getPivotY()
9940     * @see #setRotationY(float)
9941     *
9942     * @return The degrees of Y rotation.
9943     */
9944    @ViewDebug.ExportedProperty(category = "drawing")
9945    public float getRotationY() {
9946        return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0;
9947    }
9948
9949    /**
9950     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
9951     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
9952     * down the y axis.
9953     *
9954     * When rotating large views, it is recommended to adjust the camera distance
9955     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
9956     *
9957     * @param rotationY The degrees of Y rotation.
9958     *
9959     * @see #getRotationY()
9960     * @see #getPivotX()
9961     * @see #getPivotY()
9962     * @see #setRotation(float)
9963     * @see #setRotationX(float)
9964     * @see #setCameraDistance(float)
9965     *
9966     * @attr ref android.R.styleable#View_rotationY
9967     */
9968    public void setRotationY(float rotationY) {
9969        ensureTransformationInfo();
9970        final TransformationInfo info = mTransformationInfo;
9971        if (info.mRotationY != rotationY) {
9972            invalidateViewProperty(true, false);
9973            info.mRotationY = rotationY;
9974            info.mMatrixDirty = true;
9975            invalidateViewProperty(false, true);
9976            if (mDisplayList != null) {
9977                mDisplayList.setRotationY(rotationY);
9978            }
9979            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9980                // View was rejected last time it was drawn by its parent; this may have changed
9981                invalidateParentIfNeeded();
9982            }
9983        }
9984    }
9985
9986    /**
9987     * The degrees that the view is rotated around the horizontal axis through the pivot point.
9988     *
9989     * @see #getPivotX()
9990     * @see #getPivotY()
9991     * @see #setRotationX(float)
9992     *
9993     * @return The degrees of X rotation.
9994     */
9995    @ViewDebug.ExportedProperty(category = "drawing")
9996    public float getRotationX() {
9997        return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0;
9998    }
9999
10000    /**
10001     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
10002     * Increasing values result in clockwise rotation from the viewpoint of looking down the
10003     * x axis.
10004     *
10005     * When rotating large views, it is recommended to adjust the camera distance
10006     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
10007     *
10008     * @param rotationX The degrees of X rotation.
10009     *
10010     * @see #getRotationX()
10011     * @see #getPivotX()
10012     * @see #getPivotY()
10013     * @see #setRotation(float)
10014     * @see #setRotationY(float)
10015     * @see #setCameraDistance(float)
10016     *
10017     * @attr ref android.R.styleable#View_rotationX
10018     */
10019    public void setRotationX(float rotationX) {
10020        ensureTransformationInfo();
10021        final TransformationInfo info = mTransformationInfo;
10022        if (info.mRotationX != rotationX) {
10023            invalidateViewProperty(true, false);
10024            info.mRotationX = rotationX;
10025            info.mMatrixDirty = true;
10026            invalidateViewProperty(false, true);
10027            if (mDisplayList != null) {
10028                mDisplayList.setRotationX(rotationX);
10029            }
10030            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10031                // View was rejected last time it was drawn by its parent; this may have changed
10032                invalidateParentIfNeeded();
10033            }
10034        }
10035    }
10036
10037    /**
10038     * The amount that the view is scaled in x around the pivot point, as a proportion of
10039     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
10040     *
10041     * <p>By default, this is 1.0f.
10042     *
10043     * @see #getPivotX()
10044     * @see #getPivotY()
10045     * @return The scaling factor.
10046     */
10047    @ViewDebug.ExportedProperty(category = "drawing")
10048    public float getScaleX() {
10049        return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1;
10050    }
10051
10052    /**
10053     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
10054     * the view's unscaled width. A value of 1 means that no scaling is applied.
10055     *
10056     * @param scaleX The scaling factor.
10057     * @see #getPivotX()
10058     * @see #getPivotY()
10059     *
10060     * @attr ref android.R.styleable#View_scaleX
10061     */
10062    public void setScaleX(float scaleX) {
10063        ensureTransformationInfo();
10064        final TransformationInfo info = mTransformationInfo;
10065        if (info.mScaleX != scaleX) {
10066            invalidateViewProperty(true, false);
10067            info.mScaleX = scaleX;
10068            info.mMatrixDirty = true;
10069            invalidateViewProperty(false, true);
10070            if (mDisplayList != null) {
10071                mDisplayList.setScaleX(scaleX);
10072            }
10073            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10074                // View was rejected last time it was drawn by its parent; this may have changed
10075                invalidateParentIfNeeded();
10076            }
10077        }
10078    }
10079
10080    /**
10081     * The amount that the view is scaled in y around the pivot point, as a proportion of
10082     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
10083     *
10084     * <p>By default, this is 1.0f.
10085     *
10086     * @see #getPivotX()
10087     * @see #getPivotY()
10088     * @return The scaling factor.
10089     */
10090    @ViewDebug.ExportedProperty(category = "drawing")
10091    public float getScaleY() {
10092        return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1;
10093    }
10094
10095    /**
10096     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
10097     * the view's unscaled width. A value of 1 means that no scaling is applied.
10098     *
10099     * @param scaleY The scaling factor.
10100     * @see #getPivotX()
10101     * @see #getPivotY()
10102     *
10103     * @attr ref android.R.styleable#View_scaleY
10104     */
10105    public void setScaleY(float scaleY) {
10106        ensureTransformationInfo();
10107        final TransformationInfo info = mTransformationInfo;
10108        if (info.mScaleY != scaleY) {
10109            invalidateViewProperty(true, false);
10110            info.mScaleY = scaleY;
10111            info.mMatrixDirty = true;
10112            invalidateViewProperty(false, true);
10113            if (mDisplayList != null) {
10114                mDisplayList.setScaleY(scaleY);
10115            }
10116            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10117                // View was rejected last time it was drawn by its parent; this may have changed
10118                invalidateParentIfNeeded();
10119            }
10120        }
10121    }
10122
10123    /**
10124     * The x location of the point around which the view is {@link #setRotation(float) rotated}
10125     * and {@link #setScaleX(float) scaled}.
10126     *
10127     * @see #getRotation()
10128     * @see #getScaleX()
10129     * @see #getScaleY()
10130     * @see #getPivotY()
10131     * @return The x location of the pivot point.
10132     *
10133     * @attr ref android.R.styleable#View_transformPivotX
10134     */
10135    @ViewDebug.ExportedProperty(category = "drawing")
10136    public float getPivotX() {
10137        return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0;
10138    }
10139
10140    /**
10141     * Sets the x location of the point around which the view is
10142     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
10143     * By default, the pivot point is centered on the object.
10144     * Setting this property disables this behavior and causes the view to use only the
10145     * explicitly set pivotX and pivotY values.
10146     *
10147     * @param pivotX The x location of the pivot point.
10148     * @see #getRotation()
10149     * @see #getScaleX()
10150     * @see #getScaleY()
10151     * @see #getPivotY()
10152     *
10153     * @attr ref android.R.styleable#View_transformPivotX
10154     */
10155    public void setPivotX(float pivotX) {
10156        ensureTransformationInfo();
10157        final TransformationInfo info = mTransformationInfo;
10158        boolean pivotSet = (mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) ==
10159                PFLAG_PIVOT_EXPLICITLY_SET;
10160        if (info.mPivotX != pivotX || !pivotSet) {
10161            mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET;
10162            invalidateViewProperty(true, false);
10163            info.mPivotX = pivotX;
10164            info.mMatrixDirty = true;
10165            invalidateViewProperty(false, true);
10166            if (mDisplayList != null) {
10167                mDisplayList.setPivotX(pivotX);
10168            }
10169            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10170                // View was rejected last time it was drawn by its parent; this may have changed
10171                invalidateParentIfNeeded();
10172            }
10173        }
10174    }
10175
10176    /**
10177     * The y location of the point around which the view is {@link #setRotation(float) rotated}
10178     * and {@link #setScaleY(float) scaled}.
10179     *
10180     * @see #getRotation()
10181     * @see #getScaleX()
10182     * @see #getScaleY()
10183     * @see #getPivotY()
10184     * @return The y location of the pivot point.
10185     *
10186     * @attr ref android.R.styleable#View_transformPivotY
10187     */
10188    @ViewDebug.ExportedProperty(category = "drawing")
10189    public float getPivotY() {
10190        return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0;
10191    }
10192
10193    /**
10194     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
10195     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
10196     * Setting this property disables this behavior and causes the view to use only the
10197     * explicitly set pivotX and pivotY values.
10198     *
10199     * @param pivotY The y location of the pivot point.
10200     * @see #getRotation()
10201     * @see #getScaleX()
10202     * @see #getScaleY()
10203     * @see #getPivotY()
10204     *
10205     * @attr ref android.R.styleable#View_transformPivotY
10206     */
10207    public void setPivotY(float pivotY) {
10208        ensureTransformationInfo();
10209        final TransformationInfo info = mTransformationInfo;
10210        boolean pivotSet = (mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) ==
10211                PFLAG_PIVOT_EXPLICITLY_SET;
10212        if (info.mPivotY != pivotY || !pivotSet) {
10213            mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET;
10214            invalidateViewProperty(true, false);
10215            info.mPivotY = pivotY;
10216            info.mMatrixDirty = true;
10217            invalidateViewProperty(false, true);
10218            if (mDisplayList != null) {
10219                mDisplayList.setPivotY(pivotY);
10220            }
10221            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10222                // View was rejected last time it was drawn by its parent; this may have changed
10223                invalidateParentIfNeeded();
10224            }
10225        }
10226    }
10227
10228    /**
10229     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
10230     * completely transparent and 1 means the view is completely opaque.
10231     *
10232     * <p>By default this is 1.0f.
10233     * @return The opacity of the view.
10234     */
10235    @ViewDebug.ExportedProperty(category = "drawing")
10236    public float getAlpha() {
10237        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
10238    }
10239
10240    /**
10241     * Returns whether this View has content which overlaps.
10242     *
10243     * <p>This function, intended to be overridden by specific View types, is an optimization when
10244     * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to
10245     * an offscreen buffer and then composited into place, which can be expensive. If the view has
10246     * no overlapping rendering, the view can draw each primitive with the appropriate alpha value
10247     * directly. An example of overlapping rendering is a TextView with a background image, such as
10248     * a Button. An example of non-overlapping rendering is a TextView with no background, or an
10249     * ImageView with only the foreground image. The default implementation returns true; subclasses
10250     * should override if they have cases which can be optimized.</p>
10251     *
10252     * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas}
10253     * necessitates that a View return true if it uses the methods internally without passing the
10254     * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p>
10255     *
10256     * @return true if the content in this view might overlap, false otherwise.
10257     */
10258    public boolean hasOverlappingRendering() {
10259        return true;
10260    }
10261
10262    /**
10263     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
10264     * completely transparent and 1 means the view is completely opaque.</p>
10265     *
10266     * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant
10267     * performance implications, especially for large views. It is best to use the alpha property
10268     * sparingly and transiently, as in the case of fading animations.</p>
10269     *
10270     * <p>For a view with a frequently changing alpha, such as during a fading animation, it is
10271     * strongly recommended for performance reasons to either override
10272     * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a
10273     * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p>
10274     *
10275     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
10276     * responsible for applying the opacity itself.</p>
10277     *
10278     * <p>Note that if the view is backed by a
10279     * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a
10280     * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than
10281     * 1.0 will supercede the alpha of the layer paint.</p>
10282     *
10283     * @param alpha The opacity of the view.
10284     *
10285     * @see #hasOverlappingRendering()
10286     * @see #setLayerType(int, android.graphics.Paint)
10287     *
10288     * @attr ref android.R.styleable#View_alpha
10289     */
10290    public void setAlpha(float alpha) {
10291        ensureTransformationInfo();
10292        if (mTransformationInfo.mAlpha != alpha) {
10293            mTransformationInfo.mAlpha = alpha;
10294            if (onSetAlpha((int) (alpha * 255))) {
10295                mPrivateFlags |= PFLAG_ALPHA_SET;
10296                // subclass is handling alpha - don't optimize rendering cache invalidation
10297                invalidateParentCaches();
10298                invalidate(true);
10299            } else {
10300                mPrivateFlags &= ~PFLAG_ALPHA_SET;
10301                invalidateViewProperty(true, false);
10302                if (mDisplayList != null) {
10303                    mDisplayList.setAlpha(getFinalAlpha());
10304                }
10305            }
10306        }
10307    }
10308
10309    /**
10310     * Faster version of setAlpha() which performs the same steps except there are
10311     * no calls to invalidate(). The caller of this function should perform proper invalidation
10312     * on the parent and this object. The return value indicates whether the subclass handles
10313     * alpha (the return value for onSetAlpha()).
10314     *
10315     * @param alpha The new value for the alpha property
10316     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
10317     *         the new value for the alpha property is different from the old value
10318     */
10319    boolean setAlphaNoInvalidation(float alpha) {
10320        ensureTransformationInfo();
10321        if (mTransformationInfo.mAlpha != alpha) {
10322            mTransformationInfo.mAlpha = alpha;
10323            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
10324            if (subclassHandlesAlpha) {
10325                mPrivateFlags |= PFLAG_ALPHA_SET;
10326                return true;
10327            } else {
10328                mPrivateFlags &= ~PFLAG_ALPHA_SET;
10329                if (mDisplayList != null) {
10330                    mDisplayList.setAlpha(getFinalAlpha());
10331                }
10332            }
10333        }
10334        return false;
10335    }
10336
10337    /**
10338     * This property is hidden and intended only for use by the Fade transition, which
10339     * animates it to produce a visual translucency that does not side-effect (or get
10340     * affected by) the real alpha property. This value is composited with the other
10341     * alpha value (and the AlphaAnimation value, when that is present) to produce
10342     * a final visual translucency result, which is what is passed into the DisplayList.
10343     *
10344     * @hide
10345     */
10346    public void setTransitionAlpha(float alpha) {
10347        ensureTransformationInfo();
10348        if (mTransformationInfo.mTransitionAlpha != alpha) {
10349            mTransformationInfo.mTransitionAlpha = alpha;
10350            mPrivateFlags &= ~PFLAG_ALPHA_SET;
10351            invalidateViewProperty(true, false);
10352            if (mDisplayList != null) {
10353                mDisplayList.setAlpha(getFinalAlpha());
10354            }
10355        }
10356    }
10357
10358    /**
10359     * Calculates the visual alpha of this view, which is a combination of the actual
10360     * alpha value and the transitionAlpha value (if set).
10361     */
10362    private float getFinalAlpha() {
10363        if (mTransformationInfo != null) {
10364            return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha;
10365        }
10366        return 1;
10367    }
10368
10369    /**
10370     * This property is hidden and intended only for use by the Fade transition, which
10371     * animates it to produce a visual translucency that does not side-effect (or get
10372     * affected by) the real alpha property. This value is composited with the other
10373     * alpha value (and the AlphaAnimation value, when that is present) to produce
10374     * a final visual translucency result, which is what is passed into the DisplayList.
10375     *
10376     * @hide
10377     */
10378    public float getTransitionAlpha() {
10379        return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1;
10380    }
10381
10382    /**
10383     * Top position of this view relative to its parent.
10384     *
10385     * @return The top of this view, in pixels.
10386     */
10387    @ViewDebug.CapturedViewProperty
10388    public final int getTop() {
10389        return mTop;
10390    }
10391
10392    /**
10393     * Sets the top position of this view relative to its parent. This method is meant to be called
10394     * by the layout system and should not generally be called otherwise, because the property
10395     * may be changed at any time by the layout.
10396     *
10397     * @param top The top of this view, in pixels.
10398     */
10399    public final void setTop(int top) {
10400        if (top != mTop) {
10401            updateMatrix();
10402            final boolean matrixIsIdentity = mTransformationInfo == null
10403                    || mTransformationInfo.mMatrixIsIdentity;
10404            if (matrixIsIdentity) {
10405                if (mAttachInfo != null) {
10406                    int minTop;
10407                    int yLoc;
10408                    if (top < mTop) {
10409                        minTop = top;
10410                        yLoc = top - mTop;
10411                    } else {
10412                        minTop = mTop;
10413                        yLoc = 0;
10414                    }
10415                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
10416                }
10417            } else {
10418                // Double-invalidation is necessary to capture view's old and new areas
10419                invalidate(true);
10420            }
10421
10422            int width = mRight - mLeft;
10423            int oldHeight = mBottom - mTop;
10424
10425            mTop = top;
10426            if (mDisplayList != null) {
10427                mDisplayList.setTop(mTop);
10428            }
10429
10430            sizeChange(width, mBottom - mTop, width, oldHeight);
10431
10432            if (!matrixIsIdentity) {
10433                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
10434                    // A change in dimension means an auto-centered pivot point changes, too
10435                    mTransformationInfo.mMatrixDirty = true;
10436                }
10437                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10438                invalidate(true);
10439            }
10440            mBackgroundSizeChanged = true;
10441            invalidateParentIfNeeded();
10442            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10443                // View was rejected last time it was drawn by its parent; this may have changed
10444                invalidateParentIfNeeded();
10445            }
10446        }
10447    }
10448
10449    /**
10450     * Bottom position of this view relative to its parent.
10451     *
10452     * @return The bottom of this view, in pixels.
10453     */
10454    @ViewDebug.CapturedViewProperty
10455    public final int getBottom() {
10456        return mBottom;
10457    }
10458
10459    /**
10460     * True if this view has changed since the last time being drawn.
10461     *
10462     * @return The dirty state of this view.
10463     */
10464    public boolean isDirty() {
10465        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
10466    }
10467
10468    /**
10469     * Sets the bottom position of this view relative to its parent. This method is meant to be
10470     * called by the layout system and should not generally be called otherwise, because the
10471     * property may be changed at any time by the layout.
10472     *
10473     * @param bottom The bottom of this view, in pixels.
10474     */
10475    public final void setBottom(int bottom) {
10476        if (bottom != mBottom) {
10477            updateMatrix();
10478            final boolean matrixIsIdentity = mTransformationInfo == null
10479                    || mTransformationInfo.mMatrixIsIdentity;
10480            if (matrixIsIdentity) {
10481                if (mAttachInfo != null) {
10482                    int maxBottom;
10483                    if (bottom < mBottom) {
10484                        maxBottom = mBottom;
10485                    } else {
10486                        maxBottom = bottom;
10487                    }
10488                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
10489                }
10490            } else {
10491                // Double-invalidation is necessary to capture view's old and new areas
10492                invalidate(true);
10493            }
10494
10495            int width = mRight - mLeft;
10496            int oldHeight = mBottom - mTop;
10497
10498            mBottom = bottom;
10499            if (mDisplayList != null) {
10500                mDisplayList.setBottom(mBottom);
10501            }
10502
10503            sizeChange(width, mBottom - mTop, width, oldHeight);
10504
10505            if (!matrixIsIdentity) {
10506                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
10507                    // A change in dimension means an auto-centered pivot point changes, too
10508                    mTransformationInfo.mMatrixDirty = true;
10509                }
10510                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10511                invalidate(true);
10512            }
10513            mBackgroundSizeChanged = true;
10514            invalidateParentIfNeeded();
10515            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10516                // View was rejected last time it was drawn by its parent; this may have changed
10517                invalidateParentIfNeeded();
10518            }
10519        }
10520    }
10521
10522    /**
10523     * Left position of this view relative to its parent.
10524     *
10525     * @return The left edge of this view, in pixels.
10526     */
10527    @ViewDebug.CapturedViewProperty
10528    public final int getLeft() {
10529        return mLeft;
10530    }
10531
10532    /**
10533     * Sets the left position of this view relative to its parent. This method is meant to be called
10534     * by the layout system and should not generally be called otherwise, because the property
10535     * may be changed at any time by the layout.
10536     *
10537     * @param left The bottom of this view, in pixels.
10538     */
10539    public final void setLeft(int left) {
10540        if (left != mLeft) {
10541            updateMatrix();
10542            final boolean matrixIsIdentity = mTransformationInfo == null
10543                    || mTransformationInfo.mMatrixIsIdentity;
10544            if (matrixIsIdentity) {
10545                if (mAttachInfo != null) {
10546                    int minLeft;
10547                    int xLoc;
10548                    if (left < mLeft) {
10549                        minLeft = left;
10550                        xLoc = left - mLeft;
10551                    } else {
10552                        minLeft = mLeft;
10553                        xLoc = 0;
10554                    }
10555                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
10556                }
10557            } else {
10558                // Double-invalidation is necessary to capture view's old and new areas
10559                invalidate(true);
10560            }
10561
10562            int oldWidth = mRight - mLeft;
10563            int height = mBottom - mTop;
10564
10565            mLeft = left;
10566            if (mDisplayList != null) {
10567                mDisplayList.setLeft(left);
10568            }
10569
10570            sizeChange(mRight - mLeft, height, oldWidth, height);
10571
10572            if (!matrixIsIdentity) {
10573                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
10574                    // A change in dimension means an auto-centered pivot point changes, too
10575                    mTransformationInfo.mMatrixDirty = true;
10576                }
10577                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10578                invalidate(true);
10579            }
10580            mBackgroundSizeChanged = true;
10581            invalidateParentIfNeeded();
10582            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10583                // View was rejected last time it was drawn by its parent; this may have changed
10584                invalidateParentIfNeeded();
10585            }
10586        }
10587    }
10588
10589    /**
10590     * Right position of this view relative to its parent.
10591     *
10592     * @return The right edge of this view, in pixels.
10593     */
10594    @ViewDebug.CapturedViewProperty
10595    public final int getRight() {
10596        return mRight;
10597    }
10598
10599    /**
10600     * Sets the right position of this view relative to its parent. This method is meant to be called
10601     * by the layout system and should not generally be called otherwise, because the property
10602     * may be changed at any time by the layout.
10603     *
10604     * @param right The bottom of this view, in pixels.
10605     */
10606    public final void setRight(int right) {
10607        if (right != mRight) {
10608            updateMatrix();
10609            final boolean matrixIsIdentity = mTransformationInfo == null
10610                    || mTransformationInfo.mMatrixIsIdentity;
10611            if (matrixIsIdentity) {
10612                if (mAttachInfo != null) {
10613                    int maxRight;
10614                    if (right < mRight) {
10615                        maxRight = mRight;
10616                    } else {
10617                        maxRight = right;
10618                    }
10619                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
10620                }
10621            } else {
10622                // Double-invalidation is necessary to capture view's old and new areas
10623                invalidate(true);
10624            }
10625
10626            int oldWidth = mRight - mLeft;
10627            int height = mBottom - mTop;
10628
10629            mRight = right;
10630            if (mDisplayList != null) {
10631                mDisplayList.setRight(mRight);
10632            }
10633
10634            sizeChange(mRight - mLeft, height, oldWidth, height);
10635
10636            if (!matrixIsIdentity) {
10637                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
10638                    // A change in dimension means an auto-centered pivot point changes, too
10639                    mTransformationInfo.mMatrixDirty = true;
10640                }
10641                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10642                invalidate(true);
10643            }
10644            mBackgroundSizeChanged = true;
10645            invalidateParentIfNeeded();
10646            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10647                // View was rejected last time it was drawn by its parent; this may have changed
10648                invalidateParentIfNeeded();
10649            }
10650        }
10651    }
10652
10653    /**
10654     * The visual x position of this view, in pixels. This is equivalent to the
10655     * {@link #setTranslationX(float) translationX} property plus the current
10656     * {@link #getLeft() left} property.
10657     *
10658     * @return The visual x position of this view, in pixels.
10659     */
10660    @ViewDebug.ExportedProperty(category = "drawing")
10661    public float getX() {
10662        return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0);
10663    }
10664
10665    /**
10666     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
10667     * {@link #setTranslationX(float) translationX} property to be the difference between
10668     * the x value passed in and the current {@link #getLeft() left} property.
10669     *
10670     * @param x The visual x position of this view, in pixels.
10671     */
10672    public void setX(float x) {
10673        setTranslationX(x - mLeft);
10674    }
10675
10676    /**
10677     * The visual y position of this view, in pixels. This is equivalent to the
10678     * {@link #setTranslationY(float) translationY} property plus the current
10679     * {@link #getTop() top} property.
10680     *
10681     * @return The visual y position of this view, in pixels.
10682     */
10683    @ViewDebug.ExportedProperty(category = "drawing")
10684    public float getY() {
10685        return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0);
10686    }
10687
10688    /**
10689     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
10690     * {@link #setTranslationY(float) translationY} property to be the difference between
10691     * the y value passed in and the current {@link #getTop() top} property.
10692     *
10693     * @param y The visual y position of this view, in pixels.
10694     */
10695    public void setY(float y) {
10696        setTranslationY(y - mTop);
10697    }
10698
10699
10700    /**
10701     * The horizontal location of this view relative to its {@link #getLeft() left} position.
10702     * This position is post-layout, in addition to wherever the object's
10703     * layout placed it.
10704     *
10705     * @return The horizontal position of this view relative to its left position, in pixels.
10706     */
10707    @ViewDebug.ExportedProperty(category = "drawing")
10708    public float getTranslationX() {
10709        return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0;
10710    }
10711
10712    /**
10713     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
10714     * This effectively positions the object post-layout, in addition to wherever the object's
10715     * layout placed it.
10716     *
10717     * @param translationX The horizontal position of this view relative to its left position,
10718     * in pixels.
10719     *
10720     * @attr ref android.R.styleable#View_translationX
10721     */
10722    public void setTranslationX(float translationX) {
10723        ensureTransformationInfo();
10724        final TransformationInfo info = mTransformationInfo;
10725        if (info.mTranslationX != translationX) {
10726            // Double-invalidation is necessary to capture view's old and new areas
10727            invalidateViewProperty(true, false);
10728            info.mTranslationX = translationX;
10729            info.mMatrixDirty = true;
10730            invalidateViewProperty(false, true);
10731            if (mDisplayList != null) {
10732                mDisplayList.setTranslationX(translationX);
10733            }
10734            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10735                // View was rejected last time it was drawn by its parent; this may have changed
10736                invalidateParentIfNeeded();
10737            }
10738        }
10739    }
10740
10741    /**
10742     * The vertical location of this view relative to its {@link #getTop() top} position.
10743     * This position is post-layout, in addition to wherever the object's
10744     * layout placed it.
10745     *
10746     * @return The vertical position of this view relative to its top position,
10747     * in pixels.
10748     */
10749    @ViewDebug.ExportedProperty(category = "drawing")
10750    public float getTranslationY() {
10751        return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0;
10752    }
10753
10754    /**
10755     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
10756     * This effectively positions the object post-layout, in addition to wherever the object's
10757     * layout placed it.
10758     *
10759     * @param translationY The vertical position of this view relative to its top position,
10760     * in pixels.
10761     *
10762     * @attr ref android.R.styleable#View_translationY
10763     */
10764    public void setTranslationY(float translationY) {
10765        ensureTransformationInfo();
10766        final TransformationInfo info = mTransformationInfo;
10767        if (info.mTranslationY != translationY) {
10768            invalidateViewProperty(true, false);
10769            info.mTranslationY = translationY;
10770            info.mMatrixDirty = true;
10771            invalidateViewProperty(false, true);
10772            if (mDisplayList != null) {
10773                mDisplayList.setTranslationY(translationY);
10774            }
10775            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10776                // View was rejected last time it was drawn by its parent; this may have changed
10777                invalidateParentIfNeeded();
10778            }
10779        }
10780    }
10781
10782    /**
10783     * The depth location of this view relative to its parent.
10784     *
10785     * @return The depth of this view relative to its parent.
10786     */
10787    @ViewDebug.ExportedProperty(category = "drawing")
10788    public float getTranslationZ() {
10789        return mTransformationInfo != null ? mTransformationInfo.mTranslationZ : 0;
10790    }
10791
10792    /**
10793     * Sets the depth location of this view relative to its parent.
10794     *
10795     * @attr ref android.R.styleable#View_translationZ
10796     */
10797    public void setTranslationZ(float translationZ) {
10798        ensureTransformationInfo();
10799        final TransformationInfo info = mTransformationInfo;
10800        if (info.mTranslationZ != translationZ) {
10801            invalidateViewProperty(true, false);
10802            info.mTranslationZ = translationZ;
10803            info.mMatrixDirty = true;
10804            invalidateViewProperty(false, true);
10805            if (mDisplayList != null) {
10806                mDisplayList.setTranslationZ(translationZ);
10807            }
10808            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10809                // View was rejected last time it was drawn by its parent; this may have changed
10810                invalidateParentIfNeeded();
10811            }
10812        }
10813    }
10814
10815    /**
10816     * Copies the Outline of the View into the Path parameter.
10817     * <p>
10818     * If the outline is not set, the parameter Path is set to empty.
10819     *
10820     * @param outline Path into which View's outline will be copied. Must be non-null.
10821     *
10822     * @see #setOutline(Path)
10823     * @see #getClipToOutline()
10824     * @see #setClipToOutline(boolean)
10825     */
10826    public final void getOutline(@NonNull Path outline) {
10827        if (outline == null) {
10828            throw new IllegalArgumentException("Path must be non-null");
10829        }
10830        if (mOutline == null) {
10831            outline.reset();
10832        } else {
10833            outline.set(mOutline);
10834        }
10835    }
10836
10837    /**
10838     * Sets the outline of the view, which defines the shape of the shadow it
10839     * casts, and can used for clipping.
10840     * <p>
10841     * The outline path of a View must be {@link android.graphics.Path#isConvex() convex}.
10842     * <p>
10843     * If the outline is not set, or {@link Path#isEmpty()}, shadows will be
10844     * cast from the bounds of the View, and clipToOutline will be ignored.
10845     *
10846     * @param outline The new outline of the view. Must be non-null, and convex.
10847     *
10848     * @see #setCastsShadow(boolean)
10849     * @see #getOutline(Path)
10850     * @see #getClipToOutline()
10851     * @see #setClipToOutline(boolean)
10852     */
10853    public void setOutline(@NonNull Path outline) {
10854        if (outline == null) {
10855            throw new IllegalArgumentException("Path must be non-null");
10856        }
10857        if (!outline.isConvex()) {
10858            throw new IllegalArgumentException("Path must be convex");
10859        }
10860        // always copy the path since caller may reuse
10861        if (mOutline == null) {
10862            mOutline = new Path(outline);
10863        } else {
10864            mOutline.set(outline);
10865        }
10866
10867        if (mDisplayList != null) {
10868            mDisplayList.setOutline(outline);
10869        }
10870    }
10871
10872    /**
10873     * Returns whether the outline of the View will be used for clipping.
10874     *
10875     * @see #getOutline(Path)
10876     * @see #setOutline(Path)
10877     */
10878    public final boolean getClipToOutline() {
10879        return ((mPrivateFlags3 & PFLAG3_CLIP_TO_OUTLINE) != 0);
10880    }
10881
10882    /**
10883     * Sets whether the outline of the View will be used for clipping.
10884     * <p>
10885     * The current implementation of outline clipping uses Canvas#clipPath(),
10886     * and thus does not support anti-aliasing, and is expensive in terms of
10887     * graphics performance. Therefore, it is strongly recommended that this
10888     * property only be set temporarily, as in an animation. For the same
10889     * reasons, there is no parallel XML attribute for this property.
10890     * <p>
10891     * If the outline of the view is not set or is empty, no clipping will be
10892     * performed.
10893     *
10894     * @see #getOutline(Path)
10895     * @see #setOutline(Path)
10896     */
10897    public void setClipToOutline(boolean clipToOutline) {
10898        // TODO : Add a fast invalidation here.
10899        if (getClipToOutline() != clipToOutline) {
10900            if (clipToOutline) {
10901                mPrivateFlags3 |= PFLAG3_CLIP_TO_OUTLINE;
10902            } else {
10903                mPrivateFlags3 &= ~PFLAG3_CLIP_TO_OUTLINE;
10904            }
10905            if (mDisplayList != null) {
10906                mDisplayList.setClipToOutline(clipToOutline);
10907            }
10908        }
10909    }
10910
10911    /**
10912     * Returns whether the View will cast shadows when its
10913     * {@link #setTranslationZ(float) z translation} is greater than 0, or it is
10914     * rotated in 3D.
10915     *
10916     * @see #setTranslationZ(float)
10917     * @see #setRotationX(float)
10918     * @see #setRotationY(float)
10919     * @see #setCastsShadow(boolean)
10920     * @attr ref android.R.styleable#View_castsShadow
10921     */
10922    public final boolean getCastsShadow() {
10923        return ((mPrivateFlags3 & PFLAG3_CASTS_SHADOW) != 0);
10924    }
10925
10926    /**
10927     * Set to true to enable this View to cast shadows.
10928     * <p>
10929     * If enabled, and the View has a z translation greater than 0, or is
10930     * rotated in 3D, the shadow will be cast onto the current
10931     * {@link ViewGroup#setIsolatedZVolume(boolean) isolated Z volume},
10932     * at the z = 0 plane.
10933     * <p>
10934     * The shape of the shadow being cast is defined by the
10935     * {@link #setOutline(Path) outline} of the view, or the rectangular bounds
10936     * of the view if the outline is not set or is empty.
10937     *
10938     * @see #setTranslationZ(float)
10939     * @see #getCastsShadow()
10940     * @attr ref android.R.styleable#View_castsShadow
10941     */
10942    public void setCastsShadow(boolean castsShadow) {
10943        // TODO : Add a fast invalidation here.
10944        if (getCastsShadow() != castsShadow) {
10945            if (castsShadow) {
10946                mPrivateFlags3 |= PFLAG3_CASTS_SHADOW;
10947            } else {
10948                mPrivateFlags3 &= ~PFLAG3_CASTS_SHADOW;
10949            }
10950            if (mDisplayList != null) {
10951                mDisplayList.setCastsShadow(castsShadow);
10952            }
10953        }
10954    }
10955
10956    /**
10957     * Returns whether the View will be transformed by the global camera.
10958     *
10959     * @see #setUsesGlobalCamera(boolean)
10960     *
10961     * @hide
10962     */
10963    public final boolean getUsesGlobalCamera() {
10964        return ((mPrivateFlags3 & PFLAG3_USES_GLOBAL_CAMERA) != 0);
10965    }
10966
10967    /**
10968     * Sets whether the View should be transformed by the global camera.
10969     * <p>
10970     * If the view has a Z translation or 3D rotation, perspective from the
10971     * global camera will be applied. This enables an app to transform multiple
10972     * views in 3D with coherent perspective projection among them all.
10973     * <p>
10974     * Setting this to true will cause {@link #setCameraDistance() camera distance}
10975     * to be ignored, as the global camera's position will dictate perspective
10976     * transform.
10977     * <p>
10978     * This should not be used in conjunction with {@link android.graphics.Camera}.
10979     *
10980     * @see #getUsesGlobalCamera()
10981     * @see #setTranslationZ(float)
10982     * @see #setRotationX(float)
10983     * @see #setRotationY(float)
10984     *
10985     * @hide
10986     */
10987    public void setUsesGlobalCamera(boolean usesGlobalCamera) {
10988        // TODO : Add a fast invalidation here.
10989        if (getUsesGlobalCamera() != usesGlobalCamera) {
10990            if (usesGlobalCamera) {
10991                mPrivateFlags3 |= PFLAG3_USES_GLOBAL_CAMERA;
10992            } else {
10993                mPrivateFlags3 &= ~PFLAG3_USES_GLOBAL_CAMERA;
10994            }
10995            if (mDisplayList != null) {
10996                mDisplayList.setUsesGlobalCamera(usesGlobalCamera);
10997            }
10998        }
10999    }
11000
11001    /**
11002     * Hit rectangle in parent's coordinates
11003     *
11004     * @param outRect The hit rectangle of the view.
11005     */
11006    public void getHitRect(Rect outRect) {
11007        updateMatrix();
11008        final TransformationInfo info = mTransformationInfo;
11009        if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) {
11010            outRect.set(mLeft, mTop, mRight, mBottom);
11011        } else {
11012            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
11013            tmpRect.set(0, 0, getWidth(), getHeight());
11014            info.mMatrix.mapRect(tmpRect);
11015            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
11016                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
11017        }
11018    }
11019
11020    /**
11021     * Determines whether the given point, in local coordinates is inside the view.
11022     */
11023    /*package*/ final boolean pointInView(float localX, float localY) {
11024        return localX >= 0 && localX < (mRight - mLeft)
11025                && localY >= 0 && localY < (mBottom - mTop);
11026    }
11027
11028    /**
11029     * Utility method to determine whether the given point, in local coordinates,
11030     * is inside the view, where the area of the view is expanded by the slop factor.
11031     * This method is called while processing touch-move events to determine if the event
11032     * is still within the view.
11033     *
11034     * @hide
11035     */
11036    public boolean pointInView(float localX, float localY, float slop) {
11037        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
11038                localY < ((mBottom - mTop) + slop);
11039    }
11040
11041    /**
11042     * When a view has focus and the user navigates away from it, the next view is searched for
11043     * starting from the rectangle filled in by this method.
11044     *
11045     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
11046     * of the view.  However, if your view maintains some idea of internal selection,
11047     * such as a cursor, or a selected row or column, you should override this method and
11048     * fill in a more specific rectangle.
11049     *
11050     * @param r The rectangle to fill in, in this view's coordinates.
11051     */
11052    public void getFocusedRect(Rect r) {
11053        getDrawingRect(r);
11054    }
11055
11056    /**
11057     * If some part of this view is not clipped by any of its parents, then
11058     * return that area in r in global (root) coordinates. To convert r to local
11059     * coordinates (without taking possible View rotations into account), offset
11060     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
11061     * If the view is completely clipped or translated out, return false.
11062     *
11063     * @param r If true is returned, r holds the global coordinates of the
11064     *        visible portion of this view.
11065     * @param globalOffset If true is returned, globalOffset holds the dx,dy
11066     *        between this view and its root. globalOffet may be null.
11067     * @return true if r is non-empty (i.e. part of the view is visible at the
11068     *         root level.
11069     */
11070    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
11071        int width = mRight - mLeft;
11072        int height = mBottom - mTop;
11073        if (width > 0 && height > 0) {
11074            r.set(0, 0, width, height);
11075            if (globalOffset != null) {
11076                globalOffset.set(-mScrollX, -mScrollY);
11077            }
11078            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
11079        }
11080        return false;
11081    }
11082
11083    public final boolean getGlobalVisibleRect(Rect r) {
11084        return getGlobalVisibleRect(r, null);
11085    }
11086
11087    public final boolean getLocalVisibleRect(Rect r) {
11088        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
11089        if (getGlobalVisibleRect(r, offset)) {
11090            r.offset(-offset.x, -offset.y); // make r local
11091            return true;
11092        }
11093        return false;
11094    }
11095
11096    /**
11097     * Offset this view's vertical location by the specified number of pixels.
11098     *
11099     * @param offset the number of pixels to offset the view by
11100     */
11101    public void offsetTopAndBottom(int offset) {
11102        if (offset != 0) {
11103            updateMatrix();
11104            final boolean matrixIsIdentity = mTransformationInfo == null
11105                    || mTransformationInfo.mMatrixIsIdentity;
11106            if (matrixIsIdentity) {
11107                if (mDisplayList != null) {
11108                    invalidateViewProperty(false, false);
11109                } else {
11110                    final ViewParent p = mParent;
11111                    if (p != null && mAttachInfo != null) {
11112                        final Rect r = mAttachInfo.mTmpInvalRect;
11113                        int minTop;
11114                        int maxBottom;
11115                        int yLoc;
11116                        if (offset < 0) {
11117                            minTop = mTop + offset;
11118                            maxBottom = mBottom;
11119                            yLoc = offset;
11120                        } else {
11121                            minTop = mTop;
11122                            maxBottom = mBottom + offset;
11123                            yLoc = 0;
11124                        }
11125                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
11126                        p.invalidateChild(this, r);
11127                    }
11128                }
11129            } else {
11130                invalidateViewProperty(false, false);
11131            }
11132
11133            mTop += offset;
11134            mBottom += offset;
11135            if (mDisplayList != null) {
11136                mDisplayList.offsetTopAndBottom(offset);
11137                invalidateViewProperty(false, false);
11138            } else {
11139                if (!matrixIsIdentity) {
11140                    invalidateViewProperty(false, true);
11141                }
11142                invalidateParentIfNeeded();
11143            }
11144        }
11145    }
11146
11147    /**
11148     * Offset this view's horizontal location by the specified amount of pixels.
11149     *
11150     * @param offset the number of pixels to offset the view by
11151     */
11152    public void offsetLeftAndRight(int offset) {
11153        if (offset != 0) {
11154            updateMatrix();
11155            final boolean matrixIsIdentity = mTransformationInfo == null
11156                    || mTransformationInfo.mMatrixIsIdentity;
11157            if (matrixIsIdentity) {
11158                if (mDisplayList != null) {
11159                    invalidateViewProperty(false, false);
11160                } else {
11161                    final ViewParent p = mParent;
11162                    if (p != null && mAttachInfo != null) {
11163                        final Rect r = mAttachInfo.mTmpInvalRect;
11164                        int minLeft;
11165                        int maxRight;
11166                        if (offset < 0) {
11167                            minLeft = mLeft + offset;
11168                            maxRight = mRight;
11169                        } else {
11170                            minLeft = mLeft;
11171                            maxRight = mRight + offset;
11172                        }
11173                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
11174                        p.invalidateChild(this, r);
11175                    }
11176                }
11177            } else {
11178                invalidateViewProperty(false, false);
11179            }
11180
11181            mLeft += offset;
11182            mRight += offset;
11183            if (mDisplayList != null) {
11184                mDisplayList.offsetLeftAndRight(offset);
11185                invalidateViewProperty(false, false);
11186            } else {
11187                if (!matrixIsIdentity) {
11188                    invalidateViewProperty(false, true);
11189                }
11190                invalidateParentIfNeeded();
11191            }
11192        }
11193    }
11194
11195    /**
11196     * Get the LayoutParams associated with this view. All views should have
11197     * layout parameters. These supply parameters to the <i>parent</i> of this
11198     * view specifying how it should be arranged. There are many subclasses of
11199     * ViewGroup.LayoutParams, and these correspond to the different subclasses
11200     * of ViewGroup that are responsible for arranging their children.
11201     *
11202     * This method may return null if this View is not attached to a parent
11203     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
11204     * was not invoked successfully. When a View is attached to a parent
11205     * ViewGroup, this method must not return null.
11206     *
11207     * @return The LayoutParams associated with this view, or null if no
11208     *         parameters have been set yet
11209     */
11210    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
11211    public ViewGroup.LayoutParams getLayoutParams() {
11212        return mLayoutParams;
11213    }
11214
11215    /**
11216     * Set the layout parameters associated with this view. These supply
11217     * parameters to the <i>parent</i> of this view specifying how it should be
11218     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
11219     * correspond to the different subclasses of ViewGroup that are responsible
11220     * for arranging their children.
11221     *
11222     * @param params The layout parameters for this view, cannot be null
11223     */
11224    public void setLayoutParams(ViewGroup.LayoutParams params) {
11225        if (params == null) {
11226            throw new NullPointerException("Layout parameters cannot be null");
11227        }
11228        mLayoutParams = params;
11229        resolveLayoutParams();
11230        if (mParent instanceof ViewGroup) {
11231            ((ViewGroup) mParent).onSetLayoutParams(this, params);
11232        }
11233        requestLayout();
11234    }
11235
11236    /**
11237     * Resolve the layout parameters depending on the resolved layout direction
11238     *
11239     * @hide
11240     */
11241    public void resolveLayoutParams() {
11242        if (mLayoutParams != null) {
11243            mLayoutParams.resolveLayoutDirection(getLayoutDirection());
11244        }
11245    }
11246
11247    /**
11248     * Set the scrolled position of your view. This will cause a call to
11249     * {@link #onScrollChanged(int, int, int, int)} and the view will be
11250     * invalidated.
11251     * @param x the x position to scroll to
11252     * @param y the y position to scroll to
11253     */
11254    public void scrollTo(int x, int y) {
11255        if (mScrollX != x || mScrollY != y) {
11256            int oldX = mScrollX;
11257            int oldY = mScrollY;
11258            mScrollX = x;
11259            mScrollY = y;
11260            invalidateParentCaches();
11261            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
11262            if (!awakenScrollBars()) {
11263                postInvalidateOnAnimation();
11264            }
11265        }
11266    }
11267
11268    /**
11269     * Move the scrolled position of your view. This will cause a call to
11270     * {@link #onScrollChanged(int, int, int, int)} and the view will be
11271     * invalidated.
11272     * @param x the amount of pixels to scroll by horizontally
11273     * @param y the amount of pixels to scroll by vertically
11274     */
11275    public void scrollBy(int x, int y) {
11276        scrollTo(mScrollX + x, mScrollY + y);
11277    }
11278
11279    /**
11280     * <p>Trigger the scrollbars to draw. When invoked this method starts an
11281     * animation to fade the scrollbars out after a default delay. If a subclass
11282     * provides animated scrolling, the start delay should equal the duration
11283     * of the scrolling animation.</p>
11284     *
11285     * <p>The animation starts only if at least one of the scrollbars is
11286     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
11287     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11288     * this method returns true, and false otherwise. If the animation is
11289     * started, this method calls {@link #invalidate()}; in that case the
11290     * caller should not call {@link #invalidate()}.</p>
11291     *
11292     * <p>This method should be invoked every time a subclass directly updates
11293     * the scroll parameters.</p>
11294     *
11295     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
11296     * and {@link #scrollTo(int, int)}.</p>
11297     *
11298     * @return true if the animation is played, false otherwise
11299     *
11300     * @see #awakenScrollBars(int)
11301     * @see #scrollBy(int, int)
11302     * @see #scrollTo(int, int)
11303     * @see #isHorizontalScrollBarEnabled()
11304     * @see #isVerticalScrollBarEnabled()
11305     * @see #setHorizontalScrollBarEnabled(boolean)
11306     * @see #setVerticalScrollBarEnabled(boolean)
11307     */
11308    protected boolean awakenScrollBars() {
11309        return mScrollCache != null &&
11310                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
11311    }
11312
11313    /**
11314     * Trigger the scrollbars to draw.
11315     * This method differs from awakenScrollBars() only in its default duration.
11316     * initialAwakenScrollBars() will show the scroll bars for longer than
11317     * usual to give the user more of a chance to notice them.
11318     *
11319     * @return true if the animation is played, false otherwise.
11320     */
11321    private boolean initialAwakenScrollBars() {
11322        return mScrollCache != null &&
11323                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
11324    }
11325
11326    /**
11327     * <p>
11328     * Trigger the scrollbars to draw. When invoked this method starts an
11329     * animation to fade the scrollbars out after a fixed delay. If a subclass
11330     * provides animated scrolling, the start delay should equal the duration of
11331     * the scrolling animation.
11332     * </p>
11333     *
11334     * <p>
11335     * The animation starts only if at least one of the scrollbars is enabled,
11336     * as specified by {@link #isHorizontalScrollBarEnabled()} and
11337     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11338     * this method returns true, and false otherwise. If the animation is
11339     * started, this method calls {@link #invalidate()}; in that case the caller
11340     * should not call {@link #invalidate()}.
11341     * </p>
11342     *
11343     * <p>
11344     * This method should be invoked everytime a subclass directly updates the
11345     * scroll parameters.
11346     * </p>
11347     *
11348     * @param startDelay the delay, in milliseconds, after which the animation
11349     *        should start; when the delay is 0, the animation starts
11350     *        immediately
11351     * @return true if the animation is played, false otherwise
11352     *
11353     * @see #scrollBy(int, int)
11354     * @see #scrollTo(int, int)
11355     * @see #isHorizontalScrollBarEnabled()
11356     * @see #isVerticalScrollBarEnabled()
11357     * @see #setHorizontalScrollBarEnabled(boolean)
11358     * @see #setVerticalScrollBarEnabled(boolean)
11359     */
11360    protected boolean awakenScrollBars(int startDelay) {
11361        return awakenScrollBars(startDelay, true);
11362    }
11363
11364    /**
11365     * <p>
11366     * Trigger the scrollbars to draw. When invoked this method starts an
11367     * animation to fade the scrollbars out after a fixed delay. If a subclass
11368     * provides animated scrolling, the start delay should equal the duration of
11369     * the scrolling animation.
11370     * </p>
11371     *
11372     * <p>
11373     * The animation starts only if at least one of the scrollbars is enabled,
11374     * as specified by {@link #isHorizontalScrollBarEnabled()} and
11375     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11376     * this method returns true, and false otherwise. If the animation is
11377     * started, this method calls {@link #invalidate()} if the invalidate parameter
11378     * is set to true; in that case the caller
11379     * should not call {@link #invalidate()}.
11380     * </p>
11381     *
11382     * <p>
11383     * This method should be invoked everytime a subclass directly updates the
11384     * scroll parameters.
11385     * </p>
11386     *
11387     * @param startDelay the delay, in milliseconds, after which the animation
11388     *        should start; when the delay is 0, the animation starts
11389     *        immediately
11390     *
11391     * @param invalidate Wheter this method should call invalidate
11392     *
11393     * @return true if the animation is played, false otherwise
11394     *
11395     * @see #scrollBy(int, int)
11396     * @see #scrollTo(int, int)
11397     * @see #isHorizontalScrollBarEnabled()
11398     * @see #isVerticalScrollBarEnabled()
11399     * @see #setHorizontalScrollBarEnabled(boolean)
11400     * @see #setVerticalScrollBarEnabled(boolean)
11401     */
11402    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
11403        final ScrollabilityCache scrollCache = mScrollCache;
11404
11405        if (scrollCache == null || !scrollCache.fadeScrollBars) {
11406            return false;
11407        }
11408
11409        if (scrollCache.scrollBar == null) {
11410            scrollCache.scrollBar = new ScrollBarDrawable();
11411        }
11412
11413        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
11414
11415            if (invalidate) {
11416                // Invalidate to show the scrollbars
11417                postInvalidateOnAnimation();
11418            }
11419
11420            if (scrollCache.state == ScrollabilityCache.OFF) {
11421                // FIXME: this is copied from WindowManagerService.
11422                // We should get this value from the system when it
11423                // is possible to do so.
11424                final int KEY_REPEAT_FIRST_DELAY = 750;
11425                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
11426            }
11427
11428            // Tell mScrollCache when we should start fading. This may
11429            // extend the fade start time if one was already scheduled
11430            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
11431            scrollCache.fadeStartTime = fadeStartTime;
11432            scrollCache.state = ScrollabilityCache.ON;
11433
11434            // Schedule our fader to run, unscheduling any old ones first
11435            if (mAttachInfo != null) {
11436                mAttachInfo.mHandler.removeCallbacks(scrollCache);
11437                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
11438            }
11439
11440            return true;
11441        }
11442
11443        return false;
11444    }
11445
11446    /**
11447     * Do not invalidate views which are not visible and which are not running an animation. They
11448     * will not get drawn and they should not set dirty flags as if they will be drawn
11449     */
11450    private boolean skipInvalidate() {
11451        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
11452                (!(mParent instanceof ViewGroup) ||
11453                        !((ViewGroup) mParent).isViewTransitioning(this));
11454    }
11455
11456    /**
11457     * Mark the area defined by dirty as needing to be drawn. If the view is
11458     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
11459     * point in the future.
11460     * <p>
11461     * This must be called from a UI thread. To call from a non-UI thread, call
11462     * {@link #postInvalidate()}.
11463     * <p>
11464     * <b>WARNING:</b> In API 19 and below, this method may be destructive to
11465     * {@code dirty}.
11466     *
11467     * @param dirty the rectangle representing the bounds of the dirty region
11468     */
11469    public void invalidate(Rect dirty) {
11470        final int scrollX = mScrollX;
11471        final int scrollY = mScrollY;
11472        invalidateInternal(dirty.left - scrollX, dirty.top - scrollY,
11473                dirty.right - scrollX, dirty.bottom - scrollY, true, false);
11474    }
11475
11476    /**
11477     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The
11478     * coordinates of the dirty rect are relative to the view. If the view is
11479     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
11480     * point in the future.
11481     * <p>
11482     * This must be called from a UI thread. To call from a non-UI thread, call
11483     * {@link #postInvalidate()}.
11484     *
11485     * @param l the left position of the dirty region
11486     * @param t the top position of the dirty region
11487     * @param r the right position of the dirty region
11488     * @param b the bottom position of the dirty region
11489     */
11490    public void invalidate(int l, int t, int r, int b) {
11491        final int scrollX = mScrollX;
11492        final int scrollY = mScrollY;
11493        invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false);
11494    }
11495
11496    /**
11497     * Invalidate the whole view. If the view is visible,
11498     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
11499     * the future.
11500     * <p>
11501     * This must be called from a UI thread. To call from a non-UI thread, call
11502     * {@link #postInvalidate()}.
11503     */
11504    public void invalidate() {
11505        invalidate(true);
11506    }
11507
11508    /**
11509     * This is where the invalidate() work actually happens. A full invalidate()
11510     * causes the drawing cache to be invalidated, but this function can be
11511     * called with invalidateCache set to false to skip that invalidation step
11512     * for cases that do not need it (for example, a component that remains at
11513     * the same dimensions with the same content).
11514     *
11515     * @param invalidateCache Whether the drawing cache for this view should be
11516     *            invalidated as well. This is usually true for a full
11517     *            invalidate, but may be set to false if the View's contents or
11518     *            dimensions have not changed.
11519     */
11520    void invalidate(boolean invalidateCache) {
11521        invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true);
11522    }
11523
11524    void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache,
11525            boolean fullInvalidate) {
11526        if (skipInvalidate()) {
11527            return;
11528        }
11529
11530        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)
11531                || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID)
11532                || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED
11533                || (fullInvalidate && isOpaque() != mLastIsOpaque)) {
11534            if (fullInvalidate) {
11535                mLastIsOpaque = isOpaque();
11536                mPrivateFlags &= ~PFLAG_DRAWN;
11537            }
11538
11539            mPrivateFlags |= PFLAG_DIRTY;
11540
11541            if (invalidateCache) {
11542                mPrivateFlags |= PFLAG_INVALIDATED;
11543                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
11544            }
11545
11546            // Propagate the damage rectangle to the parent view.
11547            final AttachInfo ai = mAttachInfo;
11548            final ViewParent p = mParent;
11549            if (p != null && ai != null && l < r && t < b) {
11550                final Rect damage = ai.mTmpInvalRect;
11551                damage.set(l, t, r, b);
11552                p.invalidateChild(this, damage);
11553            }
11554
11555            // Damage the entire projection receiver, if necessary.
11556            if (mBackground != null && mBackground.isProjected()) {
11557                final View receiver = getProjectionReceiver();
11558                if (receiver != null) {
11559                    receiver.damageInParent();
11560                }
11561            }
11562
11563            // Damage the entire IsolatedZVolume recieving this view's shadow.
11564            if (getCastsShadow() && getTranslationZ() != 0) {
11565                damageIsolatedZVolume();
11566            }
11567        }
11568    }
11569
11570    /**
11571     * @return this view's projection receiver, or {@code null} if none exists
11572     */
11573    private View getProjectionReceiver() {
11574        ViewParent p = getParent();
11575        while (p != null && p instanceof View) {
11576            final View v = (View) p;
11577            if (v.isProjectionReceiver()) {
11578                return v;
11579            }
11580            p = p.getParent();
11581        }
11582
11583        return null;
11584    }
11585
11586    /**
11587     * @return whether the view is a projection receiver
11588     */
11589    private boolean isProjectionReceiver() {
11590        return mBackground != null;
11591    }
11592
11593    /**
11594     * Damage area of the screen covered by the current isolated Z volume
11595     *
11596     * This method will guarantee that any changes to shadows cast by a View
11597     * are damaged on the screen for future redraw.
11598     */
11599    private void damageIsolatedZVolume() {
11600        final AttachInfo ai = mAttachInfo;
11601        if (ai != null) {
11602            ViewParent p = getParent();
11603            while (p != null) {
11604                if (p instanceof ViewGroup) {
11605                    final ViewGroup vg = (ViewGroup) p;
11606                    if (vg.hasIsolatedZVolume()) {
11607                        vg.damageInParent();
11608                        return;
11609                    }
11610                }
11611                p = p.getParent();
11612            }
11613        }
11614    }
11615
11616    /**
11617     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
11618     * set any flags or handle all of the cases handled by the default invalidation methods.
11619     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
11620     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
11621     * walk up the hierarchy, transforming the dirty rect as necessary.
11622     *
11623     * The method also handles normal invalidation logic if display list properties are not
11624     * being used in this view. The invalidateParent and forceRedraw flags are used by that
11625     * backup approach, to handle these cases used in the various property-setting methods.
11626     *
11627     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
11628     * are not being used in this view
11629     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
11630     * list properties are not being used in this view
11631     */
11632    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
11633        if (mDisplayList == null || (mPrivateFlags & PFLAG_DRAW_ANIMATION) == PFLAG_DRAW_ANIMATION) {
11634            if (invalidateParent) {
11635                invalidateParentCaches();
11636            }
11637            if (forceRedraw) {
11638                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
11639            }
11640            invalidate(false);
11641        } else {
11642            damageInParent();
11643        }
11644        if (invalidateParent && getCastsShadow() && getTranslationZ() != 0) {
11645            damageIsolatedZVolume();
11646        }
11647    }
11648
11649    /**
11650     * Tells the parent view to damage this view's bounds.
11651     *
11652     * @hide
11653     */
11654    protected void damageInParent() {
11655        final AttachInfo ai = mAttachInfo;
11656        final ViewParent p = mParent;
11657        if (p != null && ai != null) {
11658            final Rect r = ai.mTmpInvalRect;
11659            r.set(0, 0, mRight - mLeft, mBottom - mTop);
11660            if (mParent instanceof ViewGroup) {
11661                ((ViewGroup) mParent).invalidateChildFast(this, r);
11662            } else {
11663                mParent.invalidateChild(this, r);
11664            }
11665        }
11666    }
11667
11668    /**
11669     * Utility method to transform a given Rect by the current matrix of this view.
11670     */
11671    void transformRect(final Rect rect) {
11672        if (!getMatrix().isIdentity()) {
11673            RectF boundingRect = mAttachInfo.mTmpTransformRect;
11674            boundingRect.set(rect);
11675            getMatrix().mapRect(boundingRect);
11676            rect.set((int) Math.floor(boundingRect.left),
11677                    (int) Math.floor(boundingRect.top),
11678                    (int) Math.ceil(boundingRect.right),
11679                    (int) Math.ceil(boundingRect.bottom));
11680        }
11681    }
11682
11683    /**
11684     * Used to indicate that the parent of this view should clear its caches. This functionality
11685     * is used to force the parent to rebuild its display list (when hardware-accelerated),
11686     * which is necessary when various parent-managed properties of the view change, such as
11687     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
11688     * clears the parent caches and does not causes an invalidate event.
11689     *
11690     * @hide
11691     */
11692    protected void invalidateParentCaches() {
11693        if (mParent instanceof View) {
11694            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
11695        }
11696    }
11697
11698    /**
11699     * Used to indicate that the parent of this view should be invalidated. This functionality
11700     * is used to force the parent to rebuild its display list (when hardware-accelerated),
11701     * which is necessary when various parent-managed properties of the view change, such as
11702     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
11703     * an invalidation event to the parent.
11704     *
11705     * @hide
11706     */
11707    protected void invalidateParentIfNeeded() {
11708        if (isHardwareAccelerated() && mParent instanceof View) {
11709            ((View) mParent).invalidate(true);
11710        }
11711    }
11712
11713    /**
11714     * Indicates whether this View is opaque. An opaque View guarantees that it will
11715     * draw all the pixels overlapping its bounds using a fully opaque color.
11716     *
11717     * Subclasses of View should override this method whenever possible to indicate
11718     * whether an instance is opaque. Opaque Views are treated in a special way by
11719     * the View hierarchy, possibly allowing it to perform optimizations during
11720     * invalidate/draw passes.
11721     *
11722     * @return True if this View is guaranteed to be fully opaque, false otherwise.
11723     */
11724    @ViewDebug.ExportedProperty(category = "drawing")
11725    public boolean isOpaque() {
11726        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
11727                getFinalAlpha() >= 1.0f;
11728    }
11729
11730    /**
11731     * @hide
11732     */
11733    protected void computeOpaqueFlags() {
11734        // Opaque if:
11735        //   - Has a background
11736        //   - Background is opaque
11737        //   - Doesn't have scrollbars or scrollbars overlay
11738
11739        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
11740            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
11741        } else {
11742            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
11743        }
11744
11745        final int flags = mViewFlags;
11746        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
11747                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY ||
11748                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) {
11749            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
11750        } else {
11751            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
11752        }
11753    }
11754
11755    /**
11756     * @hide
11757     */
11758    protected boolean hasOpaqueScrollbars() {
11759        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
11760    }
11761
11762    /**
11763     * @return A handler associated with the thread running the View. This
11764     * handler can be used to pump events in the UI events queue.
11765     */
11766    public Handler getHandler() {
11767        final AttachInfo attachInfo = mAttachInfo;
11768        if (attachInfo != null) {
11769            return attachInfo.mHandler;
11770        }
11771        return null;
11772    }
11773
11774    /**
11775     * Gets the view root associated with the View.
11776     * @return The view root, or null if none.
11777     * @hide
11778     */
11779    public ViewRootImpl getViewRootImpl() {
11780        if (mAttachInfo != null) {
11781            return mAttachInfo.mViewRootImpl;
11782        }
11783        return null;
11784    }
11785
11786    /**
11787     * @hide
11788     */
11789    public HardwareRenderer getHardwareRenderer() {
11790        return mAttachInfo != null ? mAttachInfo.mHardwareRenderer : null;
11791    }
11792
11793    /**
11794     * <p>Causes the Runnable to be added to the message queue.
11795     * The runnable will be run on the user interface thread.</p>
11796     *
11797     * @param action The Runnable that will be executed.
11798     *
11799     * @return Returns true if the Runnable was successfully placed in to the
11800     *         message queue.  Returns false on failure, usually because the
11801     *         looper processing the message queue is exiting.
11802     *
11803     * @see #postDelayed
11804     * @see #removeCallbacks
11805     */
11806    public boolean post(Runnable action) {
11807        final AttachInfo attachInfo = mAttachInfo;
11808        if (attachInfo != null) {
11809            return attachInfo.mHandler.post(action);
11810        }
11811        // Assume that post will succeed later
11812        ViewRootImpl.getRunQueue().post(action);
11813        return true;
11814    }
11815
11816    /**
11817     * <p>Causes the Runnable to be added to the message queue, to be run
11818     * after the specified amount of time elapses.
11819     * The runnable will be run on the user interface thread.</p>
11820     *
11821     * @param action The Runnable that will be executed.
11822     * @param delayMillis The delay (in milliseconds) until the Runnable
11823     *        will be executed.
11824     *
11825     * @return true if the Runnable was successfully placed in to the
11826     *         message queue.  Returns false on failure, usually because the
11827     *         looper processing the message queue is exiting.  Note that a
11828     *         result of true does not mean the Runnable will be processed --
11829     *         if the looper is quit before the delivery time of the message
11830     *         occurs then the message will be dropped.
11831     *
11832     * @see #post
11833     * @see #removeCallbacks
11834     */
11835    public boolean postDelayed(Runnable action, long delayMillis) {
11836        final AttachInfo attachInfo = mAttachInfo;
11837        if (attachInfo != null) {
11838            return attachInfo.mHandler.postDelayed(action, delayMillis);
11839        }
11840        // Assume that post will succeed later
11841        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
11842        return true;
11843    }
11844
11845    /**
11846     * <p>Causes the Runnable to execute on the next animation time step.
11847     * The runnable will be run on the user interface thread.</p>
11848     *
11849     * @param action The Runnable that will be executed.
11850     *
11851     * @see #postOnAnimationDelayed
11852     * @see #removeCallbacks
11853     */
11854    public void postOnAnimation(Runnable action) {
11855        final AttachInfo attachInfo = mAttachInfo;
11856        if (attachInfo != null) {
11857            attachInfo.mViewRootImpl.mChoreographer.postCallback(
11858                    Choreographer.CALLBACK_ANIMATION, action, null);
11859        } else {
11860            // Assume that post will succeed later
11861            ViewRootImpl.getRunQueue().post(action);
11862        }
11863    }
11864
11865    /**
11866     * <p>Causes the Runnable to execute on the next animation time step,
11867     * after the specified amount of time elapses.
11868     * The runnable will be run on the user interface thread.</p>
11869     *
11870     * @param action The Runnable that will be executed.
11871     * @param delayMillis The delay (in milliseconds) until the Runnable
11872     *        will be executed.
11873     *
11874     * @see #postOnAnimation
11875     * @see #removeCallbacks
11876     */
11877    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
11878        final AttachInfo attachInfo = mAttachInfo;
11879        if (attachInfo != null) {
11880            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
11881                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
11882        } else {
11883            // Assume that post will succeed later
11884            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
11885        }
11886    }
11887
11888    /**
11889     * <p>Removes the specified Runnable from the message queue.</p>
11890     *
11891     * @param action The Runnable to remove from the message handling queue
11892     *
11893     * @return true if this view could ask the Handler to remove the Runnable,
11894     *         false otherwise. When the returned value is true, the Runnable
11895     *         may or may not have been actually removed from the message queue
11896     *         (for instance, if the Runnable was not in the queue already.)
11897     *
11898     * @see #post
11899     * @see #postDelayed
11900     * @see #postOnAnimation
11901     * @see #postOnAnimationDelayed
11902     */
11903    public boolean removeCallbacks(Runnable action) {
11904        if (action != null) {
11905            final AttachInfo attachInfo = mAttachInfo;
11906            if (attachInfo != null) {
11907                attachInfo.mHandler.removeCallbacks(action);
11908                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
11909                        Choreographer.CALLBACK_ANIMATION, action, null);
11910            }
11911            // Assume that post will succeed later
11912            ViewRootImpl.getRunQueue().removeCallbacks(action);
11913        }
11914        return true;
11915    }
11916
11917    /**
11918     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
11919     * Use this to invalidate the View from a non-UI thread.</p>
11920     *
11921     * <p>This method can be invoked from outside of the UI thread
11922     * only when this View is attached to a window.</p>
11923     *
11924     * @see #invalidate()
11925     * @see #postInvalidateDelayed(long)
11926     */
11927    public void postInvalidate() {
11928        postInvalidateDelayed(0);
11929    }
11930
11931    /**
11932     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
11933     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
11934     *
11935     * <p>This method can be invoked from outside of the UI thread
11936     * only when this View is attached to a window.</p>
11937     *
11938     * @param left The left coordinate of the rectangle to invalidate.
11939     * @param top The top coordinate of the rectangle to invalidate.
11940     * @param right The right coordinate of the rectangle to invalidate.
11941     * @param bottom The bottom coordinate of the rectangle to invalidate.
11942     *
11943     * @see #invalidate(int, int, int, int)
11944     * @see #invalidate(Rect)
11945     * @see #postInvalidateDelayed(long, int, int, int, int)
11946     */
11947    public void postInvalidate(int left, int top, int right, int bottom) {
11948        postInvalidateDelayed(0, left, top, right, bottom);
11949    }
11950
11951    /**
11952     * <p>Cause an invalidate to happen on a subsequent cycle through the event
11953     * loop. Waits for the specified amount of time.</p>
11954     *
11955     * <p>This method can be invoked from outside of the UI thread
11956     * only when this View is attached to a window.</p>
11957     *
11958     * @param delayMilliseconds the duration in milliseconds to delay the
11959     *         invalidation by
11960     *
11961     * @see #invalidate()
11962     * @see #postInvalidate()
11963     */
11964    public void postInvalidateDelayed(long delayMilliseconds) {
11965        // We try only with the AttachInfo because there's no point in invalidating
11966        // if we are not attached to our window
11967        final AttachInfo attachInfo = mAttachInfo;
11968        if (attachInfo != null) {
11969            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
11970        }
11971    }
11972
11973    /**
11974     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
11975     * through the event loop. Waits for the specified amount of time.</p>
11976     *
11977     * <p>This method can be invoked from outside of the UI thread
11978     * only when this View is attached to a window.</p>
11979     *
11980     * @param delayMilliseconds the duration in milliseconds to delay the
11981     *         invalidation by
11982     * @param left The left coordinate of the rectangle to invalidate.
11983     * @param top The top coordinate of the rectangle to invalidate.
11984     * @param right The right coordinate of the rectangle to invalidate.
11985     * @param bottom The bottom coordinate of the rectangle to invalidate.
11986     *
11987     * @see #invalidate(int, int, int, int)
11988     * @see #invalidate(Rect)
11989     * @see #postInvalidate(int, int, int, int)
11990     */
11991    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
11992            int right, int bottom) {
11993
11994        // We try only with the AttachInfo because there's no point in invalidating
11995        // if we are not attached to our window
11996        final AttachInfo attachInfo = mAttachInfo;
11997        if (attachInfo != null) {
11998            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
11999            info.target = this;
12000            info.left = left;
12001            info.top = top;
12002            info.right = right;
12003            info.bottom = bottom;
12004
12005            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
12006        }
12007    }
12008
12009    /**
12010     * <p>Cause an invalidate to happen on the next animation time step, typically the
12011     * next display frame.</p>
12012     *
12013     * <p>This method can be invoked from outside of the UI thread
12014     * only when this View is attached to a window.</p>
12015     *
12016     * @see #invalidate()
12017     */
12018    public void postInvalidateOnAnimation() {
12019        // We try only with the AttachInfo because there's no point in invalidating
12020        // if we are not attached to our window
12021        final AttachInfo attachInfo = mAttachInfo;
12022        if (attachInfo != null) {
12023            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
12024        }
12025    }
12026
12027    /**
12028     * <p>Cause an invalidate of the specified area to happen on the next animation
12029     * time step, typically the next display frame.</p>
12030     *
12031     * <p>This method can be invoked from outside of the UI thread
12032     * only when this View is attached to a window.</p>
12033     *
12034     * @param left The left coordinate of the rectangle to invalidate.
12035     * @param top The top coordinate of the rectangle to invalidate.
12036     * @param right The right coordinate of the rectangle to invalidate.
12037     * @param bottom The bottom coordinate of the rectangle to invalidate.
12038     *
12039     * @see #invalidate(int, int, int, int)
12040     * @see #invalidate(Rect)
12041     */
12042    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
12043        // We try only with the AttachInfo because there's no point in invalidating
12044        // if we are not attached to our window
12045        final AttachInfo attachInfo = mAttachInfo;
12046        if (attachInfo != null) {
12047            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
12048            info.target = this;
12049            info.left = left;
12050            info.top = top;
12051            info.right = right;
12052            info.bottom = bottom;
12053
12054            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
12055        }
12056    }
12057
12058    /**
12059     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
12060     * This event is sent at most once every
12061     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
12062     */
12063    private void postSendViewScrolledAccessibilityEventCallback() {
12064        if (mSendViewScrolledAccessibilityEvent == null) {
12065            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
12066        }
12067        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
12068            mSendViewScrolledAccessibilityEvent.mIsPending = true;
12069            postDelayed(mSendViewScrolledAccessibilityEvent,
12070                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
12071        }
12072    }
12073
12074    /**
12075     * Called by a parent to request that a child update its values for mScrollX
12076     * and mScrollY if necessary. This will typically be done if the child is
12077     * animating a scroll using a {@link android.widget.Scroller Scroller}
12078     * object.
12079     */
12080    public void computeScroll() {
12081    }
12082
12083    /**
12084     * <p>Indicate whether the horizontal edges are faded when the view is
12085     * scrolled horizontally.</p>
12086     *
12087     * @return true if the horizontal edges should are faded on scroll, false
12088     *         otherwise
12089     *
12090     * @see #setHorizontalFadingEdgeEnabled(boolean)
12091     *
12092     * @attr ref android.R.styleable#View_requiresFadingEdge
12093     */
12094    public boolean isHorizontalFadingEdgeEnabled() {
12095        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
12096    }
12097
12098    /**
12099     * <p>Define whether the horizontal edges should be faded when this view
12100     * is scrolled horizontally.</p>
12101     *
12102     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
12103     *                                    be faded when the view is scrolled
12104     *                                    horizontally
12105     *
12106     * @see #isHorizontalFadingEdgeEnabled()
12107     *
12108     * @attr ref android.R.styleable#View_requiresFadingEdge
12109     */
12110    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
12111        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
12112            if (horizontalFadingEdgeEnabled) {
12113                initScrollCache();
12114            }
12115
12116            mViewFlags ^= FADING_EDGE_HORIZONTAL;
12117        }
12118    }
12119
12120    /**
12121     * <p>Indicate whether the vertical edges are faded when the view is
12122     * scrolled horizontally.</p>
12123     *
12124     * @return true if the vertical edges should are faded on scroll, false
12125     *         otherwise
12126     *
12127     * @see #setVerticalFadingEdgeEnabled(boolean)
12128     *
12129     * @attr ref android.R.styleable#View_requiresFadingEdge
12130     */
12131    public boolean isVerticalFadingEdgeEnabled() {
12132        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
12133    }
12134
12135    /**
12136     * <p>Define whether the vertical edges should be faded when this view
12137     * is scrolled vertically.</p>
12138     *
12139     * @param verticalFadingEdgeEnabled true if the vertical edges should
12140     *                                  be faded when the view is scrolled
12141     *                                  vertically
12142     *
12143     * @see #isVerticalFadingEdgeEnabled()
12144     *
12145     * @attr ref android.R.styleable#View_requiresFadingEdge
12146     */
12147    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
12148        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
12149            if (verticalFadingEdgeEnabled) {
12150                initScrollCache();
12151            }
12152
12153            mViewFlags ^= FADING_EDGE_VERTICAL;
12154        }
12155    }
12156
12157    /**
12158     * Returns the strength, or intensity, of the top faded edge. The strength is
12159     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12160     * returns 0.0 or 1.0 but no value in between.
12161     *
12162     * Subclasses should override this method to provide a smoother fade transition
12163     * when scrolling occurs.
12164     *
12165     * @return the intensity of the top fade as a float between 0.0f and 1.0f
12166     */
12167    protected float getTopFadingEdgeStrength() {
12168        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
12169    }
12170
12171    /**
12172     * Returns the strength, or intensity, of the bottom faded edge. The strength is
12173     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12174     * returns 0.0 or 1.0 but no value in between.
12175     *
12176     * Subclasses should override this method to provide a smoother fade transition
12177     * when scrolling occurs.
12178     *
12179     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
12180     */
12181    protected float getBottomFadingEdgeStrength() {
12182        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
12183                computeVerticalScrollRange() ? 1.0f : 0.0f;
12184    }
12185
12186    /**
12187     * Returns the strength, or intensity, of the left faded edge. The strength is
12188     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12189     * returns 0.0 or 1.0 but no value in between.
12190     *
12191     * Subclasses should override this method to provide a smoother fade transition
12192     * when scrolling occurs.
12193     *
12194     * @return the intensity of the left fade as a float between 0.0f and 1.0f
12195     */
12196    protected float getLeftFadingEdgeStrength() {
12197        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
12198    }
12199
12200    /**
12201     * Returns the strength, or intensity, of the right faded edge. The strength is
12202     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12203     * returns 0.0 or 1.0 but no value in between.
12204     *
12205     * Subclasses should override this method to provide a smoother fade transition
12206     * when scrolling occurs.
12207     *
12208     * @return the intensity of the right fade as a float between 0.0f and 1.0f
12209     */
12210    protected float getRightFadingEdgeStrength() {
12211        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
12212                computeHorizontalScrollRange() ? 1.0f : 0.0f;
12213    }
12214
12215    /**
12216     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
12217     * scrollbar is not drawn by default.</p>
12218     *
12219     * @return true if the horizontal scrollbar should be painted, false
12220     *         otherwise
12221     *
12222     * @see #setHorizontalScrollBarEnabled(boolean)
12223     */
12224    public boolean isHorizontalScrollBarEnabled() {
12225        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
12226    }
12227
12228    /**
12229     * <p>Define whether the horizontal scrollbar should be drawn or not. The
12230     * scrollbar is not drawn by default.</p>
12231     *
12232     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
12233     *                                   be painted
12234     *
12235     * @see #isHorizontalScrollBarEnabled()
12236     */
12237    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
12238        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
12239            mViewFlags ^= SCROLLBARS_HORIZONTAL;
12240            computeOpaqueFlags();
12241            resolvePadding();
12242        }
12243    }
12244
12245    /**
12246     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
12247     * scrollbar is not drawn by default.</p>
12248     *
12249     * @return true if the vertical scrollbar should be painted, false
12250     *         otherwise
12251     *
12252     * @see #setVerticalScrollBarEnabled(boolean)
12253     */
12254    public boolean isVerticalScrollBarEnabled() {
12255        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
12256    }
12257
12258    /**
12259     * <p>Define whether the vertical scrollbar should be drawn or not. The
12260     * scrollbar is not drawn by default.</p>
12261     *
12262     * @param verticalScrollBarEnabled true if the vertical scrollbar should
12263     *                                 be painted
12264     *
12265     * @see #isVerticalScrollBarEnabled()
12266     */
12267    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
12268        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
12269            mViewFlags ^= SCROLLBARS_VERTICAL;
12270            computeOpaqueFlags();
12271            resolvePadding();
12272        }
12273    }
12274
12275    /**
12276     * @hide
12277     */
12278    protected void recomputePadding() {
12279        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
12280    }
12281
12282    /**
12283     * Define whether scrollbars will fade when the view is not scrolling.
12284     *
12285     * @param fadeScrollbars wheter to enable fading
12286     *
12287     * @attr ref android.R.styleable#View_fadeScrollbars
12288     */
12289    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
12290        initScrollCache();
12291        final ScrollabilityCache scrollabilityCache = mScrollCache;
12292        scrollabilityCache.fadeScrollBars = fadeScrollbars;
12293        if (fadeScrollbars) {
12294            scrollabilityCache.state = ScrollabilityCache.OFF;
12295        } else {
12296            scrollabilityCache.state = ScrollabilityCache.ON;
12297        }
12298    }
12299
12300    /**
12301     *
12302     * Returns true if scrollbars will fade when this view is not scrolling
12303     *
12304     * @return true if scrollbar fading is enabled
12305     *
12306     * @attr ref android.R.styleable#View_fadeScrollbars
12307     */
12308    public boolean isScrollbarFadingEnabled() {
12309        return mScrollCache != null && mScrollCache.fadeScrollBars;
12310    }
12311
12312    /**
12313     *
12314     * Returns the delay before scrollbars fade.
12315     *
12316     * @return the delay before scrollbars fade
12317     *
12318     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
12319     */
12320    public int getScrollBarDefaultDelayBeforeFade() {
12321        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
12322                mScrollCache.scrollBarDefaultDelayBeforeFade;
12323    }
12324
12325    /**
12326     * Define the delay before scrollbars fade.
12327     *
12328     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
12329     *
12330     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
12331     */
12332    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
12333        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
12334    }
12335
12336    /**
12337     *
12338     * Returns the scrollbar fade duration.
12339     *
12340     * @return the scrollbar fade duration
12341     *
12342     * @attr ref android.R.styleable#View_scrollbarFadeDuration
12343     */
12344    public int getScrollBarFadeDuration() {
12345        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
12346                mScrollCache.scrollBarFadeDuration;
12347    }
12348
12349    /**
12350     * Define the scrollbar fade duration.
12351     *
12352     * @param scrollBarFadeDuration - the scrollbar fade duration
12353     *
12354     * @attr ref android.R.styleable#View_scrollbarFadeDuration
12355     */
12356    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
12357        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
12358    }
12359
12360    /**
12361     *
12362     * Returns the scrollbar size.
12363     *
12364     * @return the scrollbar size
12365     *
12366     * @attr ref android.R.styleable#View_scrollbarSize
12367     */
12368    public int getScrollBarSize() {
12369        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
12370                mScrollCache.scrollBarSize;
12371    }
12372
12373    /**
12374     * Define the scrollbar size.
12375     *
12376     * @param scrollBarSize - the scrollbar size
12377     *
12378     * @attr ref android.R.styleable#View_scrollbarSize
12379     */
12380    public void setScrollBarSize(int scrollBarSize) {
12381        getScrollCache().scrollBarSize = scrollBarSize;
12382    }
12383
12384    /**
12385     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
12386     * inset. When inset, they add to the padding of the view. And the scrollbars
12387     * can be drawn inside the padding area or on the edge of the view. For example,
12388     * if a view has a background drawable and you want to draw the scrollbars
12389     * inside the padding specified by the drawable, you can use
12390     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
12391     * appear at the edge of the view, ignoring the padding, then you can use
12392     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
12393     * @param style the style of the scrollbars. Should be one of
12394     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
12395     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
12396     * @see #SCROLLBARS_INSIDE_OVERLAY
12397     * @see #SCROLLBARS_INSIDE_INSET
12398     * @see #SCROLLBARS_OUTSIDE_OVERLAY
12399     * @see #SCROLLBARS_OUTSIDE_INSET
12400     *
12401     * @attr ref android.R.styleable#View_scrollbarStyle
12402     */
12403    public void setScrollBarStyle(@ScrollBarStyle int style) {
12404        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
12405            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
12406            computeOpaqueFlags();
12407            resolvePadding();
12408        }
12409    }
12410
12411    /**
12412     * <p>Returns the current scrollbar style.</p>
12413     * @return the current scrollbar style
12414     * @see #SCROLLBARS_INSIDE_OVERLAY
12415     * @see #SCROLLBARS_INSIDE_INSET
12416     * @see #SCROLLBARS_OUTSIDE_OVERLAY
12417     * @see #SCROLLBARS_OUTSIDE_INSET
12418     *
12419     * @attr ref android.R.styleable#View_scrollbarStyle
12420     */
12421    @ViewDebug.ExportedProperty(mapping = {
12422            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
12423            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
12424            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
12425            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
12426    })
12427    @ScrollBarStyle
12428    public int getScrollBarStyle() {
12429        return mViewFlags & SCROLLBARS_STYLE_MASK;
12430    }
12431
12432    /**
12433     * <p>Compute the horizontal range that the horizontal scrollbar
12434     * represents.</p>
12435     *
12436     * <p>The range is expressed in arbitrary units that must be the same as the
12437     * units used by {@link #computeHorizontalScrollExtent()} and
12438     * {@link #computeHorizontalScrollOffset()}.</p>
12439     *
12440     * <p>The default range is the drawing width of this view.</p>
12441     *
12442     * @return the total horizontal range represented by the horizontal
12443     *         scrollbar
12444     *
12445     * @see #computeHorizontalScrollExtent()
12446     * @see #computeHorizontalScrollOffset()
12447     * @see android.widget.ScrollBarDrawable
12448     */
12449    protected int computeHorizontalScrollRange() {
12450        return getWidth();
12451    }
12452
12453    /**
12454     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
12455     * within the horizontal range. This value is used to compute the position
12456     * of the thumb within the scrollbar's track.</p>
12457     *
12458     * <p>The range is expressed in arbitrary units that must be the same as the
12459     * units used by {@link #computeHorizontalScrollRange()} and
12460     * {@link #computeHorizontalScrollExtent()}.</p>
12461     *
12462     * <p>The default offset is the scroll offset of this view.</p>
12463     *
12464     * @return the horizontal offset of the scrollbar's thumb
12465     *
12466     * @see #computeHorizontalScrollRange()
12467     * @see #computeHorizontalScrollExtent()
12468     * @see android.widget.ScrollBarDrawable
12469     */
12470    protected int computeHorizontalScrollOffset() {
12471        return mScrollX;
12472    }
12473
12474    /**
12475     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
12476     * within the horizontal range. This value is used to compute the length
12477     * of the thumb within the scrollbar's track.</p>
12478     *
12479     * <p>The range is expressed in arbitrary units that must be the same as the
12480     * units used by {@link #computeHorizontalScrollRange()} and
12481     * {@link #computeHorizontalScrollOffset()}.</p>
12482     *
12483     * <p>The default extent is the drawing width of this view.</p>
12484     *
12485     * @return the horizontal extent of the scrollbar's thumb
12486     *
12487     * @see #computeHorizontalScrollRange()
12488     * @see #computeHorizontalScrollOffset()
12489     * @see android.widget.ScrollBarDrawable
12490     */
12491    protected int computeHorizontalScrollExtent() {
12492        return getWidth();
12493    }
12494
12495    /**
12496     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
12497     *
12498     * <p>The range is expressed in arbitrary units that must be the same as the
12499     * units used by {@link #computeVerticalScrollExtent()} and
12500     * {@link #computeVerticalScrollOffset()}.</p>
12501     *
12502     * @return the total vertical range represented by the vertical scrollbar
12503     *
12504     * <p>The default range is the drawing height of this view.</p>
12505     *
12506     * @see #computeVerticalScrollExtent()
12507     * @see #computeVerticalScrollOffset()
12508     * @see android.widget.ScrollBarDrawable
12509     */
12510    protected int computeVerticalScrollRange() {
12511        return getHeight();
12512    }
12513
12514    /**
12515     * <p>Compute the vertical offset of the vertical scrollbar's thumb
12516     * within the horizontal range. This value is used to compute the position
12517     * of the thumb within the scrollbar's track.</p>
12518     *
12519     * <p>The range is expressed in arbitrary units that must be the same as the
12520     * units used by {@link #computeVerticalScrollRange()} and
12521     * {@link #computeVerticalScrollExtent()}.</p>
12522     *
12523     * <p>The default offset is the scroll offset of this view.</p>
12524     *
12525     * @return the vertical offset of the scrollbar's thumb
12526     *
12527     * @see #computeVerticalScrollRange()
12528     * @see #computeVerticalScrollExtent()
12529     * @see android.widget.ScrollBarDrawable
12530     */
12531    protected int computeVerticalScrollOffset() {
12532        return mScrollY;
12533    }
12534
12535    /**
12536     * <p>Compute the vertical extent of the vertical scrollbar's thumb
12537     * within the vertical range. This value is used to compute the length
12538     * of the thumb within the scrollbar's track.</p>
12539     *
12540     * <p>The range is expressed in arbitrary units that must be the same as the
12541     * units used by {@link #computeVerticalScrollRange()} and
12542     * {@link #computeVerticalScrollOffset()}.</p>
12543     *
12544     * <p>The default extent is the drawing height of this view.</p>
12545     *
12546     * @return the vertical extent of the scrollbar's thumb
12547     *
12548     * @see #computeVerticalScrollRange()
12549     * @see #computeVerticalScrollOffset()
12550     * @see android.widget.ScrollBarDrawable
12551     */
12552    protected int computeVerticalScrollExtent() {
12553        return getHeight();
12554    }
12555
12556    /**
12557     * Check if this view can be scrolled horizontally in a certain direction.
12558     *
12559     * @param direction Negative to check scrolling left, positive to check scrolling right.
12560     * @return true if this view can be scrolled in the specified direction, false otherwise.
12561     */
12562    public boolean canScrollHorizontally(int direction) {
12563        final int offset = computeHorizontalScrollOffset();
12564        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
12565        if (range == 0) return false;
12566        if (direction < 0) {
12567            return offset > 0;
12568        } else {
12569            return offset < range - 1;
12570        }
12571    }
12572
12573    /**
12574     * Check if this view can be scrolled vertically in a certain direction.
12575     *
12576     * @param direction Negative to check scrolling up, positive to check scrolling down.
12577     * @return true if this view can be scrolled in the specified direction, false otherwise.
12578     */
12579    public boolean canScrollVertically(int direction) {
12580        final int offset = computeVerticalScrollOffset();
12581        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
12582        if (range == 0) return false;
12583        if (direction < 0) {
12584            return offset > 0;
12585        } else {
12586            return offset < range - 1;
12587        }
12588    }
12589
12590    /**
12591     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
12592     * scrollbars are painted only if they have been awakened first.</p>
12593     *
12594     * @param canvas the canvas on which to draw the scrollbars
12595     *
12596     * @see #awakenScrollBars(int)
12597     */
12598    protected final void onDrawScrollBars(Canvas canvas) {
12599        // scrollbars are drawn only when the animation is running
12600        final ScrollabilityCache cache = mScrollCache;
12601        if (cache != null) {
12602
12603            int state = cache.state;
12604
12605            if (state == ScrollabilityCache.OFF) {
12606                return;
12607            }
12608
12609            boolean invalidate = false;
12610
12611            if (state == ScrollabilityCache.FADING) {
12612                // We're fading -- get our fade interpolation
12613                if (cache.interpolatorValues == null) {
12614                    cache.interpolatorValues = new float[1];
12615                }
12616
12617                float[] values = cache.interpolatorValues;
12618
12619                // Stops the animation if we're done
12620                if (cache.scrollBarInterpolator.timeToValues(values) ==
12621                        Interpolator.Result.FREEZE_END) {
12622                    cache.state = ScrollabilityCache.OFF;
12623                } else {
12624                    cache.scrollBar.setAlpha(Math.round(values[0]));
12625                }
12626
12627                // This will make the scroll bars inval themselves after
12628                // drawing. We only want this when we're fading so that
12629                // we prevent excessive redraws
12630                invalidate = true;
12631            } else {
12632                // We're just on -- but we may have been fading before so
12633                // reset alpha
12634                cache.scrollBar.setAlpha(255);
12635            }
12636
12637
12638            final int viewFlags = mViewFlags;
12639
12640            final boolean drawHorizontalScrollBar =
12641                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
12642            final boolean drawVerticalScrollBar =
12643                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
12644                && !isVerticalScrollBarHidden();
12645
12646            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
12647                final int width = mRight - mLeft;
12648                final int height = mBottom - mTop;
12649
12650                final ScrollBarDrawable scrollBar = cache.scrollBar;
12651
12652                final int scrollX = mScrollX;
12653                final int scrollY = mScrollY;
12654                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
12655
12656                int left;
12657                int top;
12658                int right;
12659                int bottom;
12660
12661                if (drawHorizontalScrollBar) {
12662                    int size = scrollBar.getSize(false);
12663                    if (size <= 0) {
12664                        size = cache.scrollBarSize;
12665                    }
12666
12667                    scrollBar.setParameters(computeHorizontalScrollRange(),
12668                                            computeHorizontalScrollOffset(),
12669                                            computeHorizontalScrollExtent(), false);
12670                    final int verticalScrollBarGap = drawVerticalScrollBar ?
12671                            getVerticalScrollbarWidth() : 0;
12672                    top = scrollY + height - size - (mUserPaddingBottom & inside);
12673                    left = scrollX + (mPaddingLeft & inside);
12674                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
12675                    bottom = top + size;
12676                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
12677                    if (invalidate) {
12678                        invalidate(left, top, right, bottom);
12679                    }
12680                }
12681
12682                if (drawVerticalScrollBar) {
12683                    int size = scrollBar.getSize(true);
12684                    if (size <= 0) {
12685                        size = cache.scrollBarSize;
12686                    }
12687
12688                    scrollBar.setParameters(computeVerticalScrollRange(),
12689                                            computeVerticalScrollOffset(),
12690                                            computeVerticalScrollExtent(), true);
12691                    int verticalScrollbarPosition = mVerticalScrollbarPosition;
12692                    if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
12693                        verticalScrollbarPosition = isLayoutRtl() ?
12694                                SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
12695                    }
12696                    switch (verticalScrollbarPosition) {
12697                        default:
12698                        case SCROLLBAR_POSITION_RIGHT:
12699                            left = scrollX + width - size - (mUserPaddingRight & inside);
12700                            break;
12701                        case SCROLLBAR_POSITION_LEFT:
12702                            left = scrollX + (mUserPaddingLeft & inside);
12703                            break;
12704                    }
12705                    top = scrollY + (mPaddingTop & inside);
12706                    right = left + size;
12707                    bottom = scrollY + height - (mUserPaddingBottom & inside);
12708                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
12709                    if (invalidate) {
12710                        invalidate(left, top, right, bottom);
12711                    }
12712                }
12713            }
12714        }
12715    }
12716
12717    /**
12718     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
12719     * FastScroller is visible.
12720     * @return whether to temporarily hide the vertical scrollbar
12721     * @hide
12722     */
12723    protected boolean isVerticalScrollBarHidden() {
12724        return false;
12725    }
12726
12727    /**
12728     * <p>Draw the horizontal scrollbar if
12729     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
12730     *
12731     * @param canvas the canvas on which to draw the scrollbar
12732     * @param scrollBar the scrollbar's drawable
12733     *
12734     * @see #isHorizontalScrollBarEnabled()
12735     * @see #computeHorizontalScrollRange()
12736     * @see #computeHorizontalScrollExtent()
12737     * @see #computeHorizontalScrollOffset()
12738     * @see android.widget.ScrollBarDrawable
12739     * @hide
12740     */
12741    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
12742            int l, int t, int r, int b) {
12743        scrollBar.setBounds(l, t, r, b);
12744        scrollBar.draw(canvas);
12745    }
12746
12747    /**
12748     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
12749     * returns true.</p>
12750     *
12751     * @param canvas the canvas on which to draw the scrollbar
12752     * @param scrollBar the scrollbar's drawable
12753     *
12754     * @see #isVerticalScrollBarEnabled()
12755     * @see #computeVerticalScrollRange()
12756     * @see #computeVerticalScrollExtent()
12757     * @see #computeVerticalScrollOffset()
12758     * @see android.widget.ScrollBarDrawable
12759     * @hide
12760     */
12761    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
12762            int l, int t, int r, int b) {
12763        scrollBar.setBounds(l, t, r, b);
12764        scrollBar.draw(canvas);
12765    }
12766
12767    /**
12768     * Implement this to do your drawing.
12769     *
12770     * @param canvas the canvas on which the background will be drawn
12771     */
12772    protected void onDraw(Canvas canvas) {
12773    }
12774
12775    /*
12776     * Caller is responsible for calling requestLayout if necessary.
12777     * (This allows addViewInLayout to not request a new layout.)
12778     */
12779    void assignParent(ViewParent parent) {
12780        if (mParent == null) {
12781            mParent = parent;
12782        } else if (parent == null) {
12783            mParent = null;
12784        } else {
12785            throw new RuntimeException("view " + this + " being added, but"
12786                    + " it already has a parent");
12787        }
12788    }
12789
12790    /**
12791     * This is called when the view is attached to a window.  At this point it
12792     * has a Surface and will start drawing.  Note that this function is
12793     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
12794     * however it may be called any time before the first onDraw -- including
12795     * before or after {@link #onMeasure(int, int)}.
12796     *
12797     * @see #onDetachedFromWindow()
12798     */
12799    protected void onAttachedToWindow() {
12800        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
12801            mParent.requestTransparentRegion(this);
12802        }
12803
12804        if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
12805            initialAwakenScrollBars();
12806            mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
12807        }
12808
12809        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
12810
12811        jumpDrawablesToCurrentState();
12812
12813        resetSubtreeAccessibilityStateChanged();
12814
12815        if (isFocused()) {
12816            InputMethodManager imm = InputMethodManager.peekInstance();
12817            imm.focusIn(this);
12818        }
12819    }
12820
12821    /**
12822     * Resolve all RTL related properties.
12823     *
12824     * @return true if resolution of RTL properties has been done
12825     *
12826     * @hide
12827     */
12828    public boolean resolveRtlPropertiesIfNeeded() {
12829        if (!needRtlPropertiesResolution()) return false;
12830
12831        // Order is important here: LayoutDirection MUST be resolved first
12832        if (!isLayoutDirectionResolved()) {
12833            resolveLayoutDirection();
12834            resolveLayoutParams();
12835        }
12836        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
12837        if (!isTextDirectionResolved()) {
12838            resolveTextDirection();
12839        }
12840        if (!isTextAlignmentResolved()) {
12841            resolveTextAlignment();
12842        }
12843        // Should resolve Drawables before Padding because we need the layout direction of the
12844        // Drawable to correctly resolve Padding.
12845        if (!isDrawablesResolved()) {
12846            resolveDrawables();
12847        }
12848        if (!isPaddingResolved()) {
12849            resolvePadding();
12850        }
12851        onRtlPropertiesChanged(getLayoutDirection());
12852        return true;
12853    }
12854
12855    /**
12856     * Reset resolution of all RTL related properties.
12857     *
12858     * @hide
12859     */
12860    public void resetRtlProperties() {
12861        resetResolvedLayoutDirection();
12862        resetResolvedTextDirection();
12863        resetResolvedTextAlignment();
12864        resetResolvedPadding();
12865        resetResolvedDrawables();
12866    }
12867
12868    /**
12869     * @see #onScreenStateChanged(int)
12870     */
12871    void dispatchScreenStateChanged(int screenState) {
12872        onScreenStateChanged(screenState);
12873    }
12874
12875    /**
12876     * This method is called whenever the state of the screen this view is
12877     * attached to changes. A state change will usually occurs when the screen
12878     * turns on or off (whether it happens automatically or the user does it
12879     * manually.)
12880     *
12881     * @param screenState The new state of the screen. Can be either
12882     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
12883     */
12884    public void onScreenStateChanged(int screenState) {
12885    }
12886
12887    /**
12888     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
12889     */
12890    private boolean hasRtlSupport() {
12891        return mContext.getApplicationInfo().hasRtlSupport();
12892    }
12893
12894    /**
12895     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
12896     * RTL not supported)
12897     */
12898    private boolean isRtlCompatibilityMode() {
12899        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
12900        return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport();
12901    }
12902
12903    /**
12904     * @return true if RTL properties need resolution.
12905     *
12906     */
12907    private boolean needRtlPropertiesResolution() {
12908        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
12909    }
12910
12911    /**
12912     * Called when any RTL property (layout direction or text direction or text alignment) has
12913     * been changed.
12914     *
12915     * Subclasses need to override this method to take care of cached information that depends on the
12916     * resolved layout direction, or to inform child views that inherit their layout direction.
12917     *
12918     * The default implementation does nothing.
12919     *
12920     * @param layoutDirection the direction of the layout
12921     *
12922     * @see #LAYOUT_DIRECTION_LTR
12923     * @see #LAYOUT_DIRECTION_RTL
12924     */
12925    public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) {
12926    }
12927
12928    /**
12929     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
12930     * that the parent directionality can and will be resolved before its children.
12931     *
12932     * @return true if resolution has been done, false otherwise.
12933     *
12934     * @hide
12935     */
12936    public boolean resolveLayoutDirection() {
12937        // Clear any previous layout direction resolution
12938        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
12939
12940        if (hasRtlSupport()) {
12941            // Set resolved depending on layout direction
12942            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
12943                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
12944                case LAYOUT_DIRECTION_INHERIT:
12945                    // We cannot resolve yet. LTR is by default and let the resolution happen again
12946                    // later to get the correct resolved value
12947                    if (!canResolveLayoutDirection()) return false;
12948
12949                    // Parent has not yet resolved, LTR is still the default
12950                    try {
12951                        if (!mParent.isLayoutDirectionResolved()) return false;
12952
12953                        if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
12954                            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12955                        }
12956                    } catch (AbstractMethodError e) {
12957                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
12958                                " does not fully implement ViewParent", e);
12959                    }
12960                    break;
12961                case LAYOUT_DIRECTION_RTL:
12962                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12963                    break;
12964                case LAYOUT_DIRECTION_LOCALE:
12965                    if((LAYOUT_DIRECTION_RTL ==
12966                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
12967                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12968                    }
12969                    break;
12970                default:
12971                    // Nothing to do, LTR by default
12972            }
12973        }
12974
12975        // Set to resolved
12976        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
12977        return true;
12978    }
12979
12980    /**
12981     * Check if layout direction resolution can be done.
12982     *
12983     * @return true if layout direction resolution can be done otherwise return false.
12984     */
12985    public boolean canResolveLayoutDirection() {
12986        switch (getRawLayoutDirection()) {
12987            case LAYOUT_DIRECTION_INHERIT:
12988                if (mParent != null) {
12989                    try {
12990                        return mParent.canResolveLayoutDirection();
12991                    } catch (AbstractMethodError e) {
12992                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
12993                                " does not fully implement ViewParent", e);
12994                    }
12995                }
12996                return false;
12997
12998            default:
12999                return true;
13000        }
13001    }
13002
13003    /**
13004     * Reset the resolved layout direction. Layout direction will be resolved during a call to
13005     * {@link #onMeasure(int, int)}.
13006     *
13007     * @hide
13008     */
13009    public void resetResolvedLayoutDirection() {
13010        // Reset the current resolved bits
13011        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
13012    }
13013
13014    /**
13015     * @return true if the layout direction is inherited.
13016     *
13017     * @hide
13018     */
13019    public boolean isLayoutDirectionInherited() {
13020        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
13021    }
13022
13023    /**
13024     * @return true if layout direction has been resolved.
13025     */
13026    public boolean isLayoutDirectionResolved() {
13027        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
13028    }
13029
13030    /**
13031     * Return if padding has been resolved
13032     *
13033     * @hide
13034     */
13035    boolean isPaddingResolved() {
13036        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
13037    }
13038
13039    /**
13040     * Resolves padding depending on layout direction, if applicable, and
13041     * recomputes internal padding values to adjust for scroll bars.
13042     *
13043     * @hide
13044     */
13045    public void resolvePadding() {
13046        final int resolvedLayoutDirection = getLayoutDirection();
13047
13048        if (!isRtlCompatibilityMode()) {
13049            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
13050            // If start / end padding are defined, they will be resolved (hence overriding) to
13051            // left / right or right / left depending on the resolved layout direction.
13052            // If start / end padding are not defined, use the left / right ones.
13053            if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) {
13054                Rect padding = sThreadLocal.get();
13055                if (padding == null) {
13056                    padding = new Rect();
13057                    sThreadLocal.set(padding);
13058                }
13059                mBackground.getPadding(padding);
13060                if (!mLeftPaddingDefined) {
13061                    mUserPaddingLeftInitial = padding.left;
13062                }
13063                if (!mRightPaddingDefined) {
13064                    mUserPaddingRightInitial = padding.right;
13065                }
13066            }
13067            switch (resolvedLayoutDirection) {
13068                case LAYOUT_DIRECTION_RTL:
13069                    if (mUserPaddingStart != UNDEFINED_PADDING) {
13070                        mUserPaddingRight = mUserPaddingStart;
13071                    } else {
13072                        mUserPaddingRight = mUserPaddingRightInitial;
13073                    }
13074                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
13075                        mUserPaddingLeft = mUserPaddingEnd;
13076                    } else {
13077                        mUserPaddingLeft = mUserPaddingLeftInitial;
13078                    }
13079                    break;
13080                case LAYOUT_DIRECTION_LTR:
13081                default:
13082                    if (mUserPaddingStart != UNDEFINED_PADDING) {
13083                        mUserPaddingLeft = mUserPaddingStart;
13084                    } else {
13085                        mUserPaddingLeft = mUserPaddingLeftInitial;
13086                    }
13087                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
13088                        mUserPaddingRight = mUserPaddingEnd;
13089                    } else {
13090                        mUserPaddingRight = mUserPaddingRightInitial;
13091                    }
13092            }
13093
13094            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
13095        }
13096
13097        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
13098        onRtlPropertiesChanged(resolvedLayoutDirection);
13099
13100        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
13101    }
13102
13103    /**
13104     * Reset the resolved layout direction.
13105     *
13106     * @hide
13107     */
13108    public void resetResolvedPadding() {
13109        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
13110    }
13111
13112    /**
13113     * This is called when the view is detached from a window.  At this point it
13114     * no longer has a surface for drawing.
13115     *
13116     * @see #onAttachedToWindow()
13117     */
13118    protected void onDetachedFromWindow() {
13119    }
13120
13121    /**
13122     * This is a framework-internal mirror of onDetachedFromWindow() that's called
13123     * after onDetachedFromWindow().
13124     *
13125     * If you override this you *MUST* call super.onDetachedFromWindowInternal()!
13126     * The super method should be called at the end of the overriden method to ensure
13127     * subclasses are destroyed first
13128     *
13129     * @hide
13130     */
13131    protected void onDetachedFromWindowInternal() {
13132        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
13133        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
13134
13135        removeUnsetPressCallback();
13136        removeLongPressCallback();
13137        removePerformClickCallback();
13138        removeSendViewScrolledAccessibilityEventCallback();
13139
13140        destroyDrawingCache();
13141        destroyLayer(false);
13142
13143        cleanupDraw();
13144
13145        mCurrentAnimation = null;
13146    }
13147
13148    private void cleanupDraw() {
13149        resetDisplayList();
13150        if (mAttachInfo != null) {
13151            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
13152        }
13153    }
13154
13155    /**
13156     * This method ensures the hardware renderer is in a valid state
13157     * before executing the specified action.
13158     *
13159     * This method will attempt to set a valid state even if the window
13160     * the renderer is attached to was destroyed.
13161     *
13162     * This method is not guaranteed to work. If the hardware renderer
13163     * does not exist or cannot be put in a valid state, this method
13164     * will not executed the specified action.
13165     *
13166     * The specified action is executed synchronously.
13167     *
13168     * @param action The action to execute after the renderer is in a valid state
13169     *
13170     * @return True if the specified Runnable was executed, false otherwise
13171     *
13172     * @hide
13173     */
13174    public boolean executeHardwareAction(Runnable action) {
13175        //noinspection SimplifiableIfStatement
13176        if (mAttachInfo != null && mAttachInfo.mHardwareRenderer != null) {
13177            return mAttachInfo.mHardwareRenderer.safelyRun(action);
13178        }
13179        return false;
13180    }
13181
13182    void invalidateInheritedLayoutMode(int layoutModeOfRoot) {
13183    }
13184
13185    /**
13186     * @return The number of times this view has been attached to a window
13187     */
13188    protected int getWindowAttachCount() {
13189        return mWindowAttachCount;
13190    }
13191
13192    /**
13193     * Retrieve a unique token identifying the window this view is attached to.
13194     * @return Return the window's token for use in
13195     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
13196     */
13197    public IBinder getWindowToken() {
13198        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
13199    }
13200
13201    /**
13202     * Retrieve the {@link WindowId} for the window this view is
13203     * currently attached to.
13204     */
13205    public WindowId getWindowId() {
13206        if (mAttachInfo == null) {
13207            return null;
13208        }
13209        if (mAttachInfo.mWindowId == null) {
13210            try {
13211                mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId(
13212                        mAttachInfo.mWindowToken);
13213                mAttachInfo.mWindowId = new WindowId(
13214                        mAttachInfo.mIWindowId);
13215            } catch (RemoteException e) {
13216            }
13217        }
13218        return mAttachInfo.mWindowId;
13219    }
13220
13221    /**
13222     * Retrieve a unique token identifying the top-level "real" window of
13223     * the window that this view is attached to.  That is, this is like
13224     * {@link #getWindowToken}, except if the window this view in is a panel
13225     * window (attached to another containing window), then the token of
13226     * the containing window is returned instead.
13227     *
13228     * @return Returns the associated window token, either
13229     * {@link #getWindowToken()} or the containing window's token.
13230     */
13231    public IBinder getApplicationWindowToken() {
13232        AttachInfo ai = mAttachInfo;
13233        if (ai != null) {
13234            IBinder appWindowToken = ai.mPanelParentWindowToken;
13235            if (appWindowToken == null) {
13236                appWindowToken = ai.mWindowToken;
13237            }
13238            return appWindowToken;
13239        }
13240        return null;
13241    }
13242
13243    /**
13244     * Gets the logical display to which the view's window has been attached.
13245     *
13246     * @return The logical display, or null if the view is not currently attached to a window.
13247     */
13248    public Display getDisplay() {
13249        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
13250    }
13251
13252    /**
13253     * Retrieve private session object this view hierarchy is using to
13254     * communicate with the window manager.
13255     * @return the session object to communicate with the window manager
13256     */
13257    /*package*/ IWindowSession getWindowSession() {
13258        return mAttachInfo != null ? mAttachInfo.mSession : null;
13259    }
13260
13261    /**
13262     * @param info the {@link android.view.View.AttachInfo} to associated with
13263     *        this view
13264     */
13265    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
13266        //System.out.println("Attached! " + this);
13267        mAttachInfo = info;
13268        if (mOverlay != null) {
13269            mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
13270        }
13271        mWindowAttachCount++;
13272        // We will need to evaluate the drawable state at least once.
13273        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
13274        if (mFloatingTreeObserver != null) {
13275            info.mTreeObserver.merge(mFloatingTreeObserver);
13276            mFloatingTreeObserver = null;
13277        }
13278        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
13279            mAttachInfo.mScrollContainers.add(this);
13280            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
13281        }
13282        performCollectViewAttributes(mAttachInfo, visibility);
13283        onAttachedToWindow();
13284
13285        ListenerInfo li = mListenerInfo;
13286        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
13287                li != null ? li.mOnAttachStateChangeListeners : null;
13288        if (listeners != null && listeners.size() > 0) {
13289            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
13290            // perform the dispatching. The iterator is a safe guard against listeners that
13291            // could mutate the list by calling the various add/remove methods. This prevents
13292            // the array from being modified while we iterate it.
13293            for (OnAttachStateChangeListener listener : listeners) {
13294                listener.onViewAttachedToWindow(this);
13295            }
13296        }
13297
13298        int vis = info.mWindowVisibility;
13299        if (vis != GONE) {
13300            onWindowVisibilityChanged(vis);
13301        }
13302        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
13303            // If nobody has evaluated the drawable state yet, then do it now.
13304            refreshDrawableState();
13305        }
13306        needGlobalAttributesUpdate(false);
13307    }
13308
13309    void dispatchDetachedFromWindow() {
13310        AttachInfo info = mAttachInfo;
13311        if (info != null) {
13312            int vis = info.mWindowVisibility;
13313            if (vis != GONE) {
13314                onWindowVisibilityChanged(GONE);
13315            }
13316        }
13317
13318        onDetachedFromWindow();
13319        onDetachedFromWindowInternal();
13320
13321        ListenerInfo li = mListenerInfo;
13322        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
13323                li != null ? li.mOnAttachStateChangeListeners : null;
13324        if (listeners != null && listeners.size() > 0) {
13325            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
13326            // perform the dispatching. The iterator is a safe guard against listeners that
13327            // could mutate the list by calling the various add/remove methods. This prevents
13328            // the array from being modified while we iterate it.
13329            for (OnAttachStateChangeListener listener : listeners) {
13330                listener.onViewDetachedFromWindow(this);
13331            }
13332        }
13333
13334        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
13335            mAttachInfo.mScrollContainers.remove(this);
13336            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
13337        }
13338
13339        mAttachInfo = null;
13340        if (mOverlay != null) {
13341            mOverlay.getOverlayView().dispatchDetachedFromWindow();
13342        }
13343    }
13344
13345    /**
13346     * Cancel any deferred high-level input events that were previously posted to the event queue.
13347     *
13348     * <p>Many views post high-level events such as click handlers to the event queue
13349     * to run deferred in order to preserve a desired user experience - clearing visible
13350     * pressed states before executing, etc. This method will abort any events of this nature
13351     * that are currently in flight.</p>
13352     *
13353     * <p>Custom views that generate their own high-level deferred input events should override
13354     * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p>
13355     *
13356     * <p>This will also cancel pending input events for any child views.</p>
13357     *
13358     * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases.
13359     * This will not impact newer events posted after this call that may occur as a result of
13360     * lower-level input events still waiting in the queue. If you are trying to prevent
13361     * double-submitted  events for the duration of some sort of asynchronous transaction
13362     * you should also take other steps to protect against unexpected double inputs e.g. calling
13363     * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when
13364     * the transaction completes, tracking already submitted transaction IDs, etc.</p>
13365     */
13366    public final void cancelPendingInputEvents() {
13367        dispatchCancelPendingInputEvents();
13368    }
13369
13370    /**
13371     * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight.
13372     * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling.
13373     */
13374    void dispatchCancelPendingInputEvents() {
13375        mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER;
13376        onCancelPendingInputEvents();
13377        if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) {
13378            throw new SuperNotCalledException("View " + getClass().getSimpleName() +
13379                    " did not call through to super.onCancelPendingInputEvents()");
13380        }
13381    }
13382
13383    /**
13384     * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or
13385     * a parent view.
13386     *
13387     * <p>This method is responsible for removing any pending high-level input events that were
13388     * posted to the event queue to run later. Custom view classes that post their own deferred
13389     * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or
13390     * {@link android.os.Handler} should override this method, call
13391     * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate.
13392     * </p>
13393     */
13394    public void onCancelPendingInputEvents() {
13395        removePerformClickCallback();
13396        cancelLongPress();
13397        mPrivateFlags3 |= PFLAG3_CALLED_SUPER;
13398    }
13399
13400    /**
13401     * Store this view hierarchy's frozen state into the given container.
13402     *
13403     * @param container The SparseArray in which to save the view's state.
13404     *
13405     * @see #restoreHierarchyState(android.util.SparseArray)
13406     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13407     * @see #onSaveInstanceState()
13408     */
13409    public void saveHierarchyState(SparseArray<Parcelable> container) {
13410        dispatchSaveInstanceState(container);
13411    }
13412
13413    /**
13414     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
13415     * this view and its children. May be overridden to modify how freezing happens to a
13416     * view's children; for example, some views may want to not store state for their children.
13417     *
13418     * @param container The SparseArray in which to save the view's state.
13419     *
13420     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13421     * @see #saveHierarchyState(android.util.SparseArray)
13422     * @see #onSaveInstanceState()
13423     */
13424    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
13425        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
13426            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
13427            Parcelable state = onSaveInstanceState();
13428            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
13429                throw new IllegalStateException(
13430                        "Derived class did not call super.onSaveInstanceState()");
13431            }
13432            if (state != null) {
13433                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
13434                // + ": " + state);
13435                container.put(mID, state);
13436            }
13437        }
13438    }
13439
13440    /**
13441     * Hook allowing a view to generate a representation of its internal state
13442     * that can later be used to create a new instance with that same state.
13443     * This state should only contain information that is not persistent or can
13444     * not be reconstructed later. For example, you will never store your
13445     * current position on screen because that will be computed again when a
13446     * new instance of the view is placed in its view hierarchy.
13447     * <p>
13448     * Some examples of things you may store here: the current cursor position
13449     * in a text view (but usually not the text itself since that is stored in a
13450     * content provider or other persistent storage), the currently selected
13451     * item in a list view.
13452     *
13453     * @return Returns a Parcelable object containing the view's current dynamic
13454     *         state, or null if there is nothing interesting to save. The
13455     *         default implementation returns null.
13456     * @see #onRestoreInstanceState(android.os.Parcelable)
13457     * @see #saveHierarchyState(android.util.SparseArray)
13458     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13459     * @see #setSaveEnabled(boolean)
13460     */
13461    protected Parcelable onSaveInstanceState() {
13462        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
13463        return BaseSavedState.EMPTY_STATE;
13464    }
13465
13466    /**
13467     * Restore this view hierarchy's frozen state from the given container.
13468     *
13469     * @param container The SparseArray which holds previously frozen states.
13470     *
13471     * @see #saveHierarchyState(android.util.SparseArray)
13472     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13473     * @see #onRestoreInstanceState(android.os.Parcelable)
13474     */
13475    public void restoreHierarchyState(SparseArray<Parcelable> container) {
13476        dispatchRestoreInstanceState(container);
13477    }
13478
13479    /**
13480     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
13481     * state for this view and its children. May be overridden to modify how restoring
13482     * happens to a view's children; for example, some views may want to not store state
13483     * for their children.
13484     *
13485     * @param container The SparseArray which holds previously saved state.
13486     *
13487     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13488     * @see #restoreHierarchyState(android.util.SparseArray)
13489     * @see #onRestoreInstanceState(android.os.Parcelable)
13490     */
13491    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
13492        if (mID != NO_ID) {
13493            Parcelable state = container.get(mID);
13494            if (state != null) {
13495                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
13496                // + ": " + state);
13497                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
13498                onRestoreInstanceState(state);
13499                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
13500                    throw new IllegalStateException(
13501                            "Derived class did not call super.onRestoreInstanceState()");
13502                }
13503            }
13504        }
13505    }
13506
13507    /**
13508     * Hook allowing a view to re-apply a representation of its internal state that had previously
13509     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
13510     * null state.
13511     *
13512     * @param state The frozen state that had previously been returned by
13513     *        {@link #onSaveInstanceState}.
13514     *
13515     * @see #onSaveInstanceState()
13516     * @see #restoreHierarchyState(android.util.SparseArray)
13517     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13518     */
13519    protected void onRestoreInstanceState(Parcelable state) {
13520        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
13521        if (state != BaseSavedState.EMPTY_STATE && state != null) {
13522            throw new IllegalArgumentException("Wrong state class, expecting View State but "
13523                    + "received " + state.getClass().toString() + " instead. This usually happens "
13524                    + "when two views of different type have the same id in the same hierarchy. "
13525                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
13526                    + "other views do not use the same id.");
13527        }
13528    }
13529
13530    /**
13531     * <p>Return the time at which the drawing of the view hierarchy started.</p>
13532     *
13533     * @return the drawing start time in milliseconds
13534     */
13535    public long getDrawingTime() {
13536        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
13537    }
13538
13539    /**
13540     * <p>Enables or disables the duplication of the parent's state into this view. When
13541     * duplication is enabled, this view gets its drawable state from its parent rather
13542     * than from its own internal properties.</p>
13543     *
13544     * <p>Note: in the current implementation, setting this property to true after the
13545     * view was added to a ViewGroup might have no effect at all. This property should
13546     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
13547     *
13548     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
13549     * property is enabled, an exception will be thrown.</p>
13550     *
13551     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
13552     * parent, these states should not be affected by this method.</p>
13553     *
13554     * @param enabled True to enable duplication of the parent's drawable state, false
13555     *                to disable it.
13556     *
13557     * @see #getDrawableState()
13558     * @see #isDuplicateParentStateEnabled()
13559     */
13560    public void setDuplicateParentStateEnabled(boolean enabled) {
13561        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
13562    }
13563
13564    /**
13565     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
13566     *
13567     * @return True if this view's drawable state is duplicated from the parent,
13568     *         false otherwise
13569     *
13570     * @see #getDrawableState()
13571     * @see #setDuplicateParentStateEnabled(boolean)
13572     */
13573    public boolean isDuplicateParentStateEnabled() {
13574        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
13575    }
13576
13577    /**
13578     * <p>Specifies the type of layer backing this view. The layer can be
13579     * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13580     * {@link #LAYER_TYPE_HARDWARE}.</p>
13581     *
13582     * <p>A layer is associated with an optional {@link android.graphics.Paint}
13583     * instance that controls how the layer is composed on screen. The following
13584     * properties of the paint are taken into account when composing the layer:</p>
13585     * <ul>
13586     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
13587     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
13588     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
13589     * </ul>
13590     *
13591     * <p>If this view has an alpha value set to < 1.0 by calling
13592     * {@link #setAlpha(float)}, the alpha value of the layer's paint is superceded
13593     * by this view's alpha value.</p>
13594     *
13595     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE},
13596     * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE}
13597     * for more information on when and how to use layers.</p>
13598     *
13599     * @param layerType The type of layer to use with this view, must be one of
13600     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13601     *        {@link #LAYER_TYPE_HARDWARE}
13602     * @param paint The paint used to compose the layer. This argument is optional
13603     *        and can be null. It is ignored when the layer type is
13604     *        {@link #LAYER_TYPE_NONE}
13605     *
13606     * @see #getLayerType()
13607     * @see #LAYER_TYPE_NONE
13608     * @see #LAYER_TYPE_SOFTWARE
13609     * @see #LAYER_TYPE_HARDWARE
13610     * @see #setAlpha(float)
13611     *
13612     * @attr ref android.R.styleable#View_layerType
13613     */
13614    public void setLayerType(int layerType, Paint paint) {
13615        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
13616            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
13617                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
13618        }
13619
13620        if (layerType == mLayerType) {
13621            setLayerPaint(paint);
13622            return;
13623        }
13624
13625        // Destroy any previous software drawing cache if needed
13626        switch (mLayerType) {
13627            case LAYER_TYPE_HARDWARE:
13628                destroyLayer(false);
13629                // fall through - non-accelerated views may use software layer mechanism instead
13630            case LAYER_TYPE_SOFTWARE:
13631                destroyDrawingCache();
13632                break;
13633            default:
13634                break;
13635        }
13636
13637        mLayerType = layerType;
13638        final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE;
13639        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
13640        mLocalDirtyRect = layerDisabled ? null : new Rect();
13641
13642        invalidateParentCaches();
13643        invalidate(true);
13644    }
13645
13646    /**
13647     * Updates the {@link Paint} object used with the current layer (used only if the current
13648     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
13649     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
13650     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
13651     * ensure that the view gets redrawn immediately.
13652     *
13653     * <p>A layer is associated with an optional {@link android.graphics.Paint}
13654     * instance that controls how the layer is composed on screen. The following
13655     * properties of the paint are taken into account when composing the layer:</p>
13656     * <ul>
13657     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
13658     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
13659     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
13660     * </ul>
13661     *
13662     * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the
13663     * alpha value of the layer's paint is superceded by this view's alpha value.</p>
13664     *
13665     * @param paint The paint used to compose the layer. This argument is optional
13666     *        and can be null. It is ignored when the layer type is
13667     *        {@link #LAYER_TYPE_NONE}
13668     *
13669     * @see #setLayerType(int, android.graphics.Paint)
13670     */
13671    public void setLayerPaint(Paint paint) {
13672        int layerType = getLayerType();
13673        if (layerType != LAYER_TYPE_NONE) {
13674            mLayerPaint = paint == null ? new Paint() : paint;
13675            if (layerType == LAYER_TYPE_HARDWARE) {
13676                HardwareLayer layer = getHardwareLayer();
13677                if (layer != null) {
13678                    layer.setLayerPaint(mLayerPaint);
13679                }
13680                invalidateViewProperty(false, false);
13681            } else {
13682                invalidate();
13683            }
13684        }
13685    }
13686
13687    /**
13688     * Indicates whether this view has a static layer. A view with layer type
13689     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
13690     * dynamic.
13691     */
13692    boolean hasStaticLayer() {
13693        return true;
13694    }
13695
13696    /**
13697     * Indicates what type of layer is currently associated with this view. By default
13698     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
13699     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
13700     * for more information on the different types of layers.
13701     *
13702     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13703     *         {@link #LAYER_TYPE_HARDWARE}
13704     *
13705     * @see #setLayerType(int, android.graphics.Paint)
13706     * @see #buildLayer()
13707     * @see #LAYER_TYPE_NONE
13708     * @see #LAYER_TYPE_SOFTWARE
13709     * @see #LAYER_TYPE_HARDWARE
13710     */
13711    public int getLayerType() {
13712        return mLayerType;
13713    }
13714
13715    /**
13716     * Forces this view's layer to be created and this view to be rendered
13717     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
13718     * invoking this method will have no effect.
13719     *
13720     * This method can for instance be used to render a view into its layer before
13721     * starting an animation. If this view is complex, rendering into the layer
13722     * before starting the animation will avoid skipping frames.
13723     *
13724     * @throws IllegalStateException If this view is not attached to a window
13725     *
13726     * @see #setLayerType(int, android.graphics.Paint)
13727     */
13728    public void buildLayer() {
13729        if (mLayerType == LAYER_TYPE_NONE) return;
13730
13731        final AttachInfo attachInfo = mAttachInfo;
13732        if (attachInfo == null) {
13733            throw new IllegalStateException("This view must be attached to a window first");
13734        }
13735
13736        switch (mLayerType) {
13737            case LAYER_TYPE_HARDWARE:
13738                getHardwareLayer();
13739                // TODO: We need a better way to handle this case
13740                // If views have registered pre-draw listeners they need
13741                // to be notified before we build the layer. Those listeners
13742                // may however rely on other events to happen first so we
13743                // cannot just invoke them here until they don't cancel the
13744                // current frame
13745                if (!attachInfo.mTreeObserver.hasOnPreDrawListeners()) {
13746                    attachInfo.mViewRootImpl.dispatchFlushHardwareLayerUpdates();
13747                }
13748                break;
13749            case LAYER_TYPE_SOFTWARE:
13750                buildDrawingCache(true);
13751                break;
13752        }
13753    }
13754
13755    /**
13756     * <p>Returns a hardware layer that can be used to draw this view again
13757     * without executing its draw method.</p>
13758     *
13759     * @return A HardwareLayer ready to render, or null if an error occurred.
13760     */
13761    HardwareLayer getHardwareLayer() {
13762        if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null ||
13763                !mAttachInfo.mHardwareRenderer.isEnabled()) {
13764            return null;
13765        }
13766
13767        final int width = mRight - mLeft;
13768        final int height = mBottom - mTop;
13769
13770        if (width == 0 || height == 0) {
13771            return null;
13772        }
13773
13774        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
13775            if (mHardwareLayer == null) {
13776                mHardwareLayer = mAttachInfo.mHardwareRenderer.createDisplayListLayer(
13777                        width, height);
13778                mLocalDirtyRect.set(0, 0, width, height);
13779            } else if (mHardwareLayer.isValid()) {
13780                // This should not be necessary but applications that change
13781                // the parameters of their background drawable without calling
13782                // this.setBackground(Drawable) can leave the view in a bad state
13783                // (for instance isOpaque() returns true, but the background is
13784                // not opaque.)
13785                computeOpaqueFlags();
13786
13787                if (mHardwareLayer.prepare(width, height, isOpaque())) {
13788                    mLocalDirtyRect.set(0, 0, width, height);
13789                }
13790            }
13791
13792            // The layer is not valid if the underlying GPU resources cannot be allocated
13793            mHardwareLayer.flushChanges();
13794            if (!mHardwareLayer.isValid()) {
13795                return null;
13796            }
13797
13798            mHardwareLayer.setLayerPaint(mLayerPaint);
13799            DisplayList displayList = mHardwareLayer.startRecording();
13800            if (getDisplayList(displayList, true) != displayList) {
13801                throw new IllegalStateException("getDisplayList() didn't return"
13802                        + " the input displaylist for a hardware layer!");
13803            }
13804            mHardwareLayer.endRecording(mLocalDirtyRect);
13805            mLocalDirtyRect.setEmpty();
13806        }
13807
13808        return mHardwareLayer;
13809    }
13810
13811    /**
13812     * Destroys this View's hardware layer if possible.
13813     *
13814     * @return True if the layer was destroyed, false otherwise.
13815     *
13816     * @see #setLayerType(int, android.graphics.Paint)
13817     * @see #LAYER_TYPE_HARDWARE
13818     */
13819    boolean destroyLayer(boolean valid) {
13820        if (mHardwareLayer != null) {
13821            mHardwareLayer.destroy();
13822            mHardwareLayer = null;
13823
13824            invalidate(true);
13825            invalidateParentCaches();
13826            return true;
13827        }
13828        return false;
13829    }
13830
13831    /**
13832     * Destroys all hardware rendering resources. This method is invoked
13833     * when the system needs to reclaim resources. Upon execution of this
13834     * method, you should free any OpenGL resources created by the view.
13835     *
13836     * Note: you <strong>must</strong> call
13837     * <code>super.destroyHardwareResources()</code> when overriding
13838     * this method.
13839     *
13840     * @hide
13841     */
13842    protected void destroyHardwareResources() {
13843        resetDisplayList();
13844        destroyLayer(true);
13845    }
13846
13847    /**
13848     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
13849     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
13850     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
13851     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
13852     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
13853     * null.</p>
13854     *
13855     * <p>Enabling the drawing cache is similar to
13856     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
13857     * acceleration is turned off. When hardware acceleration is turned on, enabling the
13858     * drawing cache has no effect on rendering because the system uses a different mechanism
13859     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
13860     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
13861     * for information on how to enable software and hardware layers.</p>
13862     *
13863     * <p>This API can be used to manually generate
13864     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
13865     * {@link #getDrawingCache()}.</p>
13866     *
13867     * @param enabled true to enable the drawing cache, false otherwise
13868     *
13869     * @see #isDrawingCacheEnabled()
13870     * @see #getDrawingCache()
13871     * @see #buildDrawingCache()
13872     * @see #setLayerType(int, android.graphics.Paint)
13873     */
13874    public void setDrawingCacheEnabled(boolean enabled) {
13875        mCachingFailed = false;
13876        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
13877    }
13878
13879    /**
13880     * <p>Indicates whether the drawing cache is enabled for this view.</p>
13881     *
13882     * @return true if the drawing cache is enabled
13883     *
13884     * @see #setDrawingCacheEnabled(boolean)
13885     * @see #getDrawingCache()
13886     */
13887    @ViewDebug.ExportedProperty(category = "drawing")
13888    public boolean isDrawingCacheEnabled() {
13889        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
13890    }
13891
13892    /**
13893     * Debugging utility which recursively outputs the dirty state of a view and its
13894     * descendants.
13895     *
13896     * @hide
13897     */
13898    @SuppressWarnings({"UnusedDeclaration"})
13899    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
13900        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
13901                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
13902                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
13903                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
13904        if (clear) {
13905            mPrivateFlags &= clearMask;
13906        }
13907        if (this instanceof ViewGroup) {
13908            ViewGroup parent = (ViewGroup) this;
13909            final int count = parent.getChildCount();
13910            for (int i = 0; i < count; i++) {
13911                final View child = parent.getChildAt(i);
13912                child.outputDirtyFlags(indent + "  ", clear, clearMask);
13913            }
13914        }
13915    }
13916
13917    /**
13918     * This method is used by ViewGroup to cause its children to restore or recreate their
13919     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
13920     * to recreate its own display list, which would happen if it went through the normal
13921     * draw/dispatchDraw mechanisms.
13922     *
13923     * @hide
13924     */
13925    protected void dispatchGetDisplayList() {}
13926
13927    /**
13928     * A view that is not attached or hardware accelerated cannot create a display list.
13929     * This method checks these conditions and returns the appropriate result.
13930     *
13931     * @return true if view has the ability to create a display list, false otherwise.
13932     *
13933     * @hide
13934     */
13935    public boolean canHaveDisplayList() {
13936        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
13937    }
13938
13939    /**
13940     * Returns a DisplayList. If the incoming displayList is null, one will be created.
13941     * Otherwise, the same display list will be returned (after having been rendered into
13942     * along the way, depending on the invalidation state of the view).
13943     *
13944     * @param displayList The previous version of this displayList, could be null.
13945     * @param isLayer Whether the requester of the display list is a layer. If so,
13946     * the view will avoid creating a layer inside the resulting display list.
13947     * @return A new or reused DisplayList object.
13948     */
13949    private DisplayList getDisplayList(DisplayList displayList, boolean isLayer) {
13950        if (!canHaveDisplayList()) {
13951            return null;
13952        }
13953
13954        if (((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 ||
13955                displayList == null || !displayList.isValid() ||
13956                (!isLayer && mRecreateDisplayList))) {
13957            // Don't need to recreate the display list, just need to tell our
13958            // children to restore/recreate theirs
13959            if (displayList != null && displayList.isValid() &&
13960                    !isLayer && !mRecreateDisplayList) {
13961                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13962                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13963                dispatchGetDisplayList();
13964
13965                return displayList;
13966            }
13967
13968            if (!isLayer) {
13969                // If we got here, we're recreating it. Mark it as such to ensure that
13970                // we copy in child display lists into ours in drawChild()
13971                mRecreateDisplayList = true;
13972            }
13973            if (displayList == null) {
13974                displayList = DisplayList.create(getClass().getName());
13975                // If we're creating a new display list, make sure our parent gets invalidated
13976                // since they will need to recreate their display list to account for this
13977                // new child display list.
13978                invalidateParentCaches();
13979            }
13980
13981            boolean caching = false;
13982            int width = mRight - mLeft;
13983            int height = mBottom - mTop;
13984            int layerType = getLayerType();
13985
13986            final HardwareCanvas canvas = displayList.start(width, height);
13987
13988            try {
13989                if (!isLayer && layerType != LAYER_TYPE_NONE) {
13990                    if (layerType == LAYER_TYPE_HARDWARE) {
13991                        final HardwareLayer layer = getHardwareLayer();
13992                        if (layer != null && layer.isValid()) {
13993                            canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
13994                        } else {
13995                            canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint,
13996                                    Canvas.HAS_ALPHA_LAYER_SAVE_FLAG |
13997                                            Canvas.CLIP_TO_LAYER_SAVE_FLAG);
13998                        }
13999                        caching = true;
14000                    } else {
14001                        buildDrawingCache(true);
14002                        Bitmap cache = getDrawingCache(true);
14003                        if (cache != null) {
14004                            canvas.drawBitmap(cache, 0, 0, mLayerPaint);
14005                            caching = true;
14006                        }
14007                    }
14008                } else {
14009
14010                    computeScroll();
14011
14012                    canvas.translate(-mScrollX, -mScrollY);
14013                    if (!isLayer) {
14014                        mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
14015                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14016                    }
14017
14018                    // Fast path for layouts with no backgrounds
14019                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14020                        dispatchDraw(canvas);
14021                        if (mOverlay != null && !mOverlay.isEmpty()) {
14022                            mOverlay.getOverlayView().draw(canvas);
14023                        }
14024                    } else {
14025                        draw(canvas);
14026                    }
14027                }
14028            } finally {
14029                displayList.end(getHardwareRenderer(), canvas);
14030                displayList.setCaching(caching);
14031                if (isLayer) {
14032                    displayList.setLeftTopRightBottom(0, 0, width, height);
14033                } else {
14034                    setDisplayListProperties(displayList);
14035                }
14036            }
14037        } else if (!isLayer) {
14038            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
14039            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14040        }
14041
14042        return displayList;
14043    }
14044
14045    /**
14046     * <p>Returns a display list that can be used to draw this view again
14047     * without executing its draw method.</p>
14048     *
14049     * @return A DisplayList ready to replay, or null if caching is not enabled.
14050     *
14051     * @hide
14052     */
14053    public DisplayList getDisplayList() {
14054        mDisplayList = getDisplayList(mDisplayList, false);
14055        return mDisplayList;
14056    }
14057
14058    private void resetDisplayList() {
14059        HardwareRenderer renderer = getHardwareRenderer();
14060        if (mDisplayList != null && mDisplayList.isValid()) {
14061            mDisplayList.destroyDisplayListData(renderer);
14062        }
14063
14064        if (mBackgroundDisplayList != null && mBackgroundDisplayList.isValid()) {
14065            mBackgroundDisplayList.destroyDisplayListData(renderer);
14066        }
14067    }
14068
14069    /**
14070     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
14071     *
14072     * @return A non-scaled bitmap representing this view or null if cache is disabled.
14073     *
14074     * @see #getDrawingCache(boolean)
14075     */
14076    public Bitmap getDrawingCache() {
14077        return getDrawingCache(false);
14078    }
14079
14080    /**
14081     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
14082     * is null when caching is disabled. If caching is enabled and the cache is not ready,
14083     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
14084     * draw from the cache when the cache is enabled. To benefit from the cache, you must
14085     * request the drawing cache by calling this method and draw it on screen if the
14086     * returned bitmap is not null.</p>
14087     *
14088     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
14089     * this method will create a bitmap of the same size as this view. Because this bitmap
14090     * will be drawn scaled by the parent ViewGroup, the result on screen might show
14091     * scaling artifacts. To avoid such artifacts, you should call this method by setting
14092     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
14093     * size than the view. This implies that your application must be able to handle this
14094     * size.</p>
14095     *
14096     * @param autoScale Indicates whether the generated bitmap should be scaled based on
14097     *        the current density of the screen when the application is in compatibility
14098     *        mode.
14099     *
14100     * @return A bitmap representing this view or null if cache is disabled.
14101     *
14102     * @see #setDrawingCacheEnabled(boolean)
14103     * @see #isDrawingCacheEnabled()
14104     * @see #buildDrawingCache(boolean)
14105     * @see #destroyDrawingCache()
14106     */
14107    public Bitmap getDrawingCache(boolean autoScale) {
14108        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
14109            return null;
14110        }
14111        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
14112            buildDrawingCache(autoScale);
14113        }
14114        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
14115    }
14116
14117    /**
14118     * <p>Frees the resources used by the drawing cache. If you call
14119     * {@link #buildDrawingCache()} manually without calling
14120     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
14121     * should cleanup the cache with this method afterwards.</p>
14122     *
14123     * @see #setDrawingCacheEnabled(boolean)
14124     * @see #buildDrawingCache()
14125     * @see #getDrawingCache()
14126     */
14127    public void destroyDrawingCache() {
14128        if (mDrawingCache != null) {
14129            mDrawingCache.recycle();
14130            mDrawingCache = null;
14131        }
14132        if (mUnscaledDrawingCache != null) {
14133            mUnscaledDrawingCache.recycle();
14134            mUnscaledDrawingCache = null;
14135        }
14136    }
14137
14138    /**
14139     * Setting a solid background color for the drawing cache's bitmaps will improve
14140     * performance and memory usage. Note, though that this should only be used if this
14141     * view will always be drawn on top of a solid color.
14142     *
14143     * @param color The background color to use for the drawing cache's bitmap
14144     *
14145     * @see #setDrawingCacheEnabled(boolean)
14146     * @see #buildDrawingCache()
14147     * @see #getDrawingCache()
14148     */
14149    public void setDrawingCacheBackgroundColor(int color) {
14150        if (color != mDrawingCacheBackgroundColor) {
14151            mDrawingCacheBackgroundColor = color;
14152            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
14153        }
14154    }
14155
14156    /**
14157     * @see #setDrawingCacheBackgroundColor(int)
14158     *
14159     * @return The background color to used for the drawing cache's bitmap
14160     */
14161    public int getDrawingCacheBackgroundColor() {
14162        return mDrawingCacheBackgroundColor;
14163    }
14164
14165    /**
14166     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
14167     *
14168     * @see #buildDrawingCache(boolean)
14169     */
14170    public void buildDrawingCache() {
14171        buildDrawingCache(false);
14172    }
14173
14174    /**
14175     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
14176     *
14177     * <p>If you call {@link #buildDrawingCache()} manually without calling
14178     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
14179     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
14180     *
14181     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
14182     * this method will create a bitmap of the same size as this view. Because this bitmap
14183     * will be drawn scaled by the parent ViewGroup, the result on screen might show
14184     * scaling artifacts. To avoid such artifacts, you should call this method by setting
14185     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
14186     * size than the view. This implies that your application must be able to handle this
14187     * size.</p>
14188     *
14189     * <p>You should avoid calling this method when hardware acceleration is enabled. If
14190     * you do not need the drawing cache bitmap, calling this method will increase memory
14191     * usage and cause the view to be rendered in software once, thus negatively impacting
14192     * performance.</p>
14193     *
14194     * @see #getDrawingCache()
14195     * @see #destroyDrawingCache()
14196     */
14197    public void buildDrawingCache(boolean autoScale) {
14198        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
14199                mDrawingCache == null : mUnscaledDrawingCache == null)) {
14200            mCachingFailed = false;
14201
14202            int width = mRight - mLeft;
14203            int height = mBottom - mTop;
14204
14205            final AttachInfo attachInfo = mAttachInfo;
14206            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
14207
14208            if (autoScale && scalingRequired) {
14209                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
14210                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
14211            }
14212
14213            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
14214            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
14215            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
14216
14217            final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
14218            final long drawingCacheSize =
14219                    ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
14220            if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
14221                if (width > 0 && height > 0) {
14222                    Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs "
14223                            + projectedBitmapSize + " bytes, only "
14224                            + drawingCacheSize + " available");
14225                }
14226                destroyDrawingCache();
14227                mCachingFailed = true;
14228                return;
14229            }
14230
14231            boolean clear = true;
14232            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
14233
14234            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
14235                Bitmap.Config quality;
14236                if (!opaque) {
14237                    // Never pick ARGB_4444 because it looks awful
14238                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
14239                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
14240                        case DRAWING_CACHE_QUALITY_AUTO:
14241                        case DRAWING_CACHE_QUALITY_LOW:
14242                        case DRAWING_CACHE_QUALITY_HIGH:
14243                        default:
14244                            quality = Bitmap.Config.ARGB_8888;
14245                            break;
14246                    }
14247                } else {
14248                    // Optimization for translucent windows
14249                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
14250                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
14251                }
14252
14253                // Try to cleanup memory
14254                if (bitmap != null) bitmap.recycle();
14255
14256                try {
14257                    bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
14258                            width, height, quality);
14259                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
14260                    if (autoScale) {
14261                        mDrawingCache = bitmap;
14262                    } else {
14263                        mUnscaledDrawingCache = bitmap;
14264                    }
14265                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
14266                } catch (OutOfMemoryError e) {
14267                    // If there is not enough memory to create the bitmap cache, just
14268                    // ignore the issue as bitmap caches are not required to draw the
14269                    // view hierarchy
14270                    if (autoScale) {
14271                        mDrawingCache = null;
14272                    } else {
14273                        mUnscaledDrawingCache = null;
14274                    }
14275                    mCachingFailed = true;
14276                    return;
14277                }
14278
14279                clear = drawingCacheBackgroundColor != 0;
14280            }
14281
14282            Canvas canvas;
14283            if (attachInfo != null) {
14284                canvas = attachInfo.mCanvas;
14285                if (canvas == null) {
14286                    canvas = new Canvas();
14287                }
14288                canvas.setBitmap(bitmap);
14289                // Temporarily clobber the cached Canvas in case one of our children
14290                // is also using a drawing cache. Without this, the children would
14291                // steal the canvas by attaching their own bitmap to it and bad, bad
14292                // thing would happen (invisible views, corrupted drawings, etc.)
14293                attachInfo.mCanvas = null;
14294            } else {
14295                // This case should hopefully never or seldom happen
14296                canvas = new Canvas(bitmap);
14297            }
14298
14299            if (clear) {
14300                bitmap.eraseColor(drawingCacheBackgroundColor);
14301            }
14302
14303            computeScroll();
14304            final int restoreCount = canvas.save();
14305
14306            if (autoScale && scalingRequired) {
14307                final float scale = attachInfo.mApplicationScale;
14308                canvas.scale(scale, scale);
14309            }
14310
14311            canvas.translate(-mScrollX, -mScrollY);
14312
14313            mPrivateFlags |= PFLAG_DRAWN;
14314            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
14315                    mLayerType != LAYER_TYPE_NONE) {
14316                mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
14317            }
14318
14319            // Fast path for layouts with no backgrounds
14320            if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14321                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14322                dispatchDraw(canvas);
14323                if (mOverlay != null && !mOverlay.isEmpty()) {
14324                    mOverlay.getOverlayView().draw(canvas);
14325                }
14326            } else {
14327                draw(canvas);
14328            }
14329
14330            canvas.restoreToCount(restoreCount);
14331            canvas.setBitmap(null);
14332
14333            if (attachInfo != null) {
14334                // Restore the cached Canvas for our siblings
14335                attachInfo.mCanvas = canvas;
14336            }
14337        }
14338    }
14339
14340    /**
14341     * Create a snapshot of the view into a bitmap.  We should probably make
14342     * some form of this public, but should think about the API.
14343     */
14344    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
14345        int width = mRight - mLeft;
14346        int height = mBottom - mTop;
14347
14348        final AttachInfo attachInfo = mAttachInfo;
14349        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
14350        width = (int) ((width * scale) + 0.5f);
14351        height = (int) ((height * scale) + 0.5f);
14352
14353        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
14354                width > 0 ? width : 1, height > 0 ? height : 1, quality);
14355        if (bitmap == null) {
14356            throw new OutOfMemoryError();
14357        }
14358
14359        Resources resources = getResources();
14360        if (resources != null) {
14361            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
14362        }
14363
14364        Canvas canvas;
14365        if (attachInfo != null) {
14366            canvas = attachInfo.mCanvas;
14367            if (canvas == null) {
14368                canvas = new Canvas();
14369            }
14370            canvas.setBitmap(bitmap);
14371            // Temporarily clobber the cached Canvas in case one of our children
14372            // is also using a drawing cache. Without this, the children would
14373            // steal the canvas by attaching their own bitmap to it and bad, bad
14374            // things would happen (invisible views, corrupted drawings, etc.)
14375            attachInfo.mCanvas = null;
14376        } else {
14377            // This case should hopefully never or seldom happen
14378            canvas = new Canvas(bitmap);
14379        }
14380
14381        if ((backgroundColor & 0xff000000) != 0) {
14382            bitmap.eraseColor(backgroundColor);
14383        }
14384
14385        computeScroll();
14386        final int restoreCount = canvas.save();
14387        canvas.scale(scale, scale);
14388        canvas.translate(-mScrollX, -mScrollY);
14389
14390        // Temporarily remove the dirty mask
14391        int flags = mPrivateFlags;
14392        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14393
14394        // Fast path for layouts with no backgrounds
14395        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14396            dispatchDraw(canvas);
14397            if (mOverlay != null && !mOverlay.isEmpty()) {
14398                mOverlay.getOverlayView().draw(canvas);
14399            }
14400        } else {
14401            draw(canvas);
14402        }
14403
14404        mPrivateFlags = flags;
14405
14406        canvas.restoreToCount(restoreCount);
14407        canvas.setBitmap(null);
14408
14409        if (attachInfo != null) {
14410            // Restore the cached Canvas for our siblings
14411            attachInfo.mCanvas = canvas;
14412        }
14413
14414        return bitmap;
14415    }
14416
14417    /**
14418     * Indicates whether this View is currently in edit mode. A View is usually
14419     * in edit mode when displayed within a developer tool. For instance, if
14420     * this View is being drawn by a visual user interface builder, this method
14421     * should return true.
14422     *
14423     * Subclasses should check the return value of this method to provide
14424     * different behaviors if their normal behavior might interfere with the
14425     * host environment. For instance: the class spawns a thread in its
14426     * constructor, the drawing code relies on device-specific features, etc.
14427     *
14428     * This method is usually checked in the drawing code of custom widgets.
14429     *
14430     * @return True if this View is in edit mode, false otherwise.
14431     */
14432    public boolean isInEditMode() {
14433        return false;
14434    }
14435
14436    /**
14437     * If the View draws content inside its padding and enables fading edges,
14438     * it needs to support padding offsets. Padding offsets are added to the
14439     * fading edges to extend the length of the fade so that it covers pixels
14440     * drawn inside the padding.
14441     *
14442     * Subclasses of this class should override this method if they need
14443     * to draw content inside the padding.
14444     *
14445     * @return True if padding offset must be applied, false otherwise.
14446     *
14447     * @see #getLeftPaddingOffset()
14448     * @see #getRightPaddingOffset()
14449     * @see #getTopPaddingOffset()
14450     * @see #getBottomPaddingOffset()
14451     *
14452     * @since CURRENT
14453     */
14454    protected boolean isPaddingOffsetRequired() {
14455        return false;
14456    }
14457
14458    /**
14459     * Amount by which to extend the left fading region. Called only when
14460     * {@link #isPaddingOffsetRequired()} returns true.
14461     *
14462     * @return The left padding offset in pixels.
14463     *
14464     * @see #isPaddingOffsetRequired()
14465     *
14466     * @since CURRENT
14467     */
14468    protected int getLeftPaddingOffset() {
14469        return 0;
14470    }
14471
14472    /**
14473     * Amount by which to extend the right fading region. Called only when
14474     * {@link #isPaddingOffsetRequired()} returns true.
14475     *
14476     * @return The right padding offset in pixels.
14477     *
14478     * @see #isPaddingOffsetRequired()
14479     *
14480     * @since CURRENT
14481     */
14482    protected int getRightPaddingOffset() {
14483        return 0;
14484    }
14485
14486    /**
14487     * Amount by which to extend the top fading region. Called only when
14488     * {@link #isPaddingOffsetRequired()} returns true.
14489     *
14490     * @return The top padding offset in pixels.
14491     *
14492     * @see #isPaddingOffsetRequired()
14493     *
14494     * @since CURRENT
14495     */
14496    protected int getTopPaddingOffset() {
14497        return 0;
14498    }
14499
14500    /**
14501     * Amount by which to extend the bottom fading region. Called only when
14502     * {@link #isPaddingOffsetRequired()} returns true.
14503     *
14504     * @return The bottom padding offset in pixels.
14505     *
14506     * @see #isPaddingOffsetRequired()
14507     *
14508     * @since CURRENT
14509     */
14510    protected int getBottomPaddingOffset() {
14511        return 0;
14512    }
14513
14514    /**
14515     * @hide
14516     * @param offsetRequired
14517     */
14518    protected int getFadeTop(boolean offsetRequired) {
14519        int top = mPaddingTop;
14520        if (offsetRequired) top += getTopPaddingOffset();
14521        return top;
14522    }
14523
14524    /**
14525     * @hide
14526     * @param offsetRequired
14527     */
14528    protected int getFadeHeight(boolean offsetRequired) {
14529        int padding = mPaddingTop;
14530        if (offsetRequired) padding += getTopPaddingOffset();
14531        return mBottom - mTop - mPaddingBottom - padding;
14532    }
14533
14534    /**
14535     * <p>Indicates whether this view is attached to a hardware accelerated
14536     * window or not.</p>
14537     *
14538     * <p>Even if this method returns true, it does not mean that every call
14539     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
14540     * accelerated {@link android.graphics.Canvas}. For instance, if this view
14541     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
14542     * window is hardware accelerated,
14543     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
14544     * return false, and this method will return true.</p>
14545     *
14546     * @return True if the view is attached to a window and the window is
14547     *         hardware accelerated; false in any other case.
14548     */
14549    public boolean isHardwareAccelerated() {
14550        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
14551    }
14552
14553    /**
14554     * Sets a rectangular area on this view to which the view will be clipped
14555     * when it is drawn. Setting the value to null will remove the clip bounds
14556     * and the view will draw normally, using its full bounds.
14557     *
14558     * @param clipBounds The rectangular area, in the local coordinates of
14559     * this view, to which future drawing operations will be clipped.
14560     */
14561    public void setClipBounds(Rect clipBounds) {
14562        if (clipBounds != null) {
14563            if (clipBounds.equals(mClipBounds)) {
14564                return;
14565            }
14566            if (mClipBounds == null) {
14567                invalidate();
14568                mClipBounds = new Rect(clipBounds);
14569            } else {
14570                invalidate(Math.min(mClipBounds.left, clipBounds.left),
14571                        Math.min(mClipBounds.top, clipBounds.top),
14572                        Math.max(mClipBounds.right, clipBounds.right),
14573                        Math.max(mClipBounds.bottom, clipBounds.bottom));
14574                mClipBounds.set(clipBounds);
14575            }
14576        } else {
14577            if (mClipBounds != null) {
14578                invalidate();
14579                mClipBounds = null;
14580            }
14581        }
14582    }
14583
14584    /**
14585     * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}.
14586     *
14587     * @return A copy of the current clip bounds if clip bounds are set,
14588     * otherwise null.
14589     */
14590    public Rect getClipBounds() {
14591        return (mClipBounds != null) ? new Rect(mClipBounds) : null;
14592    }
14593
14594    /**
14595     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
14596     * case of an active Animation being run on the view.
14597     */
14598    private boolean drawAnimation(ViewGroup parent, long drawingTime,
14599            Animation a, boolean scalingRequired) {
14600        Transformation invalidationTransform;
14601        final int flags = parent.mGroupFlags;
14602        final boolean initialized = a.isInitialized();
14603        if (!initialized) {
14604            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
14605            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
14606            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
14607            onAnimationStart();
14608        }
14609
14610        final Transformation t = parent.getChildTransformation();
14611        boolean more = a.getTransformation(drawingTime, t, 1f);
14612        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
14613            if (parent.mInvalidationTransformation == null) {
14614                parent.mInvalidationTransformation = new Transformation();
14615            }
14616            invalidationTransform = parent.mInvalidationTransformation;
14617            a.getTransformation(drawingTime, invalidationTransform, 1f);
14618        } else {
14619            invalidationTransform = t;
14620        }
14621
14622        if (more) {
14623            if (!a.willChangeBounds()) {
14624                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
14625                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
14626                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
14627                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
14628                    // The child need to draw an animation, potentially offscreen, so
14629                    // make sure we do not cancel invalidate requests
14630                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
14631                    parent.invalidate(mLeft, mTop, mRight, mBottom);
14632                }
14633            } else {
14634                if (parent.mInvalidateRegion == null) {
14635                    parent.mInvalidateRegion = new RectF();
14636                }
14637                final RectF region = parent.mInvalidateRegion;
14638                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
14639                        invalidationTransform);
14640
14641                // The child need to draw an animation, potentially offscreen, so
14642                // make sure we do not cancel invalidate requests
14643                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
14644
14645                final int left = mLeft + (int) region.left;
14646                final int top = mTop + (int) region.top;
14647                parent.invalidate(left, top, left + (int) (region.width() + .5f),
14648                        top + (int) (region.height() + .5f));
14649            }
14650        }
14651        return more;
14652    }
14653
14654    /**
14655     * This method is called by getDisplayList() when a display list is created or re-rendered.
14656     * It sets or resets the current value of all properties on that display list (resetting is
14657     * necessary when a display list is being re-created, because we need to make sure that
14658     * previously-set transform values
14659     */
14660    void setDisplayListProperties(DisplayList displayList) {
14661        if (displayList != null) {
14662            displayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
14663            displayList.setHasOverlappingRendering(hasOverlappingRendering());
14664            if (mParent instanceof ViewGroup) {
14665                displayList.setClipToBounds(
14666                        (((ViewGroup) mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0);
14667            }
14668            if (this instanceof ViewGroup) {
14669                displayList.setIsolatedZVolume(
14670                        (((ViewGroup) this).mGroupFlags & ViewGroup.FLAG_ISOLATED_Z_VOLUME) != 0);
14671            }
14672            displayList.setOutline(mOutline);
14673            displayList.setClipToOutline(getClipToOutline());
14674            displayList.setCastsShadow(getCastsShadow());
14675            displayList.setUsesGlobalCamera(getUsesGlobalCamera());
14676            float alpha = 1;
14677            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
14678                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
14679                ViewGroup parentVG = (ViewGroup) mParent;
14680                final Transformation t = parentVG.getChildTransformation();
14681                if (parentVG.getChildStaticTransformation(this, t)) {
14682                    final int transformType = t.getTransformationType();
14683                    if (transformType != Transformation.TYPE_IDENTITY) {
14684                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
14685                            alpha = t.getAlpha();
14686                        }
14687                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
14688                            displayList.setStaticMatrix(t.getMatrix());
14689                        }
14690                    }
14691                }
14692            }
14693            if (mTransformationInfo != null) {
14694                alpha *= getFinalAlpha();
14695                if (alpha < 1) {
14696                    final int multipliedAlpha = (int) (255 * alpha);
14697                    if (onSetAlpha(multipliedAlpha)) {
14698                        alpha = 1;
14699                    }
14700                }
14701                displayList.setTransformationInfo(alpha,
14702                        mTransformationInfo.mTranslationX, mTransformationInfo.mTranslationY,
14703                        mTransformationInfo.mTranslationZ,
14704                        mTransformationInfo.mRotation, mTransformationInfo.mRotationX,
14705                        mTransformationInfo.mRotationY, mTransformationInfo.mScaleX,
14706                        mTransformationInfo.mScaleY);
14707                if (mTransformationInfo.mCamera == null) {
14708                    mTransformationInfo.mCamera = new Camera();
14709                    mTransformationInfo.matrix3D = new Matrix();
14710                }
14711                displayList.setCameraDistance(mTransformationInfo.mCamera.getLocationZ());
14712                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == PFLAG_PIVOT_EXPLICITLY_SET) {
14713                    displayList.setPivotX(getPivotX());
14714                    displayList.setPivotY(getPivotY());
14715                }
14716            } else if (alpha < 1) {
14717                displayList.setAlpha(alpha);
14718            }
14719        }
14720    }
14721
14722    /**
14723     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
14724     * This draw() method is an implementation detail and is not intended to be overridden or
14725     * to be called from anywhere else other than ViewGroup.drawChild().
14726     */
14727    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
14728        boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
14729        boolean more = false;
14730        final boolean childHasIdentityMatrix = hasIdentityMatrix();
14731        final int flags = parent.mGroupFlags;
14732
14733        if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) {
14734            parent.getChildTransformation().clear();
14735            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14736        }
14737
14738        Transformation transformToApply = null;
14739        boolean concatMatrix = false;
14740
14741        boolean scalingRequired = false;
14742        boolean caching;
14743        int layerType = getLayerType();
14744
14745        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
14746        if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 ||
14747                (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) {
14748            caching = true;
14749            // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList
14750            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
14751        } else {
14752            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
14753        }
14754
14755        final Animation a = getAnimation();
14756        if (a != null) {
14757            more = drawAnimation(parent, drawingTime, a, scalingRequired);
14758            concatMatrix = a.willChangeTransformationMatrix();
14759            if (concatMatrix) {
14760                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
14761            }
14762            transformToApply = parent.getChildTransformation();
14763        } else {
14764            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) ==
14765                    PFLAG3_VIEW_IS_ANIMATING_TRANSFORM && mDisplayList != null) {
14766                // No longer animating: clear out old animation matrix
14767                mDisplayList.setAnimationMatrix(null);
14768                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
14769            }
14770            if (!useDisplayListProperties &&
14771                    (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
14772                final Transformation t = parent.getChildTransformation();
14773                final boolean hasTransform = parent.getChildStaticTransformation(this, t);
14774                if (hasTransform) {
14775                    final int transformType = t.getTransformationType();
14776                    transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null;
14777                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
14778                }
14779            }
14780        }
14781
14782        concatMatrix |= !childHasIdentityMatrix;
14783
14784        // Sets the flag as early as possible to allow draw() implementations
14785        // to call invalidate() successfully when doing animations
14786        mPrivateFlags |= PFLAG_DRAWN;
14787
14788        if (!concatMatrix &&
14789                (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
14790                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
14791                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
14792                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
14793            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
14794            return more;
14795        }
14796        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
14797
14798        if (hardwareAccelerated) {
14799            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
14800            // retain the flag's value temporarily in the mRecreateDisplayList flag
14801            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED;
14802            mPrivateFlags &= ~PFLAG_INVALIDATED;
14803        }
14804
14805        DisplayList displayList = null;
14806        Bitmap cache = null;
14807        boolean hasDisplayList = false;
14808        if (caching) {
14809            if (!hardwareAccelerated) {
14810                if (layerType != LAYER_TYPE_NONE) {
14811                    layerType = LAYER_TYPE_SOFTWARE;
14812                    buildDrawingCache(true);
14813                }
14814                cache = getDrawingCache(true);
14815            } else {
14816                switch (layerType) {
14817                    case LAYER_TYPE_SOFTWARE:
14818                        if (useDisplayListProperties) {
14819                            hasDisplayList = canHaveDisplayList();
14820                        } else {
14821                            buildDrawingCache(true);
14822                            cache = getDrawingCache(true);
14823                        }
14824                        break;
14825                    case LAYER_TYPE_HARDWARE:
14826                        if (useDisplayListProperties) {
14827                            hasDisplayList = canHaveDisplayList();
14828                        }
14829                        break;
14830                    case LAYER_TYPE_NONE:
14831                        // Delay getting the display list until animation-driven alpha values are
14832                        // set up and possibly passed on to the view
14833                        hasDisplayList = canHaveDisplayList();
14834                        break;
14835                }
14836            }
14837        }
14838        useDisplayListProperties &= hasDisplayList;
14839        if (useDisplayListProperties) {
14840            displayList = getDisplayList();
14841            if (!displayList.isValid()) {
14842                // Uncommon, but possible. If a view is removed from the hierarchy during the call
14843                // to getDisplayList(), the display list will be marked invalid and we should not
14844                // try to use it again.
14845                displayList = null;
14846                hasDisplayList = false;
14847                useDisplayListProperties = false;
14848            }
14849        }
14850
14851        int sx = 0;
14852        int sy = 0;
14853        if (!hasDisplayList) {
14854            computeScroll();
14855            sx = mScrollX;
14856            sy = mScrollY;
14857        }
14858
14859        final boolean hasNoCache = cache == null || hasDisplayList;
14860        final boolean offsetForScroll = cache == null && !hasDisplayList &&
14861                layerType != LAYER_TYPE_HARDWARE;
14862
14863        int restoreTo = -1;
14864        if (!useDisplayListProperties || transformToApply != null) {
14865            restoreTo = canvas.save();
14866        }
14867        if (offsetForScroll) {
14868            canvas.translate(mLeft - sx, mTop - sy);
14869        } else {
14870            if (!useDisplayListProperties) {
14871                canvas.translate(mLeft, mTop);
14872            }
14873            if (scalingRequired) {
14874                if (useDisplayListProperties) {
14875                    // TODO: Might not need this if we put everything inside the DL
14876                    restoreTo = canvas.save();
14877                }
14878                // mAttachInfo cannot be null, otherwise scalingRequired == false
14879                final float scale = 1.0f / mAttachInfo.mApplicationScale;
14880                canvas.scale(scale, scale);
14881            }
14882        }
14883
14884        float alpha = useDisplayListProperties ? 1 : (getAlpha() * getTransitionAlpha());
14885        if (transformToApply != null || alpha < 1 ||  !hasIdentityMatrix() ||
14886                (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
14887            if (transformToApply != null || !childHasIdentityMatrix) {
14888                int transX = 0;
14889                int transY = 0;
14890
14891                if (offsetForScroll) {
14892                    transX = -sx;
14893                    transY = -sy;
14894                }
14895
14896                if (transformToApply != null) {
14897                    if (concatMatrix) {
14898                        if (useDisplayListProperties) {
14899                            displayList.setAnimationMatrix(transformToApply.getMatrix());
14900                        } else {
14901                            // Undo the scroll translation, apply the transformation matrix,
14902                            // then redo the scroll translate to get the correct result.
14903                            canvas.translate(-transX, -transY);
14904                            canvas.concat(transformToApply.getMatrix());
14905                            canvas.translate(transX, transY);
14906                        }
14907                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14908                    }
14909
14910                    float transformAlpha = transformToApply.getAlpha();
14911                    if (transformAlpha < 1) {
14912                        alpha *= transformAlpha;
14913                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14914                    }
14915                }
14916
14917                if (!childHasIdentityMatrix && !useDisplayListProperties) {
14918                    canvas.translate(-transX, -transY);
14919                    canvas.concat(getMatrix());
14920                    canvas.translate(transX, transY);
14921                }
14922            }
14923
14924            // Deal with alpha if it is or used to be <1
14925            if (alpha < 1 ||
14926                    (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
14927                if (alpha < 1) {
14928                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
14929                } else {
14930                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
14931                }
14932                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14933                if (hasNoCache) {
14934                    final int multipliedAlpha = (int) (255 * alpha);
14935                    if (!onSetAlpha(multipliedAlpha)) {
14936                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
14937                        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 ||
14938                                layerType != LAYER_TYPE_NONE) {
14939                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
14940                        }
14941                        if (useDisplayListProperties) {
14942                            displayList.setAlpha(alpha * getAlpha() * getTransitionAlpha());
14943                        } else  if (layerType == LAYER_TYPE_NONE) {
14944                            final int scrollX = hasDisplayList ? 0 : sx;
14945                            final int scrollY = hasDisplayList ? 0 : sy;
14946                            canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft,
14947                                    scrollY + mBottom - mTop, multipliedAlpha, layerFlags);
14948                        }
14949                    } else {
14950                        // Alpha is handled by the child directly, clobber the layer's alpha
14951                        mPrivateFlags |= PFLAG_ALPHA_SET;
14952                    }
14953                }
14954            }
14955        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
14956            onSetAlpha(255);
14957            mPrivateFlags &= ~PFLAG_ALPHA_SET;
14958        }
14959
14960        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN &&
14961                !useDisplayListProperties && cache == null) {
14962            if (offsetForScroll) {
14963                canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
14964            } else {
14965                if (!scalingRequired || cache == null) {
14966                    canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
14967                } else {
14968                    canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
14969                }
14970            }
14971        }
14972
14973        if (!useDisplayListProperties && hasDisplayList) {
14974            displayList = getDisplayList();
14975            if (!displayList.isValid()) {
14976                // Uncommon, but possible. If a view is removed from the hierarchy during the call
14977                // to getDisplayList(), the display list will be marked invalid and we should not
14978                // try to use it again.
14979                displayList = null;
14980                hasDisplayList = false;
14981            }
14982        }
14983
14984        if (hasNoCache) {
14985            boolean layerRendered = false;
14986            if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) {
14987                final HardwareLayer layer = getHardwareLayer();
14988                if (layer != null && layer.isValid()) {
14989                    mLayerPaint.setAlpha((int) (alpha * 255));
14990                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
14991                    layerRendered = true;
14992                } else {
14993                    final int scrollX = hasDisplayList ? 0 : sx;
14994                    final int scrollY = hasDisplayList ? 0 : sy;
14995                    canvas.saveLayer(scrollX, scrollY,
14996                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
14997                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
14998                }
14999            }
15000
15001            if (!layerRendered) {
15002                if (!hasDisplayList) {
15003                    // Fast path for layouts with no backgrounds
15004                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
15005                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
15006                        dispatchDraw(canvas);
15007                    } else {
15008                        draw(canvas);
15009                    }
15010                } else {
15011                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
15012                    ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags);
15013                }
15014            }
15015        } else if (cache != null) {
15016            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
15017            Paint cachePaint;
15018
15019            if (layerType == LAYER_TYPE_NONE) {
15020                cachePaint = parent.mCachePaint;
15021                if (cachePaint == null) {
15022                    cachePaint = new Paint();
15023                    cachePaint.setDither(false);
15024                    parent.mCachePaint = cachePaint;
15025                }
15026                if (alpha < 1) {
15027                    cachePaint.setAlpha((int) (alpha * 255));
15028                    parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
15029                } else if  ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) {
15030                    cachePaint.setAlpha(255);
15031                    parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
15032                }
15033            } else {
15034                cachePaint = mLayerPaint;
15035                cachePaint.setAlpha((int) (alpha * 255));
15036            }
15037            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
15038        }
15039
15040        if (restoreTo >= 0) {
15041            canvas.restoreToCount(restoreTo);
15042        }
15043
15044        if (a != null && !more) {
15045            if (!hardwareAccelerated && !a.getFillAfter()) {
15046                onSetAlpha(255);
15047            }
15048            parent.finishAnimatingView(this, a);
15049        }
15050
15051        if (more && hardwareAccelerated) {
15052            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
15053                // alpha animations should cause the child to recreate its display list
15054                invalidate(true);
15055            }
15056        }
15057
15058        mRecreateDisplayList = false;
15059
15060        return more;
15061    }
15062
15063    /**
15064     * Manually render this view (and all of its children) to the given Canvas.
15065     * The view must have already done a full layout before this function is
15066     * called.  When implementing a view, implement
15067     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
15068     * If you do need to override this method, call the superclass version.
15069     *
15070     * @param canvas The Canvas to which the View is rendered.
15071     */
15072    public void draw(Canvas canvas) {
15073        if (mClipBounds != null) {
15074            canvas.clipRect(mClipBounds);
15075        }
15076        final int privateFlags = mPrivateFlags;
15077        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
15078                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
15079        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
15080
15081        /*
15082         * Draw traversal performs several drawing steps which must be executed
15083         * in the appropriate order:
15084         *
15085         *      1. Draw the background
15086         *      2. If necessary, save the canvas' layers to prepare for fading
15087         *      3. Draw view's content
15088         *      4. Draw children
15089         *      5. If necessary, draw the fading edges and restore layers
15090         *      6. Draw decorations (scrollbars for instance)
15091         */
15092
15093        // Step 1, draw the background, if needed
15094        int saveCount;
15095
15096        if (!dirtyOpaque) {
15097            drawBackground(canvas);
15098        }
15099
15100        // skip step 2 & 5 if possible (common case)
15101        final int viewFlags = mViewFlags;
15102        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
15103        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
15104        if (!verticalEdges && !horizontalEdges) {
15105            // Step 3, draw the content
15106            if (!dirtyOpaque) onDraw(canvas);
15107
15108            // Step 4, draw the children
15109            dispatchDraw(canvas);
15110
15111            // Step 6, draw decorations (scrollbars)
15112            onDrawScrollBars(canvas);
15113
15114            if (mOverlay != null && !mOverlay.isEmpty()) {
15115                mOverlay.getOverlayView().dispatchDraw(canvas);
15116            }
15117
15118            // we're done...
15119            return;
15120        }
15121
15122        /*
15123         * Here we do the full fledged routine...
15124         * (this is an uncommon case where speed matters less,
15125         * this is why we repeat some of the tests that have been
15126         * done above)
15127         */
15128
15129        boolean drawTop = false;
15130        boolean drawBottom = false;
15131        boolean drawLeft = false;
15132        boolean drawRight = false;
15133
15134        float topFadeStrength = 0.0f;
15135        float bottomFadeStrength = 0.0f;
15136        float leftFadeStrength = 0.0f;
15137        float rightFadeStrength = 0.0f;
15138
15139        // Step 2, save the canvas' layers
15140        int paddingLeft = mPaddingLeft;
15141
15142        final boolean offsetRequired = isPaddingOffsetRequired();
15143        if (offsetRequired) {
15144            paddingLeft += getLeftPaddingOffset();
15145        }
15146
15147        int left = mScrollX + paddingLeft;
15148        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
15149        int top = mScrollY + getFadeTop(offsetRequired);
15150        int bottom = top + getFadeHeight(offsetRequired);
15151
15152        if (offsetRequired) {
15153            right += getRightPaddingOffset();
15154            bottom += getBottomPaddingOffset();
15155        }
15156
15157        final ScrollabilityCache scrollabilityCache = mScrollCache;
15158        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
15159        int length = (int) fadeHeight;
15160
15161        // clip the fade length if top and bottom fades overlap
15162        // overlapping fades produce odd-looking artifacts
15163        if (verticalEdges && (top + length > bottom - length)) {
15164            length = (bottom - top) / 2;
15165        }
15166
15167        // also clip horizontal fades if necessary
15168        if (horizontalEdges && (left + length > right - length)) {
15169            length = (right - left) / 2;
15170        }
15171
15172        if (verticalEdges) {
15173            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
15174            drawTop = topFadeStrength * fadeHeight > 1.0f;
15175            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
15176            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
15177        }
15178
15179        if (horizontalEdges) {
15180            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
15181            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
15182            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
15183            drawRight = rightFadeStrength * fadeHeight > 1.0f;
15184        }
15185
15186        saveCount = canvas.getSaveCount();
15187
15188        int solidColor = getSolidColor();
15189        if (solidColor == 0) {
15190            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
15191
15192            if (drawTop) {
15193                canvas.saveLayer(left, top, right, top + length, null, flags);
15194            }
15195
15196            if (drawBottom) {
15197                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
15198            }
15199
15200            if (drawLeft) {
15201                canvas.saveLayer(left, top, left + length, bottom, null, flags);
15202            }
15203
15204            if (drawRight) {
15205                canvas.saveLayer(right - length, top, right, bottom, null, flags);
15206            }
15207        } else {
15208            scrollabilityCache.setFadeColor(solidColor);
15209        }
15210
15211        // Step 3, draw the content
15212        if (!dirtyOpaque) onDraw(canvas);
15213
15214        // Step 4, draw the children
15215        dispatchDraw(canvas);
15216
15217        // Step 5, draw the fade effect and restore layers
15218        final Paint p = scrollabilityCache.paint;
15219        final Matrix matrix = scrollabilityCache.matrix;
15220        final Shader fade = scrollabilityCache.shader;
15221
15222        if (drawTop) {
15223            matrix.setScale(1, fadeHeight * topFadeStrength);
15224            matrix.postTranslate(left, top);
15225            fade.setLocalMatrix(matrix);
15226            canvas.drawRect(left, top, right, top + length, p);
15227        }
15228
15229        if (drawBottom) {
15230            matrix.setScale(1, fadeHeight * bottomFadeStrength);
15231            matrix.postRotate(180);
15232            matrix.postTranslate(left, bottom);
15233            fade.setLocalMatrix(matrix);
15234            canvas.drawRect(left, bottom - length, right, bottom, p);
15235        }
15236
15237        if (drawLeft) {
15238            matrix.setScale(1, fadeHeight * leftFadeStrength);
15239            matrix.postRotate(-90);
15240            matrix.postTranslate(left, top);
15241            fade.setLocalMatrix(matrix);
15242            canvas.drawRect(left, top, left + length, bottom, p);
15243        }
15244
15245        if (drawRight) {
15246            matrix.setScale(1, fadeHeight * rightFadeStrength);
15247            matrix.postRotate(90);
15248            matrix.postTranslate(right, top);
15249            fade.setLocalMatrix(matrix);
15250            canvas.drawRect(right - length, top, right, bottom, p);
15251        }
15252
15253        canvas.restoreToCount(saveCount);
15254
15255        // Step 6, draw decorations (scrollbars)
15256        onDrawScrollBars(canvas);
15257
15258        if (mOverlay != null && !mOverlay.isEmpty()) {
15259            mOverlay.getOverlayView().dispatchDraw(canvas);
15260        }
15261    }
15262
15263    /**
15264     * Draws the background onto the specified canvas.
15265     *
15266     * @param canvas Canvas on which to draw the background
15267     */
15268    private void drawBackground(Canvas canvas) {
15269        final Drawable background = mBackground;
15270        if (background == null) {
15271            return;
15272        }
15273
15274        if (mBackgroundSizeChanged) {
15275            background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
15276            mBackgroundSizeChanged = false;
15277        }
15278
15279        // Attempt to use a display list if requested.
15280        if (canvas.isHardwareAccelerated() && mAttachInfo != null
15281                && mAttachInfo.mHardwareRenderer != null) {
15282            mBackgroundDisplayList = getDrawableDisplayList(background, mBackgroundDisplayList);
15283
15284            final DisplayList displayList = mBackgroundDisplayList;
15285            if (displayList != null && displayList.isValid()) {
15286                setBackgroundDisplayListProperties(displayList);
15287                ((HardwareCanvas) canvas).drawDisplayList(displayList);
15288                return;
15289            }
15290        }
15291
15292        final int scrollX = mScrollX;
15293        final int scrollY = mScrollY;
15294        if ((scrollX | scrollY) == 0) {
15295            background.draw(canvas);
15296        } else {
15297            canvas.translate(scrollX, scrollY);
15298            background.draw(canvas);
15299            canvas.translate(-scrollX, -scrollY);
15300        }
15301    }
15302
15303    /**
15304     * Set up background drawable display list properties.
15305     *
15306     * @param displayList Valid display list for the background drawable
15307     */
15308    private void setBackgroundDisplayListProperties(DisplayList displayList) {
15309        displayList.setTranslationX(mScrollX);
15310        displayList.setTranslationY(mScrollY);
15311    }
15312
15313    /**
15314     * Creates a new display list or updates the existing display list for the
15315     * specified Drawable.
15316     *
15317     * @param drawable Drawable for which to create a display list
15318     * @param displayList Existing display list, or {@code null}
15319     * @return A valid display list for the specified drawable
15320     */
15321    private DisplayList getDrawableDisplayList(Drawable drawable, DisplayList displayList) {
15322        if (displayList == null) {
15323            displayList = DisplayList.create(drawable.getClass().getName());
15324        }
15325
15326        final Rect bounds = drawable.getBounds();
15327        final int width = bounds.width();
15328        final int height = bounds.height();
15329        final HardwareCanvas canvas = displayList.start(width, height);
15330        drawable.draw(canvas);
15331        displayList.end(getHardwareRenderer(), canvas);
15332
15333        // Set up drawable properties that are view-independent.
15334        displayList.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom);
15335        displayList.setProjectBackwards(drawable.isProjected());
15336        displayList.setProjectionReceiver(true);
15337        displayList.setClipToBounds(false);
15338        return displayList;
15339    }
15340
15341    /**
15342     * Returns the overlay for this view, creating it if it does not yet exist.
15343     * Adding drawables to the overlay will cause them to be displayed whenever
15344     * the view itself is redrawn. Objects in the overlay should be actively
15345     * managed: remove them when they should not be displayed anymore. The
15346     * overlay will always have the same size as its host view.
15347     *
15348     * <p>Note: Overlays do not currently work correctly with {@link
15349     * SurfaceView} or {@link TextureView}; contents in overlays for these
15350     * types of views may not display correctly.</p>
15351     *
15352     * @return The ViewOverlay object for this view.
15353     * @see ViewOverlay
15354     */
15355    public ViewOverlay getOverlay() {
15356        if (mOverlay == null) {
15357            mOverlay = new ViewOverlay(mContext, this);
15358        }
15359        return mOverlay;
15360    }
15361
15362    /**
15363     * Override this if your view is known to always be drawn on top of a solid color background,
15364     * and needs to draw fading edges. Returning a non-zero color enables the view system to
15365     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
15366     * should be set to 0xFF.
15367     *
15368     * @see #setVerticalFadingEdgeEnabled(boolean)
15369     * @see #setHorizontalFadingEdgeEnabled(boolean)
15370     *
15371     * @return The known solid color background for this view, or 0 if the color may vary
15372     */
15373    @ViewDebug.ExportedProperty(category = "drawing")
15374    public int getSolidColor() {
15375        return 0;
15376    }
15377
15378    /**
15379     * Build a human readable string representation of the specified view flags.
15380     *
15381     * @param flags the view flags to convert to a string
15382     * @return a String representing the supplied flags
15383     */
15384    private static String printFlags(int flags) {
15385        String output = "";
15386        int numFlags = 0;
15387        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
15388            output += "TAKES_FOCUS";
15389            numFlags++;
15390        }
15391
15392        switch (flags & VISIBILITY_MASK) {
15393        case INVISIBLE:
15394            if (numFlags > 0) {
15395                output += " ";
15396            }
15397            output += "INVISIBLE";
15398            // USELESS HERE numFlags++;
15399            break;
15400        case GONE:
15401            if (numFlags > 0) {
15402                output += " ";
15403            }
15404            output += "GONE";
15405            // USELESS HERE numFlags++;
15406            break;
15407        default:
15408            break;
15409        }
15410        return output;
15411    }
15412
15413    /**
15414     * Build a human readable string representation of the specified private
15415     * view flags.
15416     *
15417     * @param privateFlags the private view flags to convert to a string
15418     * @return a String representing the supplied flags
15419     */
15420    private static String printPrivateFlags(int privateFlags) {
15421        String output = "";
15422        int numFlags = 0;
15423
15424        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
15425            output += "WANTS_FOCUS";
15426            numFlags++;
15427        }
15428
15429        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
15430            if (numFlags > 0) {
15431                output += " ";
15432            }
15433            output += "FOCUSED";
15434            numFlags++;
15435        }
15436
15437        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
15438            if (numFlags > 0) {
15439                output += " ";
15440            }
15441            output += "SELECTED";
15442            numFlags++;
15443        }
15444
15445        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
15446            if (numFlags > 0) {
15447                output += " ";
15448            }
15449            output += "IS_ROOT_NAMESPACE";
15450            numFlags++;
15451        }
15452
15453        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
15454            if (numFlags > 0) {
15455                output += " ";
15456            }
15457            output += "HAS_BOUNDS";
15458            numFlags++;
15459        }
15460
15461        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
15462            if (numFlags > 0) {
15463                output += " ";
15464            }
15465            output += "DRAWN";
15466            // USELESS HERE numFlags++;
15467        }
15468        return output;
15469    }
15470
15471    /**
15472     * <p>Indicates whether or not this view's layout will be requested during
15473     * the next hierarchy layout pass.</p>
15474     *
15475     * @return true if the layout will be forced during next layout pass
15476     */
15477    public boolean isLayoutRequested() {
15478        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
15479    }
15480
15481    /**
15482     * Return true if o is a ViewGroup that is laying out using optical bounds.
15483     * @hide
15484     */
15485    public static boolean isLayoutModeOptical(Object o) {
15486        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
15487    }
15488
15489    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
15490        Insets parentInsets = mParent instanceof View ?
15491                ((View) mParent).getOpticalInsets() : Insets.NONE;
15492        Insets childInsets = getOpticalInsets();
15493        return setFrame(
15494                left   + parentInsets.left - childInsets.left,
15495                top    + parentInsets.top  - childInsets.top,
15496                right  + parentInsets.left + childInsets.right,
15497                bottom + parentInsets.top  + childInsets.bottom);
15498    }
15499
15500    /**
15501     * Assign a size and position to a view and all of its
15502     * descendants
15503     *
15504     * <p>This is the second phase of the layout mechanism.
15505     * (The first is measuring). In this phase, each parent calls
15506     * layout on all of its children to position them.
15507     * This is typically done using the child measurements
15508     * that were stored in the measure pass().</p>
15509     *
15510     * <p>Derived classes should not override this method.
15511     * Derived classes with children should override
15512     * onLayout. In that method, they should
15513     * call layout on each of their children.</p>
15514     *
15515     * @param l Left position, relative to parent
15516     * @param t Top position, relative to parent
15517     * @param r Right position, relative to parent
15518     * @param b Bottom position, relative to parent
15519     */
15520    @SuppressWarnings({"unchecked"})
15521    public void layout(int l, int t, int r, int b) {
15522        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
15523            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
15524            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
15525        }
15526
15527        int oldL = mLeft;
15528        int oldT = mTop;
15529        int oldB = mBottom;
15530        int oldR = mRight;
15531
15532        boolean changed = isLayoutModeOptical(mParent) ?
15533                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
15534
15535        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
15536            onLayout(changed, l, t, r, b);
15537            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
15538
15539            ListenerInfo li = mListenerInfo;
15540            if (li != null && li.mOnLayoutChangeListeners != null) {
15541                ArrayList<OnLayoutChangeListener> listenersCopy =
15542                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
15543                int numListeners = listenersCopy.size();
15544                for (int i = 0; i < numListeners; ++i) {
15545                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
15546                }
15547            }
15548        }
15549
15550        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
15551        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
15552    }
15553
15554    /**
15555     * Called from layout when this view should
15556     * assign a size and position to each of its children.
15557     *
15558     * Derived classes with children should override
15559     * this method and call layout on each of
15560     * their children.
15561     * @param changed This is a new size or position for this view
15562     * @param left Left position, relative to parent
15563     * @param top Top position, relative to parent
15564     * @param right Right position, relative to parent
15565     * @param bottom Bottom position, relative to parent
15566     */
15567    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
15568    }
15569
15570    /**
15571     * Assign a size and position to this view.
15572     *
15573     * This is called from layout.
15574     *
15575     * @param left Left position, relative to parent
15576     * @param top Top position, relative to parent
15577     * @param right Right position, relative to parent
15578     * @param bottom Bottom position, relative to parent
15579     * @return true if the new size and position are different than the
15580     *         previous ones
15581     * {@hide}
15582     */
15583    protected boolean setFrame(int left, int top, int right, int bottom) {
15584        boolean changed = false;
15585
15586        if (DBG) {
15587            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
15588                    + right + "," + bottom + ")");
15589        }
15590
15591        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
15592            changed = true;
15593
15594            // Remember our drawn bit
15595            int drawn = mPrivateFlags & PFLAG_DRAWN;
15596
15597            int oldWidth = mRight - mLeft;
15598            int oldHeight = mBottom - mTop;
15599            int newWidth = right - left;
15600            int newHeight = bottom - top;
15601            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
15602
15603            // Invalidate our old position
15604            invalidate(sizeChanged);
15605
15606            mLeft = left;
15607            mTop = top;
15608            mRight = right;
15609            mBottom = bottom;
15610            if (mDisplayList != null) {
15611                mDisplayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
15612            }
15613
15614            mPrivateFlags |= PFLAG_HAS_BOUNDS;
15615
15616
15617            if (sizeChanged) {
15618                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
15619                    // A change in dimension means an auto-centered pivot point changes, too
15620                    if (mTransformationInfo != null) {
15621                        mTransformationInfo.mMatrixDirty = true;
15622                    }
15623                }
15624                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
15625            }
15626
15627            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
15628                // If we are visible, force the DRAWN bit to on so that
15629                // this invalidate will go through (at least to our parent).
15630                // This is because someone may have invalidated this view
15631                // before this call to setFrame came in, thereby clearing
15632                // the DRAWN bit.
15633                mPrivateFlags |= PFLAG_DRAWN;
15634                invalidate(sizeChanged);
15635                // parent display list may need to be recreated based on a change in the bounds
15636                // of any child
15637                invalidateParentCaches();
15638            }
15639
15640            // Reset drawn bit to original value (invalidate turns it off)
15641            mPrivateFlags |= drawn;
15642
15643            mBackgroundSizeChanged = true;
15644
15645            notifySubtreeAccessibilityStateChangedIfNeeded();
15646        }
15647        return changed;
15648    }
15649
15650    private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
15651        onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
15652        if (mOverlay != null) {
15653            mOverlay.getOverlayView().setRight(newWidth);
15654            mOverlay.getOverlayView().setBottom(newHeight);
15655        }
15656    }
15657
15658    /**
15659     * Finalize inflating a view from XML.  This is called as the last phase
15660     * of inflation, after all child views have been added.
15661     *
15662     * <p>Even if the subclass overrides onFinishInflate, they should always be
15663     * sure to call the super method, so that we get called.
15664     */
15665    protected void onFinishInflate() {
15666    }
15667
15668    /**
15669     * Returns the resources associated with this view.
15670     *
15671     * @return Resources object.
15672     */
15673    public Resources getResources() {
15674        return mResources;
15675    }
15676
15677    /**
15678     * Invalidates the specified Drawable.
15679     *
15680     * @param drawable the drawable to invalidate
15681     */
15682    @Override
15683    public void invalidateDrawable(Drawable drawable) {
15684        if (verifyDrawable(drawable)) {
15685            final Rect dirty = drawable.getDirtyBounds();
15686            final int scrollX = mScrollX;
15687            final int scrollY = mScrollY;
15688
15689            invalidate(dirty.left + scrollX, dirty.top + scrollY,
15690                    dirty.right + scrollX, dirty.bottom + scrollY);
15691        }
15692    }
15693
15694    /**
15695     * Schedules an action on a drawable to occur at a specified time.
15696     *
15697     * @param who the recipient of the action
15698     * @param what the action to run on the drawable
15699     * @param when the time at which the action must occur. Uses the
15700     *        {@link SystemClock#uptimeMillis} timebase.
15701     */
15702    @Override
15703    public void scheduleDrawable(Drawable who, Runnable what, long when) {
15704        if (verifyDrawable(who) && what != null) {
15705            final long delay = when - SystemClock.uptimeMillis();
15706            if (mAttachInfo != null) {
15707                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
15708                        Choreographer.CALLBACK_ANIMATION, what, who,
15709                        Choreographer.subtractFrameDelay(delay));
15710            } else {
15711                ViewRootImpl.getRunQueue().postDelayed(what, delay);
15712            }
15713        }
15714    }
15715
15716    /**
15717     * Cancels a scheduled action on a drawable.
15718     *
15719     * @param who the recipient of the action
15720     * @param what the action to cancel
15721     */
15722    @Override
15723    public void unscheduleDrawable(Drawable who, Runnable what) {
15724        if (verifyDrawable(who) && what != null) {
15725            if (mAttachInfo != null) {
15726                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
15727                        Choreographer.CALLBACK_ANIMATION, what, who);
15728            }
15729            ViewRootImpl.getRunQueue().removeCallbacks(what);
15730        }
15731    }
15732
15733    /**
15734     * Unschedule any events associated with the given Drawable.  This can be
15735     * used when selecting a new Drawable into a view, so that the previous
15736     * one is completely unscheduled.
15737     *
15738     * @param who The Drawable to unschedule.
15739     *
15740     * @see #drawableStateChanged
15741     */
15742    public void unscheduleDrawable(Drawable who) {
15743        if (mAttachInfo != null && who != null) {
15744            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
15745                    Choreographer.CALLBACK_ANIMATION, null, who);
15746        }
15747    }
15748
15749    /**
15750     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
15751     * that the View directionality can and will be resolved before its Drawables.
15752     *
15753     * Will call {@link View#onResolveDrawables} when resolution is done.
15754     *
15755     * @hide
15756     */
15757    protected void resolveDrawables() {
15758        // Drawables resolution may need to happen before resolving the layout direction (which is
15759        // done only during the measure() call).
15760        // If the layout direction is not resolved yet, we cannot resolve the Drawables except in
15761        // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT.
15762        // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or
15763        // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout
15764        // direction to be resolved as its resolved value will be the same as its raw value.
15765        if (!isLayoutDirectionResolved() &&
15766                getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) {
15767            return;
15768        }
15769
15770        final int layoutDirection = isLayoutDirectionResolved() ?
15771                getLayoutDirection() : getRawLayoutDirection();
15772
15773        if (mBackground != null) {
15774            mBackground.setLayoutDirection(layoutDirection);
15775        }
15776        mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
15777        onResolveDrawables(layoutDirection);
15778    }
15779
15780    /**
15781     * Called when layout direction has been resolved.
15782     *
15783     * The default implementation does nothing.
15784     *
15785     * @param layoutDirection The resolved layout direction.
15786     *
15787     * @see #LAYOUT_DIRECTION_LTR
15788     * @see #LAYOUT_DIRECTION_RTL
15789     *
15790     * @hide
15791     */
15792    public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) {
15793    }
15794
15795    /**
15796     * @hide
15797     */
15798    protected void resetResolvedDrawables() {
15799        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
15800    }
15801
15802    private boolean isDrawablesResolved() {
15803        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
15804    }
15805
15806    /**
15807     * If your view subclass is displaying its own Drawable objects, it should
15808     * override this function and return true for any Drawable it is
15809     * displaying.  This allows animations for those drawables to be
15810     * scheduled.
15811     *
15812     * <p>Be sure to call through to the super class when overriding this
15813     * function.
15814     *
15815     * @param who The Drawable to verify.  Return true if it is one you are
15816     *            displaying, else return the result of calling through to the
15817     *            super class.
15818     *
15819     * @return boolean If true than the Drawable is being displayed in the
15820     *         view; else false and it is not allowed to animate.
15821     *
15822     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
15823     * @see #drawableStateChanged()
15824     */
15825    protected boolean verifyDrawable(Drawable who) {
15826        return who == mBackground;
15827    }
15828
15829    /**
15830     * This function is called whenever the state of the view changes in such
15831     * a way that it impacts the state of drawables being shown.
15832     *
15833     * <p>Be sure to call through to the superclass when overriding this
15834     * function.
15835     *
15836     * @see Drawable#setState(int[])
15837     */
15838    protected void drawableStateChanged() {
15839        final Drawable d = mBackground;
15840        if (d != null && d.isStateful()) {
15841            d.setState(getDrawableState());
15842        }
15843    }
15844
15845    /**
15846     * Call this to force a view to update its drawable state. This will cause
15847     * drawableStateChanged to be called on this view. Views that are interested
15848     * in the new state should call getDrawableState.
15849     *
15850     * @see #drawableStateChanged
15851     * @see #getDrawableState
15852     */
15853    public void refreshDrawableState() {
15854        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
15855        drawableStateChanged();
15856
15857        ViewParent parent = mParent;
15858        if (parent != null) {
15859            parent.childDrawableStateChanged(this);
15860        }
15861    }
15862
15863    /**
15864     * Return an array of resource IDs of the drawable states representing the
15865     * current state of the view.
15866     *
15867     * @return The current drawable state
15868     *
15869     * @see Drawable#setState(int[])
15870     * @see #drawableStateChanged()
15871     * @see #onCreateDrawableState(int)
15872     */
15873    public final int[] getDrawableState() {
15874        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
15875            return mDrawableState;
15876        } else {
15877            mDrawableState = onCreateDrawableState(0);
15878            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
15879            return mDrawableState;
15880        }
15881    }
15882
15883    /**
15884     * Generate the new {@link android.graphics.drawable.Drawable} state for
15885     * this view. This is called by the view
15886     * system when the cached Drawable state is determined to be invalid.  To
15887     * retrieve the current state, you should use {@link #getDrawableState}.
15888     *
15889     * @param extraSpace if non-zero, this is the number of extra entries you
15890     * would like in the returned array in which you can place your own
15891     * states.
15892     *
15893     * @return Returns an array holding the current {@link Drawable} state of
15894     * the view.
15895     *
15896     * @see #mergeDrawableStates(int[], int[])
15897     */
15898    protected int[] onCreateDrawableState(int extraSpace) {
15899        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
15900                mParent instanceof View) {
15901            return ((View) mParent).onCreateDrawableState(extraSpace);
15902        }
15903
15904        int[] drawableState;
15905
15906        int privateFlags = mPrivateFlags;
15907
15908        int viewStateIndex = 0;
15909        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
15910        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
15911        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
15912        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
15913        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
15914        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
15915        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
15916                HardwareRenderer.isAvailable()) {
15917            // This is set if HW acceleration is requested, even if the current
15918            // process doesn't allow it.  This is just to allow app preview
15919            // windows to better match their app.
15920            viewStateIndex |= VIEW_STATE_ACCELERATED;
15921        }
15922        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
15923
15924        final int privateFlags2 = mPrivateFlags2;
15925        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
15926        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
15927
15928        drawableState = VIEW_STATE_SETS[viewStateIndex];
15929
15930        //noinspection ConstantIfStatement
15931        if (false) {
15932            Log.i("View", "drawableStateIndex=" + viewStateIndex);
15933            Log.i("View", toString()
15934                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
15935                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
15936                    + " fo=" + hasFocus()
15937                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
15938                    + " wf=" + hasWindowFocus()
15939                    + ": " + Arrays.toString(drawableState));
15940        }
15941
15942        if (extraSpace == 0) {
15943            return drawableState;
15944        }
15945
15946        final int[] fullState;
15947        if (drawableState != null) {
15948            fullState = new int[drawableState.length + extraSpace];
15949            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
15950        } else {
15951            fullState = new int[extraSpace];
15952        }
15953
15954        return fullState;
15955    }
15956
15957    /**
15958     * Merge your own state values in <var>additionalState</var> into the base
15959     * state values <var>baseState</var> that were returned by
15960     * {@link #onCreateDrawableState(int)}.
15961     *
15962     * @param baseState The base state values returned by
15963     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
15964     * own additional state values.
15965     *
15966     * @param additionalState The additional state values you would like
15967     * added to <var>baseState</var>; this array is not modified.
15968     *
15969     * @return As a convenience, the <var>baseState</var> array you originally
15970     * passed into the function is returned.
15971     *
15972     * @see #onCreateDrawableState(int)
15973     */
15974    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
15975        final int N = baseState.length;
15976        int i = N - 1;
15977        while (i >= 0 && baseState[i] == 0) {
15978            i--;
15979        }
15980        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
15981        return baseState;
15982    }
15983
15984    /**
15985     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
15986     * on all Drawable objects associated with this view.
15987     */
15988    public void jumpDrawablesToCurrentState() {
15989        if (mBackground != null) {
15990            mBackground.jumpToCurrentState();
15991        }
15992    }
15993
15994    /**
15995     * Sets the background color for this view.
15996     * @param color the color of the background
15997     */
15998    @RemotableViewMethod
15999    public void setBackgroundColor(int color) {
16000        if (mBackground instanceof ColorDrawable) {
16001            ((ColorDrawable) mBackground.mutate()).setColor(color);
16002            computeOpaqueFlags();
16003            mBackgroundResource = 0;
16004        } else {
16005            setBackground(new ColorDrawable(color));
16006        }
16007    }
16008
16009    /**
16010     * Set the background to a given resource. The resource should refer to
16011     * a Drawable object or 0 to remove the background.
16012     * @param resid The identifier of the resource.
16013     *
16014     * @attr ref android.R.styleable#View_background
16015     */
16016    @RemotableViewMethod
16017    public void setBackgroundResource(int resid) {
16018        if (resid != 0 && resid == mBackgroundResource) {
16019            return;
16020        }
16021
16022        Drawable d= null;
16023        if (resid != 0) {
16024            d = mContext.getDrawable(resid);
16025        }
16026        setBackground(d);
16027
16028        mBackgroundResource = resid;
16029    }
16030
16031    /**
16032     * Set the background to a given Drawable, or remove the background. If the
16033     * background has padding, this View's padding is set to the background's
16034     * padding. However, when a background is removed, this View's padding isn't
16035     * touched. If setting the padding is desired, please use
16036     * {@link #setPadding(int, int, int, int)}.
16037     *
16038     * @param background The Drawable to use as the background, or null to remove the
16039     *        background
16040     */
16041    public void setBackground(Drawable background) {
16042        //noinspection deprecation
16043        setBackgroundDrawable(background);
16044    }
16045
16046    /**
16047     * @deprecated use {@link #setBackground(Drawable)} instead
16048     */
16049    @Deprecated
16050    public void setBackgroundDrawable(Drawable background) {
16051        computeOpaqueFlags();
16052
16053        if (background == mBackground) {
16054            return;
16055        }
16056
16057        boolean requestLayout = false;
16058
16059        mBackgroundResource = 0;
16060
16061        /*
16062         * Regardless of whether we're setting a new background or not, we want
16063         * to clear the previous drawable.
16064         */
16065        if (mBackground != null) {
16066            mBackground.setCallback(null);
16067            unscheduleDrawable(mBackground);
16068        }
16069
16070        if (background != null) {
16071            Rect padding = sThreadLocal.get();
16072            if (padding == null) {
16073                padding = new Rect();
16074                sThreadLocal.set(padding);
16075            }
16076            resetResolvedDrawables();
16077            background.setLayoutDirection(getLayoutDirection());
16078            if (background.getPadding(padding)) {
16079                resetResolvedPadding();
16080                switch (background.getLayoutDirection()) {
16081                    case LAYOUT_DIRECTION_RTL:
16082                        mUserPaddingLeftInitial = padding.right;
16083                        mUserPaddingRightInitial = padding.left;
16084                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
16085                        break;
16086                    case LAYOUT_DIRECTION_LTR:
16087                    default:
16088                        mUserPaddingLeftInitial = padding.left;
16089                        mUserPaddingRightInitial = padding.right;
16090                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
16091                }
16092                mLeftPaddingDefined = false;
16093                mRightPaddingDefined = false;
16094            }
16095
16096            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
16097            // if it has a different minimum size, we should layout again
16098            if (mBackground == null || mBackground.getMinimumHeight() != background.getMinimumHeight() ||
16099                    mBackground.getMinimumWidth() != background.getMinimumWidth()) {
16100                requestLayout = true;
16101            }
16102
16103            background.setCallback(this);
16104            if (background.isStateful()) {
16105                background.setState(getDrawableState());
16106            }
16107            background.setVisible(getVisibility() == VISIBLE, false);
16108            mBackground = background;
16109
16110            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
16111                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
16112                mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
16113                requestLayout = true;
16114            }
16115        } else {
16116            /* Remove the background */
16117            mBackground = null;
16118
16119            if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) {
16120                /*
16121                 * This view ONLY drew the background before and we're removing
16122                 * the background, so now it won't draw anything
16123                 * (hence we SKIP_DRAW)
16124                 */
16125                mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND;
16126                mPrivateFlags |= PFLAG_SKIP_DRAW;
16127            }
16128
16129            /*
16130             * When the background is set, we try to apply its padding to this
16131             * View. When the background is removed, we don't touch this View's
16132             * padding. This is noted in the Javadocs. Hence, we don't need to
16133             * requestLayout(), the invalidate() below is sufficient.
16134             */
16135
16136            // The old background's minimum size could have affected this
16137            // View's layout, so let's requestLayout
16138            requestLayout = true;
16139        }
16140
16141        computeOpaqueFlags();
16142
16143        if (requestLayout) {
16144            requestLayout();
16145        }
16146
16147        mBackgroundSizeChanged = true;
16148        invalidate(true);
16149    }
16150
16151    /**
16152     * Gets the background drawable
16153     *
16154     * @return The drawable used as the background for this view, if any.
16155     *
16156     * @see #setBackground(Drawable)
16157     *
16158     * @attr ref android.R.styleable#View_background
16159     */
16160    public Drawable getBackground() {
16161        return mBackground;
16162    }
16163
16164    /**
16165     * Sets the padding. The view may add on the space required to display
16166     * the scrollbars, depending on the style and visibility of the scrollbars.
16167     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
16168     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
16169     * from the values set in this call.
16170     *
16171     * @attr ref android.R.styleable#View_padding
16172     * @attr ref android.R.styleable#View_paddingBottom
16173     * @attr ref android.R.styleable#View_paddingLeft
16174     * @attr ref android.R.styleable#View_paddingRight
16175     * @attr ref android.R.styleable#View_paddingTop
16176     * @param left the left padding in pixels
16177     * @param top the top padding in pixels
16178     * @param right the right padding in pixels
16179     * @param bottom the bottom padding in pixels
16180     */
16181    public void setPadding(int left, int top, int right, int bottom) {
16182        resetResolvedPadding();
16183
16184        mUserPaddingStart = UNDEFINED_PADDING;
16185        mUserPaddingEnd = UNDEFINED_PADDING;
16186
16187        mUserPaddingLeftInitial = left;
16188        mUserPaddingRightInitial = right;
16189
16190        mLeftPaddingDefined = true;
16191        mRightPaddingDefined = true;
16192
16193        internalSetPadding(left, top, right, bottom);
16194    }
16195
16196    /**
16197     * @hide
16198     */
16199    protected void internalSetPadding(int left, int top, int right, int bottom) {
16200        mUserPaddingLeft = left;
16201        mUserPaddingRight = right;
16202        mUserPaddingBottom = bottom;
16203
16204        final int viewFlags = mViewFlags;
16205        boolean changed = false;
16206
16207        // Common case is there are no scroll bars.
16208        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
16209            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
16210                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
16211                        ? 0 : getVerticalScrollbarWidth();
16212                switch (mVerticalScrollbarPosition) {
16213                    case SCROLLBAR_POSITION_DEFAULT:
16214                        if (isLayoutRtl()) {
16215                            left += offset;
16216                        } else {
16217                            right += offset;
16218                        }
16219                        break;
16220                    case SCROLLBAR_POSITION_RIGHT:
16221                        right += offset;
16222                        break;
16223                    case SCROLLBAR_POSITION_LEFT:
16224                        left += offset;
16225                        break;
16226                }
16227            }
16228            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
16229                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
16230                        ? 0 : getHorizontalScrollbarHeight();
16231            }
16232        }
16233
16234        if (mPaddingLeft != left) {
16235            changed = true;
16236            mPaddingLeft = left;
16237        }
16238        if (mPaddingTop != top) {
16239            changed = true;
16240            mPaddingTop = top;
16241        }
16242        if (mPaddingRight != right) {
16243            changed = true;
16244            mPaddingRight = right;
16245        }
16246        if (mPaddingBottom != bottom) {
16247            changed = true;
16248            mPaddingBottom = bottom;
16249        }
16250
16251        if (changed) {
16252            requestLayout();
16253        }
16254    }
16255
16256    /**
16257     * Sets the relative padding. The view may add on the space required to display
16258     * the scrollbars, depending on the style and visibility of the scrollbars.
16259     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
16260     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
16261     * from the values set in this call.
16262     *
16263     * @attr ref android.R.styleable#View_padding
16264     * @attr ref android.R.styleable#View_paddingBottom
16265     * @attr ref android.R.styleable#View_paddingStart
16266     * @attr ref android.R.styleable#View_paddingEnd
16267     * @attr ref android.R.styleable#View_paddingTop
16268     * @param start the start padding in pixels
16269     * @param top the top padding in pixels
16270     * @param end the end padding in pixels
16271     * @param bottom the bottom padding in pixels
16272     */
16273    public void setPaddingRelative(int start, int top, int end, int bottom) {
16274        resetResolvedPadding();
16275
16276        mUserPaddingStart = start;
16277        mUserPaddingEnd = end;
16278        mLeftPaddingDefined = true;
16279        mRightPaddingDefined = true;
16280
16281        switch(getLayoutDirection()) {
16282            case LAYOUT_DIRECTION_RTL:
16283                mUserPaddingLeftInitial = end;
16284                mUserPaddingRightInitial = start;
16285                internalSetPadding(end, top, start, bottom);
16286                break;
16287            case LAYOUT_DIRECTION_LTR:
16288            default:
16289                mUserPaddingLeftInitial = start;
16290                mUserPaddingRightInitial = end;
16291                internalSetPadding(start, top, end, bottom);
16292        }
16293    }
16294
16295    /**
16296     * Returns the top padding of this view.
16297     *
16298     * @return the top padding in pixels
16299     */
16300    public int getPaddingTop() {
16301        return mPaddingTop;
16302    }
16303
16304    /**
16305     * Returns the bottom padding of this view. If there are inset and enabled
16306     * scrollbars, this value may include the space required to display the
16307     * scrollbars as well.
16308     *
16309     * @return the bottom padding in pixels
16310     */
16311    public int getPaddingBottom() {
16312        return mPaddingBottom;
16313    }
16314
16315    /**
16316     * Returns the left padding of this view. If there are inset and enabled
16317     * scrollbars, this value may include the space required to display the
16318     * scrollbars as well.
16319     *
16320     * @return the left padding in pixels
16321     */
16322    public int getPaddingLeft() {
16323        if (!isPaddingResolved()) {
16324            resolvePadding();
16325        }
16326        return mPaddingLeft;
16327    }
16328
16329    /**
16330     * Returns the start padding of this view depending on its resolved layout direction.
16331     * If there are inset and enabled scrollbars, this value may include the space
16332     * required to display the scrollbars as well.
16333     *
16334     * @return the start padding in pixels
16335     */
16336    public int getPaddingStart() {
16337        if (!isPaddingResolved()) {
16338            resolvePadding();
16339        }
16340        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
16341                mPaddingRight : mPaddingLeft;
16342    }
16343
16344    /**
16345     * Returns the right padding of this view. If there are inset and enabled
16346     * scrollbars, this value may include the space required to display the
16347     * scrollbars as well.
16348     *
16349     * @return the right padding in pixels
16350     */
16351    public int getPaddingRight() {
16352        if (!isPaddingResolved()) {
16353            resolvePadding();
16354        }
16355        return mPaddingRight;
16356    }
16357
16358    /**
16359     * Returns the end padding of this view depending on its resolved layout direction.
16360     * If there are inset and enabled scrollbars, this value may include the space
16361     * required to display the scrollbars as well.
16362     *
16363     * @return the end padding in pixels
16364     */
16365    public int getPaddingEnd() {
16366        if (!isPaddingResolved()) {
16367            resolvePadding();
16368        }
16369        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
16370                mPaddingLeft : mPaddingRight;
16371    }
16372
16373    /**
16374     * Return if the padding as been set thru relative values
16375     * {@link #setPaddingRelative(int, int, int, int)} or thru
16376     * @attr ref android.R.styleable#View_paddingStart or
16377     * @attr ref android.R.styleable#View_paddingEnd
16378     *
16379     * @return true if the padding is relative or false if it is not.
16380     */
16381    public boolean isPaddingRelative() {
16382        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
16383    }
16384
16385    Insets computeOpticalInsets() {
16386        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
16387    }
16388
16389    /**
16390     * @hide
16391     */
16392    public void resetPaddingToInitialValues() {
16393        if (isRtlCompatibilityMode()) {
16394            mPaddingLeft = mUserPaddingLeftInitial;
16395            mPaddingRight = mUserPaddingRightInitial;
16396            return;
16397        }
16398        if (isLayoutRtl()) {
16399            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
16400            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
16401        } else {
16402            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
16403            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
16404        }
16405    }
16406
16407    /**
16408     * @hide
16409     */
16410    public Insets getOpticalInsets() {
16411        if (mLayoutInsets == null) {
16412            mLayoutInsets = computeOpticalInsets();
16413        }
16414        return mLayoutInsets;
16415    }
16416
16417    /**
16418     * Changes the selection state of this view. A view can be selected or not.
16419     * Note that selection is not the same as focus. Views are typically
16420     * selected in the context of an AdapterView like ListView or GridView;
16421     * the selected view is the view that is highlighted.
16422     *
16423     * @param selected true if the view must be selected, false otherwise
16424     */
16425    public void setSelected(boolean selected) {
16426        //noinspection DoubleNegation
16427        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
16428            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
16429            if (!selected) resetPressedState();
16430            invalidate(true);
16431            refreshDrawableState();
16432            dispatchSetSelected(selected);
16433            notifyViewAccessibilityStateChangedIfNeeded(
16434                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
16435        }
16436    }
16437
16438    /**
16439     * Dispatch setSelected to all of this View's children.
16440     *
16441     * @see #setSelected(boolean)
16442     *
16443     * @param selected The new selected state
16444     */
16445    protected void dispatchSetSelected(boolean selected) {
16446    }
16447
16448    /**
16449     * Indicates the selection state of this view.
16450     *
16451     * @return true if the view is selected, false otherwise
16452     */
16453    @ViewDebug.ExportedProperty
16454    public boolean isSelected() {
16455        return (mPrivateFlags & PFLAG_SELECTED) != 0;
16456    }
16457
16458    /**
16459     * Changes the activated state of this view. A view can be activated or not.
16460     * Note that activation is not the same as selection.  Selection is
16461     * a transient property, representing the view (hierarchy) the user is
16462     * currently interacting with.  Activation is a longer-term state that the
16463     * user can move views in and out of.  For example, in a list view with
16464     * single or multiple selection enabled, the views in the current selection
16465     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
16466     * here.)  The activated state is propagated down to children of the view it
16467     * is set on.
16468     *
16469     * @param activated true if the view must be activated, false otherwise
16470     */
16471    public void setActivated(boolean activated) {
16472        //noinspection DoubleNegation
16473        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
16474            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
16475            invalidate(true);
16476            refreshDrawableState();
16477            dispatchSetActivated(activated);
16478        }
16479    }
16480
16481    /**
16482     * Dispatch setActivated to all of this View's children.
16483     *
16484     * @see #setActivated(boolean)
16485     *
16486     * @param activated The new activated state
16487     */
16488    protected void dispatchSetActivated(boolean activated) {
16489    }
16490
16491    /**
16492     * Indicates the activation state of this view.
16493     *
16494     * @return true if the view is activated, false otherwise
16495     */
16496    @ViewDebug.ExportedProperty
16497    public boolean isActivated() {
16498        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
16499    }
16500
16501    /**
16502     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
16503     * observer can be used to get notifications when global events, like
16504     * layout, happen.
16505     *
16506     * The returned ViewTreeObserver observer is not guaranteed to remain
16507     * valid for the lifetime of this View. If the caller of this method keeps
16508     * a long-lived reference to ViewTreeObserver, it should always check for
16509     * the return value of {@link ViewTreeObserver#isAlive()}.
16510     *
16511     * @return The ViewTreeObserver for this view's hierarchy.
16512     */
16513    public ViewTreeObserver getViewTreeObserver() {
16514        if (mAttachInfo != null) {
16515            return mAttachInfo.mTreeObserver;
16516        }
16517        if (mFloatingTreeObserver == null) {
16518            mFloatingTreeObserver = new ViewTreeObserver();
16519        }
16520        return mFloatingTreeObserver;
16521    }
16522
16523    /**
16524     * <p>Finds the topmost view in the current view hierarchy.</p>
16525     *
16526     * @return the topmost view containing this view
16527     */
16528    public View getRootView() {
16529        if (mAttachInfo != null) {
16530            final View v = mAttachInfo.mRootView;
16531            if (v != null) {
16532                return v;
16533            }
16534        }
16535
16536        View parent = this;
16537
16538        while (parent.mParent != null && parent.mParent instanceof View) {
16539            parent = (View) parent.mParent;
16540        }
16541
16542        return parent;
16543    }
16544
16545    /**
16546     * Transforms a motion event from view-local coordinates to on-screen
16547     * coordinates.
16548     *
16549     * @param ev the view-local motion event
16550     * @return false if the transformation could not be applied
16551     * @hide
16552     */
16553    public boolean toGlobalMotionEvent(MotionEvent ev) {
16554        final AttachInfo info = mAttachInfo;
16555        if (info == null) {
16556            return false;
16557        }
16558
16559        final Matrix m = info.mTmpMatrix;
16560        m.set(Matrix.IDENTITY_MATRIX);
16561        transformMatrixToGlobal(m);
16562        ev.transform(m);
16563        return true;
16564    }
16565
16566    /**
16567     * Transforms a motion event from on-screen coordinates to view-local
16568     * coordinates.
16569     *
16570     * @param ev the on-screen motion event
16571     * @return false if the transformation could not be applied
16572     * @hide
16573     */
16574    public boolean toLocalMotionEvent(MotionEvent ev) {
16575        final AttachInfo info = mAttachInfo;
16576        if (info == null) {
16577            return false;
16578        }
16579
16580        final Matrix m = info.mTmpMatrix;
16581        m.set(Matrix.IDENTITY_MATRIX);
16582        transformMatrixToLocal(m);
16583        ev.transform(m);
16584        return true;
16585    }
16586
16587    /**
16588     * Modifies the input matrix such that it maps view-local coordinates to
16589     * on-screen coordinates.
16590     *
16591     * @param m input matrix to modify
16592     */
16593    void transformMatrixToGlobal(Matrix m) {
16594        final ViewParent parent = mParent;
16595        if (parent instanceof View) {
16596            final View vp = (View) parent;
16597            vp.transformMatrixToGlobal(m);
16598            m.postTranslate(-vp.mScrollX, -vp.mScrollY);
16599        } else if (parent instanceof ViewRootImpl) {
16600            final ViewRootImpl vr = (ViewRootImpl) parent;
16601            vr.transformMatrixToGlobal(m);
16602            m.postTranslate(0, -vr.mCurScrollY);
16603        }
16604
16605        m.postTranslate(mLeft, mTop);
16606
16607        if (!hasIdentityMatrix()) {
16608            m.postConcat(getMatrix());
16609        }
16610    }
16611
16612    /**
16613     * Modifies the input matrix such that it maps on-screen coordinates to
16614     * view-local coordinates.
16615     *
16616     * @param m input matrix to modify
16617     */
16618    void transformMatrixToLocal(Matrix m) {
16619        final ViewParent parent = mParent;
16620        if (parent instanceof View) {
16621            final View vp = (View) parent;
16622            vp.transformMatrixToLocal(m);
16623            m.preTranslate(vp.mScrollX, vp.mScrollY);
16624        } else if (parent instanceof ViewRootImpl) {
16625            final ViewRootImpl vr = (ViewRootImpl) parent;
16626            vr.transformMatrixToLocal(m);
16627            m.preTranslate(0, vr.mCurScrollY);
16628        }
16629
16630        m.preTranslate(-mLeft, -mTop);
16631
16632        if (!hasIdentityMatrix()) {
16633            m.preConcat(getInverseMatrix());
16634        }
16635    }
16636
16637    /**
16638     * <p>Computes the coordinates of this view on the screen. The argument
16639     * must be an array of two integers. After the method returns, the array
16640     * contains the x and y location in that order.</p>
16641     *
16642     * @param location an array of two integers in which to hold the coordinates
16643     */
16644    public void getLocationOnScreen(int[] location) {
16645        getLocationInWindow(location);
16646
16647        final AttachInfo info = mAttachInfo;
16648        if (info != null) {
16649            location[0] += info.mWindowLeft;
16650            location[1] += info.mWindowTop;
16651        }
16652    }
16653
16654    /**
16655     * <p>Computes the coordinates of this view in its window. The argument
16656     * must be an array of two integers. After the method returns, the array
16657     * contains the x and y location in that order.</p>
16658     *
16659     * @param location an array of two integers in which to hold the coordinates
16660     */
16661    public void getLocationInWindow(int[] location) {
16662        if (location == null || location.length < 2) {
16663            throw new IllegalArgumentException("location must be an array of two integers");
16664        }
16665
16666        if (mAttachInfo == null) {
16667            // When the view is not attached to a window, this method does not make sense
16668            location[0] = location[1] = 0;
16669            return;
16670        }
16671
16672        float[] position = mAttachInfo.mTmpTransformLocation;
16673        position[0] = position[1] = 0.0f;
16674
16675        if (!hasIdentityMatrix()) {
16676            getMatrix().mapPoints(position);
16677        }
16678
16679        position[0] += mLeft;
16680        position[1] += mTop;
16681
16682        ViewParent viewParent = mParent;
16683        while (viewParent instanceof View) {
16684            final View view = (View) viewParent;
16685
16686            position[0] -= view.mScrollX;
16687            position[1] -= view.mScrollY;
16688
16689            if (!view.hasIdentityMatrix()) {
16690                view.getMatrix().mapPoints(position);
16691            }
16692
16693            position[0] += view.mLeft;
16694            position[1] += view.mTop;
16695
16696            viewParent = view.mParent;
16697         }
16698
16699        if (viewParent instanceof ViewRootImpl) {
16700            // *cough*
16701            final ViewRootImpl vr = (ViewRootImpl) viewParent;
16702            position[1] -= vr.mCurScrollY;
16703        }
16704
16705        location[0] = (int) (position[0] + 0.5f);
16706        location[1] = (int) (position[1] + 0.5f);
16707    }
16708
16709    /**
16710     * {@hide}
16711     * @param id the id of the view to be found
16712     * @return the view of the specified id, null if cannot be found
16713     */
16714    protected View findViewTraversal(int id) {
16715        if (id == mID) {
16716            return this;
16717        }
16718        return null;
16719    }
16720
16721    /**
16722     * {@hide}
16723     * @param tag the tag of the view to be found
16724     * @return the view of specified tag, null if cannot be found
16725     */
16726    protected View findViewWithTagTraversal(Object tag) {
16727        if (tag != null && tag.equals(mTag)) {
16728            return this;
16729        }
16730        return null;
16731    }
16732
16733    /**
16734     * {@hide}
16735     * @param predicate The predicate to evaluate.
16736     * @param childToSkip If not null, ignores this child during the recursive traversal.
16737     * @return The first view that matches the predicate or null.
16738     */
16739    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
16740        if (predicate.apply(this)) {
16741            return this;
16742        }
16743        return null;
16744    }
16745
16746    /**
16747     * Look for a child view with the given id.  If this view has the given
16748     * id, return this view.
16749     *
16750     * @param id The id to search for.
16751     * @return The view that has the given id in the hierarchy or null
16752     */
16753    public final View findViewById(int id) {
16754        if (id < 0) {
16755            return null;
16756        }
16757        return findViewTraversal(id);
16758    }
16759
16760    /**
16761     * Finds a view by its unuque and stable accessibility id.
16762     *
16763     * @param accessibilityId The searched accessibility id.
16764     * @return The found view.
16765     */
16766    final View findViewByAccessibilityId(int accessibilityId) {
16767        if (accessibilityId < 0) {
16768            return null;
16769        }
16770        return findViewByAccessibilityIdTraversal(accessibilityId);
16771    }
16772
16773    /**
16774     * Performs the traversal to find a view by its unuque and stable accessibility id.
16775     *
16776     * <strong>Note:</strong>This method does not stop at the root namespace
16777     * boundary since the user can touch the screen at an arbitrary location
16778     * potentially crossing the root namespace bounday which will send an
16779     * accessibility event to accessibility services and they should be able
16780     * to obtain the event source. Also accessibility ids are guaranteed to be
16781     * unique in the window.
16782     *
16783     * @param accessibilityId The accessibility id.
16784     * @return The found view.
16785     *
16786     * @hide
16787     */
16788    public View findViewByAccessibilityIdTraversal(int accessibilityId) {
16789        if (getAccessibilityViewId() == accessibilityId) {
16790            return this;
16791        }
16792        return null;
16793    }
16794
16795    /**
16796     * Look for a child view with the given tag.  If this view has the given
16797     * tag, return this view.
16798     *
16799     * @param tag The tag to search for, using "tag.equals(getTag())".
16800     * @return The View that has the given tag in the hierarchy or null
16801     */
16802    public final View findViewWithTag(Object tag) {
16803        if (tag == null) {
16804            return null;
16805        }
16806        return findViewWithTagTraversal(tag);
16807    }
16808
16809    /**
16810     * {@hide}
16811     * Look for a child view that matches the specified predicate.
16812     * If this view matches the predicate, return this view.
16813     *
16814     * @param predicate The predicate to evaluate.
16815     * @return The first view that matches the predicate or null.
16816     */
16817    public final View findViewByPredicate(Predicate<View> predicate) {
16818        return findViewByPredicateTraversal(predicate, null);
16819    }
16820
16821    /**
16822     * {@hide}
16823     * Look for a child view that matches the specified predicate,
16824     * starting with the specified view and its descendents and then
16825     * recusively searching the ancestors and siblings of that view
16826     * until this view is reached.
16827     *
16828     * This method is useful in cases where the predicate does not match
16829     * a single unique view (perhaps multiple views use the same id)
16830     * and we are trying to find the view that is "closest" in scope to the
16831     * starting view.
16832     *
16833     * @param start The view to start from.
16834     * @param predicate The predicate to evaluate.
16835     * @return The first view that matches the predicate or null.
16836     */
16837    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
16838        View childToSkip = null;
16839        for (;;) {
16840            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
16841            if (view != null || start == this) {
16842                return view;
16843            }
16844
16845            ViewParent parent = start.getParent();
16846            if (parent == null || !(parent instanceof View)) {
16847                return null;
16848            }
16849
16850            childToSkip = start;
16851            start = (View) parent;
16852        }
16853    }
16854
16855    /**
16856     * Sets the identifier for this view. The identifier does not have to be
16857     * unique in this view's hierarchy. The identifier should be a positive
16858     * number.
16859     *
16860     * @see #NO_ID
16861     * @see #getId()
16862     * @see #findViewById(int)
16863     *
16864     * @param id a number used to identify the view
16865     *
16866     * @attr ref android.R.styleable#View_id
16867     */
16868    public void setId(int id) {
16869        mID = id;
16870        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
16871            mID = generateViewId();
16872        }
16873    }
16874
16875    /**
16876     * {@hide}
16877     *
16878     * @param isRoot true if the view belongs to the root namespace, false
16879     *        otherwise
16880     */
16881    public void setIsRootNamespace(boolean isRoot) {
16882        if (isRoot) {
16883            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
16884        } else {
16885            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
16886        }
16887    }
16888
16889    /**
16890     * {@hide}
16891     *
16892     * @return true if the view belongs to the root namespace, false otherwise
16893     */
16894    public boolean isRootNamespace() {
16895        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
16896    }
16897
16898    /**
16899     * Returns this view's identifier.
16900     *
16901     * @return a positive integer used to identify the view or {@link #NO_ID}
16902     *         if the view has no ID
16903     *
16904     * @see #setId(int)
16905     * @see #findViewById(int)
16906     * @attr ref android.R.styleable#View_id
16907     */
16908    @ViewDebug.CapturedViewProperty
16909    public int getId() {
16910        return mID;
16911    }
16912
16913    /**
16914     * Returns this view's tag.
16915     *
16916     * @return the Object stored in this view as a tag, or {@code null} if not
16917     *         set
16918     *
16919     * @see #setTag(Object)
16920     * @see #getTag(int)
16921     */
16922    @ViewDebug.ExportedProperty
16923    public Object getTag() {
16924        return mTag;
16925    }
16926
16927    /**
16928     * Sets the tag associated with this view. A tag can be used to mark
16929     * a view in its hierarchy and does not have to be unique within the
16930     * hierarchy. Tags can also be used to store data within a view without
16931     * resorting to another data structure.
16932     *
16933     * @param tag an Object to tag the view with
16934     *
16935     * @see #getTag()
16936     * @see #setTag(int, Object)
16937     */
16938    public void setTag(final Object tag) {
16939        mTag = tag;
16940    }
16941
16942    /**
16943     * Returns the tag associated with this view and the specified key.
16944     *
16945     * @param key The key identifying the tag
16946     *
16947     * @return the Object stored in this view as a tag, or {@code null} if not
16948     *         set
16949     *
16950     * @see #setTag(int, Object)
16951     * @see #getTag()
16952     */
16953    public Object getTag(int key) {
16954        if (mKeyedTags != null) return mKeyedTags.get(key);
16955        return null;
16956    }
16957
16958    /**
16959     * Sets a tag associated with this view and a key. A tag can be used
16960     * to mark a view in its hierarchy and does not have to be unique within
16961     * the hierarchy. Tags can also be used to store data within a view
16962     * without resorting to another data structure.
16963     *
16964     * The specified key should be an id declared in the resources of the
16965     * application to ensure it is unique (see the <a
16966     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
16967     * Keys identified as belonging to
16968     * the Android framework or not associated with any package will cause
16969     * an {@link IllegalArgumentException} to be thrown.
16970     *
16971     * @param key The key identifying the tag
16972     * @param tag An Object to tag the view with
16973     *
16974     * @throws IllegalArgumentException If they specified key is not valid
16975     *
16976     * @see #setTag(Object)
16977     * @see #getTag(int)
16978     */
16979    public void setTag(int key, final Object tag) {
16980        // If the package id is 0x00 or 0x01, it's either an undefined package
16981        // or a framework id
16982        if ((key >>> 24) < 2) {
16983            throw new IllegalArgumentException("The key must be an application-specific "
16984                    + "resource id.");
16985        }
16986
16987        setKeyedTag(key, tag);
16988    }
16989
16990    /**
16991     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
16992     * framework id.
16993     *
16994     * @hide
16995     */
16996    public void setTagInternal(int key, Object tag) {
16997        if ((key >>> 24) != 0x1) {
16998            throw new IllegalArgumentException("The key must be a framework-specific "
16999                    + "resource id.");
17000        }
17001
17002        setKeyedTag(key, tag);
17003    }
17004
17005    private void setKeyedTag(int key, Object tag) {
17006        if (mKeyedTags == null) {
17007            mKeyedTags = new SparseArray<Object>(2);
17008        }
17009
17010        mKeyedTags.put(key, tag);
17011    }
17012
17013    /**
17014     * Prints information about this view in the log output, with the tag
17015     * {@link #VIEW_LOG_TAG}.
17016     *
17017     * @hide
17018     */
17019    public void debug() {
17020        debug(0);
17021    }
17022
17023    /**
17024     * Prints information about this view in the log output, with the tag
17025     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
17026     * indentation defined by the <code>depth</code>.
17027     *
17028     * @param depth the indentation level
17029     *
17030     * @hide
17031     */
17032    protected void debug(int depth) {
17033        String output = debugIndent(depth - 1);
17034
17035        output += "+ " + this;
17036        int id = getId();
17037        if (id != -1) {
17038            output += " (id=" + id + ")";
17039        }
17040        Object tag = getTag();
17041        if (tag != null) {
17042            output += " (tag=" + tag + ")";
17043        }
17044        Log.d(VIEW_LOG_TAG, output);
17045
17046        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
17047            output = debugIndent(depth) + " FOCUSED";
17048            Log.d(VIEW_LOG_TAG, output);
17049        }
17050
17051        output = debugIndent(depth);
17052        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
17053                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
17054                + "} ";
17055        Log.d(VIEW_LOG_TAG, output);
17056
17057        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
17058                || mPaddingBottom != 0) {
17059            output = debugIndent(depth);
17060            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
17061                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
17062            Log.d(VIEW_LOG_TAG, output);
17063        }
17064
17065        output = debugIndent(depth);
17066        output += "mMeasureWidth=" + mMeasuredWidth +
17067                " mMeasureHeight=" + mMeasuredHeight;
17068        Log.d(VIEW_LOG_TAG, output);
17069
17070        output = debugIndent(depth);
17071        if (mLayoutParams == null) {
17072            output += "BAD! no layout params";
17073        } else {
17074            output = mLayoutParams.debug(output);
17075        }
17076        Log.d(VIEW_LOG_TAG, output);
17077
17078        output = debugIndent(depth);
17079        output += "flags={";
17080        output += View.printFlags(mViewFlags);
17081        output += "}";
17082        Log.d(VIEW_LOG_TAG, output);
17083
17084        output = debugIndent(depth);
17085        output += "privateFlags={";
17086        output += View.printPrivateFlags(mPrivateFlags);
17087        output += "}";
17088        Log.d(VIEW_LOG_TAG, output);
17089    }
17090
17091    /**
17092     * Creates a string of whitespaces used for indentation.
17093     *
17094     * @param depth the indentation level
17095     * @return a String containing (depth * 2 + 3) * 2 white spaces
17096     *
17097     * @hide
17098     */
17099    protected static String debugIndent(int depth) {
17100        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
17101        for (int i = 0; i < (depth * 2) + 3; i++) {
17102            spaces.append(' ').append(' ');
17103        }
17104        return spaces.toString();
17105    }
17106
17107    /**
17108     * <p>Return the offset of the widget's text baseline from the widget's top
17109     * boundary. If this widget does not support baseline alignment, this
17110     * method returns -1. </p>
17111     *
17112     * @return the offset of the baseline within the widget's bounds or -1
17113     *         if baseline alignment is not supported
17114     */
17115    @ViewDebug.ExportedProperty(category = "layout")
17116    public int getBaseline() {
17117        return -1;
17118    }
17119
17120    /**
17121     * Returns whether the view hierarchy is currently undergoing a layout pass. This
17122     * information is useful to avoid situations such as calling {@link #requestLayout()} during
17123     * a layout pass.
17124     *
17125     * @return whether the view hierarchy is currently undergoing a layout pass
17126     */
17127    public boolean isInLayout() {
17128        ViewRootImpl viewRoot = getViewRootImpl();
17129        return (viewRoot != null && viewRoot.isInLayout());
17130    }
17131
17132    /**
17133     * Call this when something has changed which has invalidated the
17134     * layout of this view. This will schedule a layout pass of the view
17135     * tree. This should not be called while the view hierarchy is currently in a layout
17136     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
17137     * end of the current layout pass (and then layout will run again) or after the current
17138     * frame is drawn and the next layout occurs.
17139     *
17140     * <p>Subclasses which override this method should call the superclass method to
17141     * handle possible request-during-layout errors correctly.</p>
17142     */
17143    public void requestLayout() {
17144        if (mMeasureCache != null) mMeasureCache.clear();
17145
17146        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
17147            // Only trigger request-during-layout logic if this is the view requesting it,
17148            // not the views in its parent hierarchy
17149            ViewRootImpl viewRoot = getViewRootImpl();
17150            if (viewRoot != null && viewRoot.isInLayout()) {
17151                if (!viewRoot.requestLayoutDuringLayout(this)) {
17152                    return;
17153                }
17154            }
17155            mAttachInfo.mViewRequestingLayout = this;
17156        }
17157
17158        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
17159        mPrivateFlags |= PFLAG_INVALIDATED;
17160
17161        if (mParent != null && !mParent.isLayoutRequested()) {
17162            mParent.requestLayout();
17163        }
17164        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
17165            mAttachInfo.mViewRequestingLayout = null;
17166        }
17167    }
17168
17169    /**
17170     * Forces this view to be laid out during the next layout pass.
17171     * This method does not call requestLayout() or forceLayout()
17172     * on the parent.
17173     */
17174    public void forceLayout() {
17175        if (mMeasureCache != null) mMeasureCache.clear();
17176
17177        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
17178        mPrivateFlags |= PFLAG_INVALIDATED;
17179    }
17180
17181    /**
17182     * <p>
17183     * This is called to find out how big a view should be. The parent
17184     * supplies constraint information in the width and height parameters.
17185     * </p>
17186     *
17187     * <p>
17188     * The actual measurement work of a view is performed in
17189     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
17190     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
17191     * </p>
17192     *
17193     *
17194     * @param widthMeasureSpec Horizontal space requirements as imposed by the
17195     *        parent
17196     * @param heightMeasureSpec Vertical space requirements as imposed by the
17197     *        parent
17198     *
17199     * @see #onMeasure(int, int)
17200     */
17201    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
17202        boolean optical = isLayoutModeOptical(this);
17203        if (optical != isLayoutModeOptical(mParent)) {
17204            Insets insets = getOpticalInsets();
17205            int oWidth  = insets.left + insets.right;
17206            int oHeight = insets.top  + insets.bottom;
17207            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
17208            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
17209        }
17210
17211        // Suppress sign extension for the low bytes
17212        long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
17213        if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
17214
17215        if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ||
17216                widthMeasureSpec != mOldWidthMeasureSpec ||
17217                heightMeasureSpec != mOldHeightMeasureSpec) {
17218
17219            // first clears the measured dimension flag
17220            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
17221
17222            resolveRtlPropertiesIfNeeded();
17223
17224            int cacheIndex = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ? -1 :
17225                    mMeasureCache.indexOfKey(key);
17226            if (cacheIndex < 0 || sIgnoreMeasureCache) {
17227                // measure ourselves, this should set the measured dimension flag back
17228                onMeasure(widthMeasureSpec, heightMeasureSpec);
17229                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
17230            } else {
17231                long value = mMeasureCache.valueAt(cacheIndex);
17232                // Casting a long to int drops the high 32 bits, no mask needed
17233                setMeasuredDimension((int) (value >> 32), (int) value);
17234                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
17235            }
17236
17237            // flag not set, setMeasuredDimension() was not invoked, we raise
17238            // an exception to warn the developer
17239            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
17240                throw new IllegalStateException("onMeasure() did not set the"
17241                        + " measured dimension by calling"
17242                        + " setMeasuredDimension()");
17243            }
17244
17245            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
17246        }
17247
17248        mOldWidthMeasureSpec = widthMeasureSpec;
17249        mOldHeightMeasureSpec = heightMeasureSpec;
17250
17251        mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
17252                (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
17253    }
17254
17255    /**
17256     * <p>
17257     * Measure the view and its content to determine the measured width and the
17258     * measured height. This method is invoked by {@link #measure(int, int)} and
17259     * should be overriden by subclasses to provide accurate and efficient
17260     * measurement of their contents.
17261     * </p>
17262     *
17263     * <p>
17264     * <strong>CONTRACT:</strong> When overriding this method, you
17265     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
17266     * measured width and height of this view. Failure to do so will trigger an
17267     * <code>IllegalStateException</code>, thrown by
17268     * {@link #measure(int, int)}. Calling the superclass'
17269     * {@link #onMeasure(int, int)} is a valid use.
17270     * </p>
17271     *
17272     * <p>
17273     * The base class implementation of measure defaults to the background size,
17274     * unless a larger size is allowed by the MeasureSpec. Subclasses should
17275     * override {@link #onMeasure(int, int)} to provide better measurements of
17276     * their content.
17277     * </p>
17278     *
17279     * <p>
17280     * If this method is overridden, it is the subclass's responsibility to make
17281     * sure the measured height and width are at least the view's minimum height
17282     * and width ({@link #getSuggestedMinimumHeight()} and
17283     * {@link #getSuggestedMinimumWidth()}).
17284     * </p>
17285     *
17286     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
17287     *                         The requirements are encoded with
17288     *                         {@link android.view.View.MeasureSpec}.
17289     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
17290     *                         The requirements are encoded with
17291     *                         {@link android.view.View.MeasureSpec}.
17292     *
17293     * @see #getMeasuredWidth()
17294     * @see #getMeasuredHeight()
17295     * @see #setMeasuredDimension(int, int)
17296     * @see #getSuggestedMinimumHeight()
17297     * @see #getSuggestedMinimumWidth()
17298     * @see android.view.View.MeasureSpec#getMode(int)
17299     * @see android.view.View.MeasureSpec#getSize(int)
17300     */
17301    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
17302        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
17303                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
17304    }
17305
17306    /**
17307     * <p>This method must be called by {@link #onMeasure(int, int)} to store the
17308     * measured width and measured height. Failing to do so will trigger an
17309     * exception at measurement time.</p>
17310     *
17311     * @param measuredWidth The measured width of this view.  May be a complex
17312     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17313     * {@link #MEASURED_STATE_TOO_SMALL}.
17314     * @param measuredHeight The measured height of this view.  May be a complex
17315     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17316     * {@link #MEASURED_STATE_TOO_SMALL}.
17317     */
17318    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
17319        boolean optical = isLayoutModeOptical(this);
17320        if (optical != isLayoutModeOptical(mParent)) {
17321            Insets insets = getOpticalInsets();
17322            int opticalWidth  = insets.left + insets.right;
17323            int opticalHeight = insets.top  + insets.bottom;
17324
17325            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
17326            measuredHeight += optical ? opticalHeight : -opticalHeight;
17327        }
17328        mMeasuredWidth = measuredWidth;
17329        mMeasuredHeight = measuredHeight;
17330
17331        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
17332    }
17333
17334    /**
17335     * Merge two states as returned by {@link #getMeasuredState()}.
17336     * @param curState The current state as returned from a view or the result
17337     * of combining multiple views.
17338     * @param newState The new view state to combine.
17339     * @return Returns a new integer reflecting the combination of the two
17340     * states.
17341     */
17342    public static int combineMeasuredStates(int curState, int newState) {
17343        return curState | newState;
17344    }
17345
17346    /**
17347     * Version of {@link #resolveSizeAndState(int, int, int)}
17348     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
17349     */
17350    public static int resolveSize(int size, int measureSpec) {
17351        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
17352    }
17353
17354    /**
17355     * Utility to reconcile a desired size and state, with constraints imposed
17356     * by a MeasureSpec.  Will take the desired size, unless a different size
17357     * is imposed by the constraints.  The returned value is a compound integer,
17358     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
17359     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
17360     * size is smaller than the size the view wants to be.
17361     *
17362     * @param size How big the view wants to be
17363     * @param measureSpec Constraints imposed by the parent
17364     * @return Size information bit mask as defined by
17365     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
17366     */
17367    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
17368        int result = size;
17369        int specMode = MeasureSpec.getMode(measureSpec);
17370        int specSize =  MeasureSpec.getSize(measureSpec);
17371        switch (specMode) {
17372        case MeasureSpec.UNSPECIFIED:
17373            result = size;
17374            break;
17375        case MeasureSpec.AT_MOST:
17376            if (specSize < size) {
17377                result = specSize | MEASURED_STATE_TOO_SMALL;
17378            } else {
17379                result = size;
17380            }
17381            break;
17382        case MeasureSpec.EXACTLY:
17383            result = specSize;
17384            break;
17385        }
17386        return result | (childMeasuredState&MEASURED_STATE_MASK);
17387    }
17388
17389    /**
17390     * Utility to return a default size. Uses the supplied size if the
17391     * MeasureSpec imposed no constraints. Will get larger if allowed
17392     * by the MeasureSpec.
17393     *
17394     * @param size Default size for this view
17395     * @param measureSpec Constraints imposed by the parent
17396     * @return The size this view should be.
17397     */
17398    public static int getDefaultSize(int size, int measureSpec) {
17399        int result = size;
17400        int specMode = MeasureSpec.getMode(measureSpec);
17401        int specSize = MeasureSpec.getSize(measureSpec);
17402
17403        switch (specMode) {
17404        case MeasureSpec.UNSPECIFIED:
17405            result = size;
17406            break;
17407        case MeasureSpec.AT_MOST:
17408        case MeasureSpec.EXACTLY:
17409            result = specSize;
17410            break;
17411        }
17412        return result;
17413    }
17414
17415    /**
17416     * Returns the suggested minimum height that the view should use. This
17417     * returns the maximum of the view's minimum height
17418     * and the background's minimum height
17419     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
17420     * <p>
17421     * When being used in {@link #onMeasure(int, int)}, the caller should still
17422     * ensure the returned height is within the requirements of the parent.
17423     *
17424     * @return The suggested minimum height of the view.
17425     */
17426    protected int getSuggestedMinimumHeight() {
17427        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
17428
17429    }
17430
17431    /**
17432     * Returns the suggested minimum width that the view should use. This
17433     * returns the maximum of the view's minimum width)
17434     * and the background's minimum width
17435     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
17436     * <p>
17437     * When being used in {@link #onMeasure(int, int)}, the caller should still
17438     * ensure the returned width is within the requirements of the parent.
17439     *
17440     * @return The suggested minimum width of the view.
17441     */
17442    protected int getSuggestedMinimumWidth() {
17443        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
17444    }
17445
17446    /**
17447     * Returns the minimum height of the view.
17448     *
17449     * @return the minimum height the view will try to be.
17450     *
17451     * @see #setMinimumHeight(int)
17452     *
17453     * @attr ref android.R.styleable#View_minHeight
17454     */
17455    public int getMinimumHeight() {
17456        return mMinHeight;
17457    }
17458
17459    /**
17460     * Sets the minimum height of the view. It is not guaranteed the view will
17461     * be able to achieve this minimum height (for example, if its parent layout
17462     * constrains it with less available height).
17463     *
17464     * @param minHeight The minimum height the view will try to be.
17465     *
17466     * @see #getMinimumHeight()
17467     *
17468     * @attr ref android.R.styleable#View_minHeight
17469     */
17470    public void setMinimumHeight(int minHeight) {
17471        mMinHeight = minHeight;
17472        requestLayout();
17473    }
17474
17475    /**
17476     * Returns the minimum width of the view.
17477     *
17478     * @return the minimum width the view will try to be.
17479     *
17480     * @see #setMinimumWidth(int)
17481     *
17482     * @attr ref android.R.styleable#View_minWidth
17483     */
17484    public int getMinimumWidth() {
17485        return mMinWidth;
17486    }
17487
17488    /**
17489     * Sets the minimum width of the view. It is not guaranteed the view will
17490     * be able to achieve this minimum width (for example, if its parent layout
17491     * constrains it with less available width).
17492     *
17493     * @param minWidth The minimum width the view will try to be.
17494     *
17495     * @see #getMinimumWidth()
17496     *
17497     * @attr ref android.R.styleable#View_minWidth
17498     */
17499    public void setMinimumWidth(int minWidth) {
17500        mMinWidth = minWidth;
17501        requestLayout();
17502
17503    }
17504
17505    /**
17506     * Get the animation currently associated with this view.
17507     *
17508     * @return The animation that is currently playing or
17509     *         scheduled to play for this view.
17510     */
17511    public Animation getAnimation() {
17512        return mCurrentAnimation;
17513    }
17514
17515    /**
17516     * Start the specified animation now.
17517     *
17518     * @param animation the animation to start now
17519     */
17520    public void startAnimation(Animation animation) {
17521        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
17522        setAnimation(animation);
17523        invalidateParentCaches();
17524        invalidate(true);
17525    }
17526
17527    /**
17528     * Cancels any animations for this view.
17529     */
17530    public void clearAnimation() {
17531        if (mCurrentAnimation != null) {
17532            mCurrentAnimation.detach();
17533        }
17534        mCurrentAnimation = null;
17535        invalidateParentIfNeeded();
17536    }
17537
17538    /**
17539     * Sets the next animation to play for this view.
17540     * If you want the animation to play immediately, use
17541     * {@link #startAnimation(android.view.animation.Animation)} instead.
17542     * This method provides allows fine-grained
17543     * control over the start time and invalidation, but you
17544     * must make sure that 1) the animation has a start time set, and
17545     * 2) the view's parent (which controls animations on its children)
17546     * will be invalidated when the animation is supposed to
17547     * start.
17548     *
17549     * @param animation The next animation, or null.
17550     */
17551    public void setAnimation(Animation animation) {
17552        mCurrentAnimation = animation;
17553
17554        if (animation != null) {
17555            // If the screen is off assume the animation start time is now instead of
17556            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
17557            // would cause the animation to start when the screen turns back on
17558            if (mAttachInfo != null && !mAttachInfo.mScreenOn &&
17559                    animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
17560                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
17561            }
17562            animation.reset();
17563        }
17564    }
17565
17566    /**
17567     * Invoked by a parent ViewGroup to notify the start of the animation
17568     * currently associated with this view. If you override this method,
17569     * always call super.onAnimationStart();
17570     *
17571     * @see #setAnimation(android.view.animation.Animation)
17572     * @see #getAnimation()
17573     */
17574    protected void onAnimationStart() {
17575        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
17576    }
17577
17578    /**
17579     * Invoked by a parent ViewGroup to notify the end of the animation
17580     * currently associated with this view. If you override this method,
17581     * always call super.onAnimationEnd();
17582     *
17583     * @see #setAnimation(android.view.animation.Animation)
17584     * @see #getAnimation()
17585     */
17586    protected void onAnimationEnd() {
17587        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
17588    }
17589
17590    /**
17591     * Invoked if there is a Transform that involves alpha. Subclass that can
17592     * draw themselves with the specified alpha should return true, and then
17593     * respect that alpha when their onDraw() is called. If this returns false
17594     * then the view may be redirected to draw into an offscreen buffer to
17595     * fulfill the request, which will look fine, but may be slower than if the
17596     * subclass handles it internally. The default implementation returns false.
17597     *
17598     * @param alpha The alpha (0..255) to apply to the view's drawing
17599     * @return true if the view can draw with the specified alpha.
17600     */
17601    protected boolean onSetAlpha(int alpha) {
17602        return false;
17603    }
17604
17605    /**
17606     * This is used by the RootView to perform an optimization when
17607     * the view hierarchy contains one or several SurfaceView.
17608     * SurfaceView is always considered transparent, but its children are not,
17609     * therefore all View objects remove themselves from the global transparent
17610     * region (passed as a parameter to this function).
17611     *
17612     * @param region The transparent region for this ViewAncestor (window).
17613     *
17614     * @return Returns true if the effective visibility of the view at this
17615     * point is opaque, regardless of the transparent region; returns false
17616     * if it is possible for underlying windows to be seen behind the view.
17617     *
17618     * {@hide}
17619     */
17620    public boolean gatherTransparentRegion(Region region) {
17621        final AttachInfo attachInfo = mAttachInfo;
17622        if (region != null && attachInfo != null) {
17623            final int pflags = mPrivateFlags;
17624            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
17625                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
17626                // remove it from the transparent region.
17627                final int[] location = attachInfo.mTransparentLocation;
17628                getLocationInWindow(location);
17629                region.op(location[0], location[1], location[0] + mRight - mLeft,
17630                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
17631            } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) {
17632                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
17633                // exists, so we remove the background drawable's non-transparent
17634                // parts from this transparent region.
17635                applyDrawableToTransparentRegion(mBackground, region);
17636            }
17637        }
17638        return true;
17639    }
17640
17641    /**
17642     * Play a sound effect for this view.
17643     *
17644     * <p>The framework will play sound effects for some built in actions, such as
17645     * clicking, but you may wish to play these effects in your widget,
17646     * for instance, for internal navigation.
17647     *
17648     * <p>The sound effect will only be played if sound effects are enabled by the user, and
17649     * {@link #isSoundEffectsEnabled()} is true.
17650     *
17651     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
17652     */
17653    public void playSoundEffect(int soundConstant) {
17654        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
17655            return;
17656        }
17657        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
17658    }
17659
17660    /**
17661     * BZZZTT!!1!
17662     *
17663     * <p>Provide haptic feedback to the user for this view.
17664     *
17665     * <p>The framework will provide haptic feedback for some built in actions,
17666     * such as long presses, but you may wish to provide feedback for your
17667     * own widget.
17668     *
17669     * <p>The feedback will only be performed if
17670     * {@link #isHapticFeedbackEnabled()} is true.
17671     *
17672     * @param feedbackConstant One of the constants defined in
17673     * {@link HapticFeedbackConstants}
17674     */
17675    public boolean performHapticFeedback(int feedbackConstant) {
17676        return performHapticFeedback(feedbackConstant, 0);
17677    }
17678
17679    /**
17680     * BZZZTT!!1!
17681     *
17682     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
17683     *
17684     * @param feedbackConstant One of the constants defined in
17685     * {@link HapticFeedbackConstants}
17686     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
17687     */
17688    public boolean performHapticFeedback(int feedbackConstant, int flags) {
17689        if (mAttachInfo == null) {
17690            return false;
17691        }
17692        //noinspection SimplifiableIfStatement
17693        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
17694                && !isHapticFeedbackEnabled()) {
17695            return false;
17696        }
17697        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
17698                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
17699    }
17700
17701    /**
17702     * Request that the visibility of the status bar or other screen/window
17703     * decorations be changed.
17704     *
17705     * <p>This method is used to put the over device UI into temporary modes
17706     * where the user's attention is focused more on the application content,
17707     * by dimming or hiding surrounding system affordances.  This is typically
17708     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
17709     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
17710     * to be placed behind the action bar (and with these flags other system
17711     * affordances) so that smooth transitions between hiding and showing them
17712     * can be done.
17713     *
17714     * <p>Two representative examples of the use of system UI visibility is
17715     * implementing a content browsing application (like a magazine reader)
17716     * and a video playing application.
17717     *
17718     * <p>The first code shows a typical implementation of a View in a content
17719     * browsing application.  In this implementation, the application goes
17720     * into a content-oriented mode by hiding the status bar and action bar,
17721     * and putting the navigation elements into lights out mode.  The user can
17722     * then interact with content while in this mode.  Such an application should
17723     * provide an easy way for the user to toggle out of the mode (such as to
17724     * check information in the status bar or access notifications).  In the
17725     * implementation here, this is done simply by tapping on the content.
17726     *
17727     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
17728     *      content}
17729     *
17730     * <p>This second code sample shows a typical implementation of a View
17731     * in a video playing application.  In this situation, while the video is
17732     * playing the application would like to go into a complete full-screen mode,
17733     * to use as much of the display as possible for the video.  When in this state
17734     * the user can not interact with the application; the system intercepts
17735     * touching on the screen to pop the UI out of full screen mode.  See
17736     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
17737     *
17738     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
17739     *      content}
17740     *
17741     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
17742     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
17743     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
17744     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
17745     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
17746     */
17747    public void setSystemUiVisibility(int visibility) {
17748        if (visibility != mSystemUiVisibility) {
17749            mSystemUiVisibility = visibility;
17750            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
17751                mParent.recomputeViewAttributes(this);
17752            }
17753        }
17754    }
17755
17756    /**
17757     * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested.
17758     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
17759     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
17760     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
17761     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
17762     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
17763     */
17764    public int getSystemUiVisibility() {
17765        return mSystemUiVisibility;
17766    }
17767
17768    /**
17769     * Returns the current system UI visibility that is currently set for
17770     * the entire window.  This is the combination of the
17771     * {@link #setSystemUiVisibility(int)} values supplied by all of the
17772     * views in the window.
17773     */
17774    public int getWindowSystemUiVisibility() {
17775        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
17776    }
17777
17778    /**
17779     * Override to find out when the window's requested system UI visibility
17780     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
17781     * This is different from the callbacks received through
17782     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
17783     * in that this is only telling you about the local request of the window,
17784     * not the actual values applied by the system.
17785     */
17786    public void onWindowSystemUiVisibilityChanged(int visible) {
17787    }
17788
17789    /**
17790     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
17791     * the view hierarchy.
17792     */
17793    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
17794        onWindowSystemUiVisibilityChanged(visible);
17795    }
17796
17797    /**
17798     * Set a listener to receive callbacks when the visibility of the system bar changes.
17799     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
17800     */
17801    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
17802        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
17803        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
17804            mParent.recomputeViewAttributes(this);
17805        }
17806    }
17807
17808    /**
17809     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
17810     * the view hierarchy.
17811     */
17812    public void dispatchSystemUiVisibilityChanged(int visibility) {
17813        ListenerInfo li = mListenerInfo;
17814        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
17815            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
17816                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
17817        }
17818    }
17819
17820    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
17821        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
17822        if (val != mSystemUiVisibility) {
17823            setSystemUiVisibility(val);
17824            return true;
17825        }
17826        return false;
17827    }
17828
17829    /** @hide */
17830    public void setDisabledSystemUiVisibility(int flags) {
17831        if (mAttachInfo != null) {
17832            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
17833                mAttachInfo.mDisabledSystemUiVisibility = flags;
17834                if (mParent != null) {
17835                    mParent.recomputeViewAttributes(this);
17836                }
17837            }
17838        }
17839    }
17840
17841    /**
17842     * Creates an image that the system displays during the drag and drop
17843     * operation. This is called a &quot;drag shadow&quot;. The default implementation
17844     * for a DragShadowBuilder based on a View returns an image that has exactly the same
17845     * appearance as the given View. The default also positions the center of the drag shadow
17846     * directly under the touch point. If no View is provided (the constructor with no parameters
17847     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
17848     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
17849     * default is an invisible drag shadow.
17850     * <p>
17851     * You are not required to use the View you provide to the constructor as the basis of the
17852     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
17853     * anything you want as the drag shadow.
17854     * </p>
17855     * <p>
17856     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
17857     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
17858     *  size and position of the drag shadow. It uses this data to construct a
17859     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
17860     *  so that your application can draw the shadow image in the Canvas.
17861     * </p>
17862     *
17863     * <div class="special reference">
17864     * <h3>Developer Guides</h3>
17865     * <p>For a guide to implementing drag and drop features, read the
17866     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
17867     * </div>
17868     */
17869    public static class DragShadowBuilder {
17870        private final WeakReference<View> mView;
17871
17872        /**
17873         * Constructs a shadow image builder based on a View. By default, the resulting drag
17874         * shadow will have the same appearance and dimensions as the View, with the touch point
17875         * over the center of the View.
17876         * @param view A View. Any View in scope can be used.
17877         */
17878        public DragShadowBuilder(View view) {
17879            mView = new WeakReference<View>(view);
17880        }
17881
17882        /**
17883         * Construct a shadow builder object with no associated View.  This
17884         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
17885         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
17886         * to supply the drag shadow's dimensions and appearance without
17887         * reference to any View object. If they are not overridden, then the result is an
17888         * invisible drag shadow.
17889         */
17890        public DragShadowBuilder() {
17891            mView = new WeakReference<View>(null);
17892        }
17893
17894        /**
17895         * Returns the View object that had been passed to the
17896         * {@link #View.DragShadowBuilder(View)}
17897         * constructor.  If that View parameter was {@code null} or if the
17898         * {@link #View.DragShadowBuilder()}
17899         * constructor was used to instantiate the builder object, this method will return
17900         * null.
17901         *
17902         * @return The View object associate with this builder object.
17903         */
17904        @SuppressWarnings({"JavadocReference"})
17905        final public View getView() {
17906            return mView.get();
17907        }
17908
17909        /**
17910         * Provides the metrics for the shadow image. These include the dimensions of
17911         * the shadow image, and the point within that shadow that should
17912         * be centered under the touch location while dragging.
17913         * <p>
17914         * The default implementation sets the dimensions of the shadow to be the
17915         * same as the dimensions of the View itself and centers the shadow under
17916         * the touch point.
17917         * </p>
17918         *
17919         * @param shadowSize A {@link android.graphics.Point} containing the width and height
17920         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
17921         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
17922         * image.
17923         *
17924         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
17925         * shadow image that should be underneath the touch point during the drag and drop
17926         * operation. Your application must set {@link android.graphics.Point#x} to the
17927         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
17928         */
17929        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
17930            final View view = mView.get();
17931            if (view != null) {
17932                shadowSize.set(view.getWidth(), view.getHeight());
17933                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
17934            } else {
17935                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
17936            }
17937        }
17938
17939        /**
17940         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
17941         * based on the dimensions it received from the
17942         * {@link #onProvideShadowMetrics(Point, Point)} callback.
17943         *
17944         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
17945         */
17946        public void onDrawShadow(Canvas canvas) {
17947            final View view = mView.get();
17948            if (view != null) {
17949                view.draw(canvas);
17950            } else {
17951                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
17952            }
17953        }
17954    }
17955
17956    /**
17957     * Starts a drag and drop operation. When your application calls this method, it passes a
17958     * {@link android.view.View.DragShadowBuilder} object to the system. The
17959     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
17960     * to get metrics for the drag shadow, and then calls the object's
17961     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
17962     * <p>
17963     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
17964     *  drag events to all the View objects in your application that are currently visible. It does
17965     *  this either by calling the View object's drag listener (an implementation of
17966     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
17967     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
17968     *  Both are passed a {@link android.view.DragEvent} object that has a
17969     *  {@link android.view.DragEvent#getAction()} value of
17970     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
17971     * </p>
17972     * <p>
17973     * Your application can invoke startDrag() on any attached View object. The View object does not
17974     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
17975     * be related to the View the user selected for dragging.
17976     * </p>
17977     * @param data A {@link android.content.ClipData} object pointing to the data to be
17978     * transferred by the drag and drop operation.
17979     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
17980     * drag shadow.
17981     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
17982     * drop operation. This Object is put into every DragEvent object sent by the system during the
17983     * current drag.
17984     * <p>
17985     * myLocalState is a lightweight mechanism for the sending information from the dragged View
17986     * to the target Views. For example, it can contain flags that differentiate between a
17987     * a copy operation and a move operation.
17988     * </p>
17989     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
17990     * so the parameter should be set to 0.
17991     * @return {@code true} if the method completes successfully, or
17992     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
17993     * do a drag, and so no drag operation is in progress.
17994     */
17995    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
17996            Object myLocalState, int flags) {
17997        if (ViewDebug.DEBUG_DRAG) {
17998            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
17999        }
18000        boolean okay = false;
18001
18002        Point shadowSize = new Point();
18003        Point shadowTouchPoint = new Point();
18004        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
18005
18006        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
18007                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
18008            throw new IllegalStateException("Drag shadow dimensions must not be negative");
18009        }
18010
18011        if (ViewDebug.DEBUG_DRAG) {
18012            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
18013                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
18014        }
18015        Surface surface = new Surface();
18016        try {
18017            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
18018                    flags, shadowSize.x, shadowSize.y, surface);
18019            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
18020                    + " surface=" + surface);
18021            if (token != null) {
18022                Canvas canvas = surface.lockCanvas(null);
18023                try {
18024                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
18025                    shadowBuilder.onDrawShadow(canvas);
18026                } finally {
18027                    surface.unlockCanvasAndPost(canvas);
18028                }
18029
18030                final ViewRootImpl root = getViewRootImpl();
18031
18032                // Cache the local state object for delivery with DragEvents
18033                root.setLocalDragState(myLocalState);
18034
18035                // repurpose 'shadowSize' for the last touch point
18036                root.getLastTouchPoint(shadowSize);
18037
18038                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
18039                        shadowSize.x, shadowSize.y,
18040                        shadowTouchPoint.x, shadowTouchPoint.y, data);
18041                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
18042
18043                // Off and running!  Release our local surface instance; the drag
18044                // shadow surface is now managed by the system process.
18045                surface.release();
18046            }
18047        } catch (Exception e) {
18048            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
18049            surface.destroy();
18050        }
18051
18052        return okay;
18053    }
18054
18055    /**
18056     * Handles drag events sent by the system following a call to
18057     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
18058     *<p>
18059     * When the system calls this method, it passes a
18060     * {@link android.view.DragEvent} object. A call to
18061     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
18062     * in DragEvent. The method uses these to determine what is happening in the drag and drop
18063     * operation.
18064     * @param event The {@link android.view.DragEvent} sent by the system.
18065     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
18066     * in DragEvent, indicating the type of drag event represented by this object.
18067     * @return {@code true} if the method was successful, otherwise {@code false}.
18068     * <p>
18069     *  The method should return {@code true} in response to an action type of
18070     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
18071     *  operation.
18072     * </p>
18073     * <p>
18074     *  The method should also return {@code true} in response to an action type of
18075     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
18076     *  {@code false} if it didn't.
18077     * </p>
18078     */
18079    public boolean onDragEvent(DragEvent event) {
18080        return false;
18081    }
18082
18083    /**
18084     * Detects if this View is enabled and has a drag event listener.
18085     * If both are true, then it calls the drag event listener with the
18086     * {@link android.view.DragEvent} it received. If the drag event listener returns
18087     * {@code true}, then dispatchDragEvent() returns {@code true}.
18088     * <p>
18089     * For all other cases, the method calls the
18090     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
18091     * method and returns its result.
18092     * </p>
18093     * <p>
18094     * This ensures that a drag event is always consumed, even if the View does not have a drag
18095     * event listener. However, if the View has a listener and the listener returns true, then
18096     * onDragEvent() is not called.
18097     * </p>
18098     */
18099    public boolean dispatchDragEvent(DragEvent event) {
18100        ListenerInfo li = mListenerInfo;
18101        //noinspection SimplifiableIfStatement
18102        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
18103                && li.mOnDragListener.onDrag(this, event)) {
18104            return true;
18105        }
18106        return onDragEvent(event);
18107    }
18108
18109    boolean canAcceptDrag() {
18110        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
18111    }
18112
18113    /**
18114     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
18115     * it is ever exposed at all.
18116     * @hide
18117     */
18118    public void onCloseSystemDialogs(String reason) {
18119    }
18120
18121    /**
18122     * Given a Drawable whose bounds have been set to draw into this view,
18123     * update a Region being computed for
18124     * {@link #gatherTransparentRegion(android.graphics.Region)} so
18125     * that any non-transparent parts of the Drawable are removed from the
18126     * given transparent region.
18127     *
18128     * @param dr The Drawable whose transparency is to be applied to the region.
18129     * @param region A Region holding the current transparency information,
18130     * where any parts of the region that are set are considered to be
18131     * transparent.  On return, this region will be modified to have the
18132     * transparency information reduced by the corresponding parts of the
18133     * Drawable that are not transparent.
18134     * {@hide}
18135     */
18136    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
18137        if (DBG) {
18138            Log.i("View", "Getting transparent region for: " + this);
18139        }
18140        final Region r = dr.getTransparentRegion();
18141        final Rect db = dr.getBounds();
18142        final AttachInfo attachInfo = mAttachInfo;
18143        if (r != null && attachInfo != null) {
18144            final int w = getRight()-getLeft();
18145            final int h = getBottom()-getTop();
18146            if (db.left > 0) {
18147                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
18148                r.op(0, 0, db.left, h, Region.Op.UNION);
18149            }
18150            if (db.right < w) {
18151                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
18152                r.op(db.right, 0, w, h, Region.Op.UNION);
18153            }
18154            if (db.top > 0) {
18155                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
18156                r.op(0, 0, w, db.top, Region.Op.UNION);
18157            }
18158            if (db.bottom < h) {
18159                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
18160                r.op(0, db.bottom, w, h, Region.Op.UNION);
18161            }
18162            final int[] location = attachInfo.mTransparentLocation;
18163            getLocationInWindow(location);
18164            r.translate(location[0], location[1]);
18165            region.op(r, Region.Op.INTERSECT);
18166        } else {
18167            region.op(db, Region.Op.DIFFERENCE);
18168        }
18169    }
18170
18171    private void checkForLongClick(int delayOffset) {
18172        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
18173            mHasPerformedLongPress = false;
18174
18175            if (mPendingCheckForLongPress == null) {
18176                mPendingCheckForLongPress = new CheckForLongPress();
18177            }
18178            mPendingCheckForLongPress.rememberWindowAttachCount();
18179            postDelayed(mPendingCheckForLongPress,
18180                    ViewConfiguration.getLongPressTimeout() - delayOffset);
18181        }
18182    }
18183
18184    /**
18185     * Inflate a view from an XML resource.  This convenience method wraps the {@link
18186     * LayoutInflater} class, which provides a full range of options for view inflation.
18187     *
18188     * @param context The Context object for your activity or application.
18189     * @param resource The resource ID to inflate
18190     * @param root A view group that will be the parent.  Used to properly inflate the
18191     * layout_* parameters.
18192     * @see LayoutInflater
18193     */
18194    public static View inflate(Context context, int resource, ViewGroup root) {
18195        LayoutInflater factory = LayoutInflater.from(context);
18196        return factory.inflate(resource, root);
18197    }
18198
18199    /**
18200     * Scroll the view with standard behavior for scrolling beyond the normal
18201     * content boundaries. Views that call this method should override
18202     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
18203     * results of an over-scroll operation.
18204     *
18205     * Views can use this method to handle any touch or fling-based scrolling.
18206     *
18207     * @param deltaX Change in X in pixels
18208     * @param deltaY Change in Y in pixels
18209     * @param scrollX Current X scroll value in pixels before applying deltaX
18210     * @param scrollY Current Y scroll value in pixels before applying deltaY
18211     * @param scrollRangeX Maximum content scroll range along the X axis
18212     * @param scrollRangeY Maximum content scroll range along the Y axis
18213     * @param maxOverScrollX Number of pixels to overscroll by in either direction
18214     *          along the X axis.
18215     * @param maxOverScrollY Number of pixels to overscroll by in either direction
18216     *          along the Y axis.
18217     * @param isTouchEvent true if this scroll operation is the result of a touch event.
18218     * @return true if scrolling was clamped to an over-scroll boundary along either
18219     *          axis, false otherwise.
18220     */
18221    @SuppressWarnings({"UnusedParameters"})
18222    protected boolean overScrollBy(int deltaX, int deltaY,
18223            int scrollX, int scrollY,
18224            int scrollRangeX, int scrollRangeY,
18225            int maxOverScrollX, int maxOverScrollY,
18226            boolean isTouchEvent) {
18227        final int overScrollMode = mOverScrollMode;
18228        final boolean canScrollHorizontal =
18229                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
18230        final boolean canScrollVertical =
18231                computeVerticalScrollRange() > computeVerticalScrollExtent();
18232        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
18233                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
18234        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
18235                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
18236
18237        int newScrollX = scrollX + deltaX;
18238        if (!overScrollHorizontal) {
18239            maxOverScrollX = 0;
18240        }
18241
18242        int newScrollY = scrollY + deltaY;
18243        if (!overScrollVertical) {
18244            maxOverScrollY = 0;
18245        }
18246
18247        // Clamp values if at the limits and record
18248        final int left = -maxOverScrollX;
18249        final int right = maxOverScrollX + scrollRangeX;
18250        final int top = -maxOverScrollY;
18251        final int bottom = maxOverScrollY + scrollRangeY;
18252
18253        boolean clampedX = false;
18254        if (newScrollX > right) {
18255            newScrollX = right;
18256            clampedX = true;
18257        } else if (newScrollX < left) {
18258            newScrollX = left;
18259            clampedX = true;
18260        }
18261
18262        boolean clampedY = false;
18263        if (newScrollY > bottom) {
18264            newScrollY = bottom;
18265            clampedY = true;
18266        } else if (newScrollY < top) {
18267            newScrollY = top;
18268            clampedY = true;
18269        }
18270
18271        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
18272
18273        return clampedX || clampedY;
18274    }
18275
18276    /**
18277     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
18278     * respond to the results of an over-scroll operation.
18279     *
18280     * @param scrollX New X scroll value in pixels
18281     * @param scrollY New Y scroll value in pixels
18282     * @param clampedX True if scrollX was clamped to an over-scroll boundary
18283     * @param clampedY True if scrollY was clamped to an over-scroll boundary
18284     */
18285    protected void onOverScrolled(int scrollX, int scrollY,
18286            boolean clampedX, boolean clampedY) {
18287        // Intentionally empty.
18288    }
18289
18290    /**
18291     * Returns the over-scroll mode for this view. The result will be
18292     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
18293     * (allow over-scrolling only if the view content is larger than the container),
18294     * or {@link #OVER_SCROLL_NEVER}.
18295     *
18296     * @return This view's over-scroll mode.
18297     */
18298    public int getOverScrollMode() {
18299        return mOverScrollMode;
18300    }
18301
18302    /**
18303     * Set the over-scroll mode for this view. Valid over-scroll modes are
18304     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
18305     * (allow over-scrolling only if the view content is larger than the container),
18306     * or {@link #OVER_SCROLL_NEVER}.
18307     *
18308     * Setting the over-scroll mode of a view will have an effect only if the
18309     * view is capable of scrolling.
18310     *
18311     * @param overScrollMode The new over-scroll mode for this view.
18312     */
18313    public void setOverScrollMode(int overScrollMode) {
18314        if (overScrollMode != OVER_SCROLL_ALWAYS &&
18315                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
18316                overScrollMode != OVER_SCROLL_NEVER) {
18317            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
18318        }
18319        mOverScrollMode = overScrollMode;
18320    }
18321
18322    /**
18323     * Gets a scale factor that determines the distance the view should scroll
18324     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
18325     * @return The vertical scroll scale factor.
18326     * @hide
18327     */
18328    protected float getVerticalScrollFactor() {
18329        if (mVerticalScrollFactor == 0) {
18330            TypedValue outValue = new TypedValue();
18331            if (!mContext.getTheme().resolveAttribute(
18332                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
18333                throw new IllegalStateException(
18334                        "Expected theme to define listPreferredItemHeight.");
18335            }
18336            mVerticalScrollFactor = outValue.getDimension(
18337                    mContext.getResources().getDisplayMetrics());
18338        }
18339        return mVerticalScrollFactor;
18340    }
18341
18342    /**
18343     * Gets a scale factor that determines the distance the view should scroll
18344     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
18345     * @return The horizontal scroll scale factor.
18346     * @hide
18347     */
18348    protected float getHorizontalScrollFactor() {
18349        // TODO: Should use something else.
18350        return getVerticalScrollFactor();
18351    }
18352
18353    /**
18354     * Return the value specifying the text direction or policy that was set with
18355     * {@link #setTextDirection(int)}.
18356     *
18357     * @return the defined text direction. It can be one of:
18358     *
18359     * {@link #TEXT_DIRECTION_INHERIT},
18360     * {@link #TEXT_DIRECTION_FIRST_STRONG}
18361     * {@link #TEXT_DIRECTION_ANY_RTL},
18362     * {@link #TEXT_DIRECTION_LTR},
18363     * {@link #TEXT_DIRECTION_RTL},
18364     * {@link #TEXT_DIRECTION_LOCALE}
18365     *
18366     * @attr ref android.R.styleable#View_textDirection
18367     *
18368     * @hide
18369     */
18370    @ViewDebug.ExportedProperty(category = "text", mapping = {
18371            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
18372            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
18373            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
18374            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
18375            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
18376            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
18377    })
18378    public int getRawTextDirection() {
18379        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
18380    }
18381
18382    /**
18383     * Set the text direction.
18384     *
18385     * @param textDirection the direction to set. Should be one of:
18386     *
18387     * {@link #TEXT_DIRECTION_INHERIT},
18388     * {@link #TEXT_DIRECTION_FIRST_STRONG}
18389     * {@link #TEXT_DIRECTION_ANY_RTL},
18390     * {@link #TEXT_DIRECTION_LTR},
18391     * {@link #TEXT_DIRECTION_RTL},
18392     * {@link #TEXT_DIRECTION_LOCALE}
18393     *
18394     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
18395     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
18396     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
18397     *
18398     * @attr ref android.R.styleable#View_textDirection
18399     */
18400    public void setTextDirection(int textDirection) {
18401        if (getRawTextDirection() != textDirection) {
18402            // Reset the current text direction and the resolved one
18403            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
18404            resetResolvedTextDirection();
18405            // Set the new text direction
18406            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
18407            // Do resolution
18408            resolveTextDirection();
18409            // Notify change
18410            onRtlPropertiesChanged(getLayoutDirection());
18411            // Refresh
18412            requestLayout();
18413            invalidate(true);
18414        }
18415    }
18416
18417    /**
18418     * Return the resolved text direction.
18419     *
18420     * @return the resolved text direction. Returns one of:
18421     *
18422     * {@link #TEXT_DIRECTION_FIRST_STRONG}
18423     * {@link #TEXT_DIRECTION_ANY_RTL},
18424     * {@link #TEXT_DIRECTION_LTR},
18425     * {@link #TEXT_DIRECTION_RTL},
18426     * {@link #TEXT_DIRECTION_LOCALE}
18427     *
18428     * @attr ref android.R.styleable#View_textDirection
18429     */
18430    @ViewDebug.ExportedProperty(category = "text", mapping = {
18431            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
18432            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
18433            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
18434            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
18435            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
18436            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
18437    })
18438    public int getTextDirection() {
18439        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
18440    }
18441
18442    /**
18443     * Resolve the text direction.
18444     *
18445     * @return true if resolution has been done, false otherwise.
18446     *
18447     * @hide
18448     */
18449    public boolean resolveTextDirection() {
18450        // Reset any previous text direction resolution
18451        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
18452
18453        if (hasRtlSupport()) {
18454            // Set resolved text direction flag depending on text direction flag
18455            final int textDirection = getRawTextDirection();
18456            switch(textDirection) {
18457                case TEXT_DIRECTION_INHERIT:
18458                    if (!canResolveTextDirection()) {
18459                        // We cannot do the resolution if there is no parent, so use the default one
18460                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18461                        // Resolution will need to happen again later
18462                        return false;
18463                    }
18464
18465                    // Parent has not yet resolved, so we still return the default
18466                    try {
18467                        if (!mParent.isTextDirectionResolved()) {
18468                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18469                            // Resolution will need to happen again later
18470                            return false;
18471                        }
18472                    } catch (AbstractMethodError e) {
18473                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18474                                " does not fully implement ViewParent", e);
18475                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED |
18476                                PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18477                        return true;
18478                    }
18479
18480                    // Set current resolved direction to the same value as the parent's one
18481                    int parentResolvedDirection;
18482                    try {
18483                        parentResolvedDirection = mParent.getTextDirection();
18484                    } catch (AbstractMethodError e) {
18485                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18486                                " does not fully implement ViewParent", e);
18487                        parentResolvedDirection = TEXT_DIRECTION_LTR;
18488                    }
18489                    switch (parentResolvedDirection) {
18490                        case TEXT_DIRECTION_FIRST_STRONG:
18491                        case TEXT_DIRECTION_ANY_RTL:
18492                        case TEXT_DIRECTION_LTR:
18493                        case TEXT_DIRECTION_RTL:
18494                        case TEXT_DIRECTION_LOCALE:
18495                            mPrivateFlags2 |=
18496                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
18497                            break;
18498                        default:
18499                            // Default resolved direction is "first strong" heuristic
18500                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18501                    }
18502                    break;
18503                case TEXT_DIRECTION_FIRST_STRONG:
18504                case TEXT_DIRECTION_ANY_RTL:
18505                case TEXT_DIRECTION_LTR:
18506                case TEXT_DIRECTION_RTL:
18507                case TEXT_DIRECTION_LOCALE:
18508                    // Resolved direction is the same as text direction
18509                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
18510                    break;
18511                default:
18512                    // Default resolved direction is "first strong" heuristic
18513                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18514            }
18515        } else {
18516            // Default resolved direction is "first strong" heuristic
18517            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18518        }
18519
18520        // Set to resolved
18521        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
18522        return true;
18523    }
18524
18525    /**
18526     * Check if text direction resolution can be done.
18527     *
18528     * @return true if text direction resolution can be done otherwise return false.
18529     */
18530    public boolean canResolveTextDirection() {
18531        switch (getRawTextDirection()) {
18532            case TEXT_DIRECTION_INHERIT:
18533                if (mParent != null) {
18534                    try {
18535                        return mParent.canResolveTextDirection();
18536                    } catch (AbstractMethodError e) {
18537                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18538                                " does not fully implement ViewParent", e);
18539                    }
18540                }
18541                return false;
18542
18543            default:
18544                return true;
18545        }
18546    }
18547
18548    /**
18549     * Reset resolved text direction. Text direction will be resolved during a call to
18550     * {@link #onMeasure(int, int)}.
18551     *
18552     * @hide
18553     */
18554    public void resetResolvedTextDirection() {
18555        // Reset any previous text direction resolution
18556        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
18557        // Set to default value
18558        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18559    }
18560
18561    /**
18562     * @return true if text direction is inherited.
18563     *
18564     * @hide
18565     */
18566    public boolean isTextDirectionInherited() {
18567        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
18568    }
18569
18570    /**
18571     * @return true if text direction is resolved.
18572     */
18573    public boolean isTextDirectionResolved() {
18574        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
18575    }
18576
18577    /**
18578     * Return the value specifying the text alignment or policy that was set with
18579     * {@link #setTextAlignment(int)}.
18580     *
18581     * @return the defined text alignment. It can be one of:
18582     *
18583     * {@link #TEXT_ALIGNMENT_INHERIT},
18584     * {@link #TEXT_ALIGNMENT_GRAVITY},
18585     * {@link #TEXT_ALIGNMENT_CENTER},
18586     * {@link #TEXT_ALIGNMENT_TEXT_START},
18587     * {@link #TEXT_ALIGNMENT_TEXT_END},
18588     * {@link #TEXT_ALIGNMENT_VIEW_START},
18589     * {@link #TEXT_ALIGNMENT_VIEW_END}
18590     *
18591     * @attr ref android.R.styleable#View_textAlignment
18592     *
18593     * @hide
18594     */
18595    @ViewDebug.ExportedProperty(category = "text", mapping = {
18596            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
18597            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
18598            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
18599            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
18600            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
18601            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
18602            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
18603    })
18604    @TextAlignment
18605    public int getRawTextAlignment() {
18606        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
18607    }
18608
18609    /**
18610     * Set the text alignment.
18611     *
18612     * @param textAlignment The text alignment to set. Should be one of
18613     *
18614     * {@link #TEXT_ALIGNMENT_INHERIT},
18615     * {@link #TEXT_ALIGNMENT_GRAVITY},
18616     * {@link #TEXT_ALIGNMENT_CENTER},
18617     * {@link #TEXT_ALIGNMENT_TEXT_START},
18618     * {@link #TEXT_ALIGNMENT_TEXT_END},
18619     * {@link #TEXT_ALIGNMENT_VIEW_START},
18620     * {@link #TEXT_ALIGNMENT_VIEW_END}
18621     *
18622     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
18623     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
18624     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
18625     *
18626     * @attr ref android.R.styleable#View_textAlignment
18627     */
18628    public void setTextAlignment(@TextAlignment int textAlignment) {
18629        if (textAlignment != getRawTextAlignment()) {
18630            // Reset the current and resolved text alignment
18631            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
18632            resetResolvedTextAlignment();
18633            // Set the new text alignment
18634            mPrivateFlags2 |=
18635                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
18636            // Do resolution
18637            resolveTextAlignment();
18638            // Notify change
18639            onRtlPropertiesChanged(getLayoutDirection());
18640            // Refresh
18641            requestLayout();
18642            invalidate(true);
18643        }
18644    }
18645
18646    /**
18647     * Return the resolved text alignment.
18648     *
18649     * @return the resolved text alignment. Returns one of:
18650     *
18651     * {@link #TEXT_ALIGNMENT_GRAVITY},
18652     * {@link #TEXT_ALIGNMENT_CENTER},
18653     * {@link #TEXT_ALIGNMENT_TEXT_START},
18654     * {@link #TEXT_ALIGNMENT_TEXT_END},
18655     * {@link #TEXT_ALIGNMENT_VIEW_START},
18656     * {@link #TEXT_ALIGNMENT_VIEW_END}
18657     *
18658     * @attr ref android.R.styleable#View_textAlignment
18659     */
18660    @ViewDebug.ExportedProperty(category = "text", mapping = {
18661            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
18662            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
18663            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
18664            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
18665            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
18666            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
18667            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
18668    })
18669    @TextAlignment
18670    public int getTextAlignment() {
18671        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
18672                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
18673    }
18674
18675    /**
18676     * Resolve the text alignment.
18677     *
18678     * @return true if resolution has been done, false otherwise.
18679     *
18680     * @hide
18681     */
18682    public boolean resolveTextAlignment() {
18683        // Reset any previous text alignment resolution
18684        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
18685
18686        if (hasRtlSupport()) {
18687            // Set resolved text alignment flag depending on text alignment flag
18688            final int textAlignment = getRawTextAlignment();
18689            switch (textAlignment) {
18690                case TEXT_ALIGNMENT_INHERIT:
18691                    // Check if we can resolve the text alignment
18692                    if (!canResolveTextAlignment()) {
18693                        // We cannot do the resolution if there is no parent so use the default
18694                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18695                        // Resolution will need to happen again later
18696                        return false;
18697                    }
18698
18699                    // Parent has not yet resolved, so we still return the default
18700                    try {
18701                        if (!mParent.isTextAlignmentResolved()) {
18702                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18703                            // Resolution will need to happen again later
18704                            return false;
18705                        }
18706                    } catch (AbstractMethodError e) {
18707                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18708                                " does not fully implement ViewParent", e);
18709                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED |
18710                                PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18711                        return true;
18712                    }
18713
18714                    int parentResolvedTextAlignment;
18715                    try {
18716                        parentResolvedTextAlignment = mParent.getTextAlignment();
18717                    } catch (AbstractMethodError e) {
18718                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18719                                " does not fully implement ViewParent", e);
18720                        parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY;
18721                    }
18722                    switch (parentResolvedTextAlignment) {
18723                        case TEXT_ALIGNMENT_GRAVITY:
18724                        case TEXT_ALIGNMENT_TEXT_START:
18725                        case TEXT_ALIGNMENT_TEXT_END:
18726                        case TEXT_ALIGNMENT_CENTER:
18727                        case TEXT_ALIGNMENT_VIEW_START:
18728                        case TEXT_ALIGNMENT_VIEW_END:
18729                            // Resolved text alignment is the same as the parent resolved
18730                            // text alignment
18731                            mPrivateFlags2 |=
18732                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
18733                            break;
18734                        default:
18735                            // Use default resolved text alignment
18736                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18737                    }
18738                    break;
18739                case TEXT_ALIGNMENT_GRAVITY:
18740                case TEXT_ALIGNMENT_TEXT_START:
18741                case TEXT_ALIGNMENT_TEXT_END:
18742                case TEXT_ALIGNMENT_CENTER:
18743                case TEXT_ALIGNMENT_VIEW_START:
18744                case TEXT_ALIGNMENT_VIEW_END:
18745                    // Resolved text alignment is the same as text alignment
18746                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
18747                    break;
18748                default:
18749                    // Use default resolved text alignment
18750                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18751            }
18752        } else {
18753            // Use default resolved text alignment
18754            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18755        }
18756
18757        // Set the resolved
18758        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
18759        return true;
18760    }
18761
18762    /**
18763     * Check if text alignment resolution can be done.
18764     *
18765     * @return true if text alignment resolution can be done otherwise return false.
18766     */
18767    public boolean canResolveTextAlignment() {
18768        switch (getRawTextAlignment()) {
18769            case TEXT_DIRECTION_INHERIT:
18770                if (mParent != null) {
18771                    try {
18772                        return mParent.canResolveTextAlignment();
18773                    } catch (AbstractMethodError e) {
18774                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18775                                " does not fully implement ViewParent", e);
18776                    }
18777                }
18778                return false;
18779
18780            default:
18781                return true;
18782        }
18783    }
18784
18785    /**
18786     * Reset resolved text alignment. Text alignment will be resolved during a call to
18787     * {@link #onMeasure(int, int)}.
18788     *
18789     * @hide
18790     */
18791    public void resetResolvedTextAlignment() {
18792        // Reset any previous text alignment resolution
18793        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
18794        // Set to default
18795        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18796    }
18797
18798    /**
18799     * @return true if text alignment is inherited.
18800     *
18801     * @hide
18802     */
18803    public boolean isTextAlignmentInherited() {
18804        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
18805    }
18806
18807    /**
18808     * @return true if text alignment is resolved.
18809     */
18810    public boolean isTextAlignmentResolved() {
18811        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
18812    }
18813
18814    /**
18815     * Generate a value suitable for use in {@link #setId(int)}.
18816     * This value will not collide with ID values generated at build time by aapt for R.id.
18817     *
18818     * @return a generated ID value
18819     */
18820    public static int generateViewId() {
18821        for (;;) {
18822            final int result = sNextGeneratedId.get();
18823            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
18824            int newValue = result + 1;
18825            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
18826            if (sNextGeneratedId.compareAndSet(result, newValue)) {
18827                return result;
18828            }
18829        }
18830    }
18831
18832    /**
18833     * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions.
18834     * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and
18835     *                           a normal View or a ViewGroup with
18836     *                           {@link android.view.ViewGroup#isTransitionGroup()} true.
18837     * @hide
18838     */
18839    public void captureTransitioningViews(List<View> transitioningViews) {
18840        if (getVisibility() == View.VISIBLE) {
18841            transitioningViews.add(this);
18842        }
18843    }
18844
18845    /**
18846     * Adds all Views that have {@link #getSharedElementName()} non-null to sharedElements.
18847     * @param sharedElements Will contain all Views in the hierarchy having a shared element name.
18848     * @hide
18849     */
18850    public void findSharedElements(Map<String, View> sharedElements) {
18851        if (getVisibility() == VISIBLE) {
18852            String sharedElementName = getSharedElementName();
18853            if (sharedElementName != null) {
18854                sharedElements.put(sharedElementName, this);
18855            }
18856        }
18857    }
18858
18859    //
18860    // Properties
18861    //
18862    /**
18863     * A Property wrapper around the <code>alpha</code> functionality handled by the
18864     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
18865     */
18866    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
18867        @Override
18868        public void setValue(View object, float value) {
18869            object.setAlpha(value);
18870        }
18871
18872        @Override
18873        public Float get(View object) {
18874            return object.getAlpha();
18875        }
18876    };
18877
18878    /**
18879     * A Property wrapper around the <code>translationX</code> functionality handled by the
18880     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
18881     */
18882    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
18883        @Override
18884        public void setValue(View object, float value) {
18885            object.setTranslationX(value);
18886        }
18887
18888                @Override
18889        public Float get(View object) {
18890            return object.getTranslationX();
18891        }
18892    };
18893
18894    /**
18895     * A Property wrapper around the <code>translationY</code> functionality handled by the
18896     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
18897     */
18898    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
18899        @Override
18900        public void setValue(View object, float value) {
18901            object.setTranslationY(value);
18902        }
18903
18904        @Override
18905        public Float get(View object) {
18906            return object.getTranslationY();
18907        }
18908    };
18909
18910    /**
18911     * A Property wrapper around the <code>translationZ</code> functionality handled by the
18912     * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods.
18913     */
18914    public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") {
18915        @Override
18916        public void setValue(View object, float value) {
18917            object.setTranslationZ(value);
18918        }
18919
18920        @Override
18921        public Float get(View object) {
18922            return object.getTranslationZ();
18923        }
18924    };
18925
18926    /**
18927     * A Property wrapper around the <code>x</code> functionality handled by the
18928     * {@link View#setX(float)} and {@link View#getX()} methods.
18929     */
18930    public static final Property<View, Float> X = new FloatProperty<View>("x") {
18931        @Override
18932        public void setValue(View object, float value) {
18933            object.setX(value);
18934        }
18935
18936        @Override
18937        public Float get(View object) {
18938            return object.getX();
18939        }
18940    };
18941
18942    /**
18943     * A Property wrapper around the <code>y</code> functionality handled by the
18944     * {@link View#setY(float)} and {@link View#getY()} methods.
18945     */
18946    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
18947        @Override
18948        public void setValue(View object, float value) {
18949            object.setY(value);
18950        }
18951
18952        @Override
18953        public Float get(View object) {
18954            return object.getY();
18955        }
18956    };
18957
18958    /**
18959     * A Property wrapper around the <code>rotation</code> functionality handled by the
18960     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
18961     */
18962    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
18963        @Override
18964        public void setValue(View object, float value) {
18965            object.setRotation(value);
18966        }
18967
18968        @Override
18969        public Float get(View object) {
18970            return object.getRotation();
18971        }
18972    };
18973
18974    /**
18975     * A Property wrapper around the <code>rotationX</code> functionality handled by the
18976     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
18977     */
18978    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
18979        @Override
18980        public void setValue(View object, float value) {
18981            object.setRotationX(value);
18982        }
18983
18984        @Override
18985        public Float get(View object) {
18986            return object.getRotationX();
18987        }
18988    };
18989
18990    /**
18991     * A Property wrapper around the <code>rotationY</code> functionality handled by the
18992     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
18993     */
18994    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
18995        @Override
18996        public void setValue(View object, float value) {
18997            object.setRotationY(value);
18998        }
18999
19000        @Override
19001        public Float get(View object) {
19002            return object.getRotationY();
19003        }
19004    };
19005
19006    /**
19007     * A Property wrapper around the <code>scaleX</code> functionality handled by the
19008     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
19009     */
19010    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
19011        @Override
19012        public void setValue(View object, float value) {
19013            object.setScaleX(value);
19014        }
19015
19016        @Override
19017        public Float get(View object) {
19018            return object.getScaleX();
19019        }
19020    };
19021
19022    /**
19023     * A Property wrapper around the <code>scaleY</code> functionality handled by the
19024     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
19025     */
19026    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
19027        @Override
19028        public void setValue(View object, float value) {
19029            object.setScaleY(value);
19030        }
19031
19032        @Override
19033        public Float get(View object) {
19034            return object.getScaleY();
19035        }
19036    };
19037
19038    /**
19039     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
19040     * Each MeasureSpec represents a requirement for either the width or the height.
19041     * A MeasureSpec is comprised of a size and a mode. There are three possible
19042     * modes:
19043     * <dl>
19044     * <dt>UNSPECIFIED</dt>
19045     * <dd>
19046     * The parent has not imposed any constraint on the child. It can be whatever size
19047     * it wants.
19048     * </dd>
19049     *
19050     * <dt>EXACTLY</dt>
19051     * <dd>
19052     * The parent has determined an exact size for the child. The child is going to be
19053     * given those bounds regardless of how big it wants to be.
19054     * </dd>
19055     *
19056     * <dt>AT_MOST</dt>
19057     * <dd>
19058     * The child can be as large as it wants up to the specified size.
19059     * </dd>
19060     * </dl>
19061     *
19062     * MeasureSpecs are implemented as ints to reduce object allocation. This class
19063     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
19064     */
19065    public static class MeasureSpec {
19066        private static final int MODE_SHIFT = 30;
19067        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
19068
19069        /**
19070         * Measure specification mode: The parent has not imposed any constraint
19071         * on the child. It can be whatever size it wants.
19072         */
19073        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
19074
19075        /**
19076         * Measure specification mode: The parent has determined an exact size
19077         * for the child. The child is going to be given those bounds regardless
19078         * of how big it wants to be.
19079         */
19080        public static final int EXACTLY     = 1 << MODE_SHIFT;
19081
19082        /**
19083         * Measure specification mode: The child can be as large as it wants up
19084         * to the specified size.
19085         */
19086        public static final int AT_MOST     = 2 << MODE_SHIFT;
19087
19088        /**
19089         * Creates a measure specification based on the supplied size and mode.
19090         *
19091         * The mode must always be one of the following:
19092         * <ul>
19093         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
19094         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
19095         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
19096         * </ul>
19097         *
19098         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
19099         * implementation was such that the order of arguments did not matter
19100         * and overflow in either value could impact the resulting MeasureSpec.
19101         * {@link android.widget.RelativeLayout} was affected by this bug.
19102         * Apps targeting API levels greater than 17 will get the fixed, more strict
19103         * behavior.</p>
19104         *
19105         * @param size the size of the measure specification
19106         * @param mode the mode of the measure specification
19107         * @return the measure specification based on size and mode
19108         */
19109        public static int makeMeasureSpec(int size, int mode) {
19110            if (sUseBrokenMakeMeasureSpec) {
19111                return size + mode;
19112            } else {
19113                return (size & ~MODE_MASK) | (mode & MODE_MASK);
19114            }
19115        }
19116
19117        /**
19118         * Extracts the mode from the supplied measure specification.
19119         *
19120         * @param measureSpec the measure specification to extract the mode from
19121         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
19122         *         {@link android.view.View.MeasureSpec#AT_MOST} or
19123         *         {@link android.view.View.MeasureSpec#EXACTLY}
19124         */
19125        public static int getMode(int measureSpec) {
19126            return (measureSpec & MODE_MASK);
19127        }
19128
19129        /**
19130         * Extracts the size from the supplied measure specification.
19131         *
19132         * @param measureSpec the measure specification to extract the size from
19133         * @return the size in pixels defined in the supplied measure specification
19134         */
19135        public static int getSize(int measureSpec) {
19136            return (measureSpec & ~MODE_MASK);
19137        }
19138
19139        static int adjust(int measureSpec, int delta) {
19140            return makeMeasureSpec(getSize(measureSpec + delta), getMode(measureSpec));
19141        }
19142
19143        /**
19144         * Returns a String representation of the specified measure
19145         * specification.
19146         *
19147         * @param measureSpec the measure specification to convert to a String
19148         * @return a String with the following format: "MeasureSpec: MODE SIZE"
19149         */
19150        public static String toString(int measureSpec) {
19151            int mode = getMode(measureSpec);
19152            int size = getSize(measureSpec);
19153
19154            StringBuilder sb = new StringBuilder("MeasureSpec: ");
19155
19156            if (mode == UNSPECIFIED)
19157                sb.append("UNSPECIFIED ");
19158            else if (mode == EXACTLY)
19159                sb.append("EXACTLY ");
19160            else if (mode == AT_MOST)
19161                sb.append("AT_MOST ");
19162            else
19163                sb.append(mode).append(" ");
19164
19165            sb.append(size);
19166            return sb.toString();
19167        }
19168    }
19169
19170    class CheckForLongPress implements Runnable {
19171
19172        private int mOriginalWindowAttachCount;
19173
19174        public void run() {
19175            if (isPressed() && (mParent != null)
19176                    && mOriginalWindowAttachCount == mWindowAttachCount) {
19177                if (performLongClick()) {
19178                    mHasPerformedLongPress = true;
19179                }
19180            }
19181        }
19182
19183        public void rememberWindowAttachCount() {
19184            mOriginalWindowAttachCount = mWindowAttachCount;
19185        }
19186    }
19187
19188    private final class CheckForTap implements Runnable {
19189        public void run() {
19190            mPrivateFlags &= ~PFLAG_PREPRESSED;
19191            setPressed(true);
19192            checkForLongClick(ViewConfiguration.getTapTimeout());
19193        }
19194    }
19195
19196    private final class PerformClick implements Runnable {
19197        public void run() {
19198            performClick();
19199        }
19200    }
19201
19202    /** @hide */
19203    public void hackTurnOffWindowResizeAnim(boolean off) {
19204        mAttachInfo.mTurnOffWindowResizeAnim = off;
19205    }
19206
19207    /**
19208     * This method returns a ViewPropertyAnimator object, which can be used to animate
19209     * specific properties on this View.
19210     *
19211     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
19212     */
19213    public ViewPropertyAnimator animate() {
19214        if (mAnimator == null) {
19215            mAnimator = new ViewPropertyAnimator(this);
19216        }
19217        return mAnimator;
19218    }
19219
19220    /**
19221     * Specifies that the shared name of the View to be shared with another Activity.
19222     * When transitioning between Activities, the name links a UI element in the starting
19223     * Activity to UI element in the called Activity. Names should be unique in the
19224     * View hierarchy.
19225     *
19226     * @param sharedElementName The cross-Activity View identifier. The called Activity will use
19227     *                 the name to match the location with a View in its layout.
19228     * @see android.app.ActivityOptions#makeSceneTransitionAnimation(android.os.Bundle)
19229     */
19230    public void setSharedElementName(String sharedElementName) {
19231        setTagInternal(com.android.internal.R.id.shared_element_name, sharedElementName);
19232    }
19233
19234    /**
19235     * Returns the shared name of the View to be shared with another Activity.
19236     * When transitioning between Activities, the name links a UI element in the starting
19237     * Activity to UI element in the called Activity. Names should be unique in the
19238     * View hierarchy.
19239     *
19240     * <p>This returns null if the View is not a shared element or the name if it is.</p>
19241     *
19242     * @return The name used for this View for cross-Activity transitions or null if
19243     * this View has not been identified as shared.
19244     */
19245    public String getSharedElementName() {
19246        return (String) getTag(com.android.internal.R.id.shared_element_name);
19247    }
19248
19249    /**
19250     * Interface definition for a callback to be invoked when a hardware key event is
19251     * dispatched to this view. The callback will be invoked before the key event is
19252     * given to the view. This is only useful for hardware keyboards; a software input
19253     * method has no obligation to trigger this listener.
19254     */
19255    public interface OnKeyListener {
19256        /**
19257         * Called when a hardware key is dispatched to a view. This allows listeners to
19258         * get a chance to respond before the target view.
19259         * <p>Key presses in software keyboards will generally NOT trigger this method,
19260         * although some may elect to do so in some situations. Do not assume a
19261         * software input method has to be key-based; even if it is, it may use key presses
19262         * in a different way than you expect, so there is no way to reliably catch soft
19263         * input key presses.
19264         *
19265         * @param v The view the key has been dispatched to.
19266         * @param keyCode The code for the physical key that was pressed
19267         * @param event The KeyEvent object containing full information about
19268         *        the event.
19269         * @return True if the listener has consumed the event, false otherwise.
19270         */
19271        boolean onKey(View v, int keyCode, KeyEvent event);
19272    }
19273
19274    /**
19275     * Interface definition for a callback to be invoked when a touch event is
19276     * dispatched to this view. The callback will be invoked before the touch
19277     * event is given to the view.
19278     */
19279    public interface OnTouchListener {
19280        /**
19281         * Called when a touch event is dispatched to a view. This allows listeners to
19282         * get a chance to respond before the target view.
19283         *
19284         * @param v The view the touch event has been dispatched to.
19285         * @param event The MotionEvent object containing full information about
19286         *        the event.
19287         * @return True if the listener has consumed the event, false otherwise.
19288         */
19289        boolean onTouch(View v, MotionEvent event);
19290    }
19291
19292    /**
19293     * Interface definition for a callback to be invoked when a hover event is
19294     * dispatched to this view. The callback will be invoked before the hover
19295     * event is given to the view.
19296     */
19297    public interface OnHoverListener {
19298        /**
19299         * Called when a hover event is dispatched to a view. This allows listeners to
19300         * get a chance to respond before the target view.
19301         *
19302         * @param v The view the hover event has been dispatched to.
19303         * @param event The MotionEvent object containing full information about
19304         *        the event.
19305         * @return True if the listener has consumed the event, false otherwise.
19306         */
19307        boolean onHover(View v, MotionEvent event);
19308    }
19309
19310    /**
19311     * Interface definition for a callback to be invoked when a generic motion event is
19312     * dispatched to this view. The callback will be invoked before the generic motion
19313     * event is given to the view.
19314     */
19315    public interface OnGenericMotionListener {
19316        /**
19317         * Called when a generic motion event is dispatched to a view. This allows listeners to
19318         * get a chance to respond before the target view.
19319         *
19320         * @param v The view the generic motion event has been dispatched to.
19321         * @param event The MotionEvent object containing full information about
19322         *        the event.
19323         * @return True if the listener has consumed the event, false otherwise.
19324         */
19325        boolean onGenericMotion(View v, MotionEvent event);
19326    }
19327
19328    /**
19329     * Interface definition for a callback to be invoked when a view has been clicked and held.
19330     */
19331    public interface OnLongClickListener {
19332        /**
19333         * Called when a view has been clicked and held.
19334         *
19335         * @param v The view that was clicked and held.
19336         *
19337         * @return true if the callback consumed the long click, false otherwise.
19338         */
19339        boolean onLongClick(View v);
19340    }
19341
19342    /**
19343     * Interface definition for a callback to be invoked when a drag is being dispatched
19344     * to this view.  The callback will be invoked before the hosting view's own
19345     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
19346     * onDrag(event) behavior, it should return 'false' from this callback.
19347     *
19348     * <div class="special reference">
19349     * <h3>Developer Guides</h3>
19350     * <p>For a guide to implementing drag and drop features, read the
19351     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
19352     * </div>
19353     */
19354    public interface OnDragListener {
19355        /**
19356         * Called when a drag event is dispatched to a view. This allows listeners
19357         * to get a chance to override base View behavior.
19358         *
19359         * @param v The View that received the drag event.
19360         * @param event The {@link android.view.DragEvent} object for the drag event.
19361         * @return {@code true} if the drag event was handled successfully, or {@code false}
19362         * if the drag event was not handled. Note that {@code false} will trigger the View
19363         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
19364         */
19365        boolean onDrag(View v, DragEvent event);
19366    }
19367
19368    /**
19369     * Interface definition for a callback to be invoked when the focus state of
19370     * a view changed.
19371     */
19372    public interface OnFocusChangeListener {
19373        /**
19374         * Called when the focus state of a view has changed.
19375         *
19376         * @param v The view whose state has changed.
19377         * @param hasFocus The new focus state of v.
19378         */
19379        void onFocusChange(View v, boolean hasFocus);
19380    }
19381
19382    /**
19383     * Interface definition for a callback to be invoked when a view is clicked.
19384     */
19385    public interface OnClickListener {
19386        /**
19387         * Called when a view has been clicked.
19388         *
19389         * @param v The view that was clicked.
19390         */
19391        void onClick(View v);
19392    }
19393
19394    /**
19395     * Interface definition for a callback to be invoked when the context menu
19396     * for this view is being built.
19397     */
19398    public interface OnCreateContextMenuListener {
19399        /**
19400         * Called when the context menu for this view is being built. It is not
19401         * safe to hold onto the menu after this method returns.
19402         *
19403         * @param menu The context menu that is being built
19404         * @param v The view for which the context menu is being built
19405         * @param menuInfo Extra information about the item for which the
19406         *            context menu should be shown. This information will vary
19407         *            depending on the class of v.
19408         */
19409        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
19410    }
19411
19412    /**
19413     * Interface definition for a callback to be invoked when the status bar changes
19414     * visibility.  This reports <strong>global</strong> changes to the system UI
19415     * state, not what the application is requesting.
19416     *
19417     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
19418     */
19419    public interface OnSystemUiVisibilityChangeListener {
19420        /**
19421         * Called when the status bar changes visibility because of a call to
19422         * {@link View#setSystemUiVisibility(int)}.
19423         *
19424         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
19425         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
19426         * This tells you the <strong>global</strong> state of these UI visibility
19427         * flags, not what your app is currently applying.
19428         */
19429        public void onSystemUiVisibilityChange(int visibility);
19430    }
19431
19432    /**
19433     * Interface definition for a callback to be invoked when this view is attached
19434     * or detached from its window.
19435     */
19436    public interface OnAttachStateChangeListener {
19437        /**
19438         * Called when the view is attached to a window.
19439         * @param v The view that was attached
19440         */
19441        public void onViewAttachedToWindow(View v);
19442        /**
19443         * Called when the view is detached from a window.
19444         * @param v The view that was detached
19445         */
19446        public void onViewDetachedFromWindow(View v);
19447    }
19448
19449    /**
19450     * Listener for applying window insets on a view in a custom way.
19451     *
19452     * <p>Apps may choose to implement this interface if they want to apply custom policy
19453     * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener
19454     * is set, its
19455     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
19456     * method will be called instead of the View's own
19457     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener
19458     * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply
19459     * the View's normal behavior as part of its own.</p>
19460     */
19461    public interface OnApplyWindowInsetsListener {
19462        /**
19463         * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set}
19464         * on a View, this listener method will be called instead of the view's own
19465         * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
19466         *
19467         * @param v The view applying window insets
19468         * @param insets The insets to apply
19469         * @return The insets supplied, minus any insets that were consumed
19470         */
19471        public WindowInsets onApplyWindowInsets(View v, WindowInsets insets);
19472    }
19473
19474    private final class UnsetPressedState implements Runnable {
19475        public void run() {
19476            setPressed(false);
19477        }
19478    }
19479
19480    /**
19481     * Base class for derived classes that want to save and restore their own
19482     * state in {@link android.view.View#onSaveInstanceState()}.
19483     */
19484    public static class BaseSavedState extends AbsSavedState {
19485        /**
19486         * Constructor used when reading from a parcel. Reads the state of the superclass.
19487         *
19488         * @param source
19489         */
19490        public BaseSavedState(Parcel source) {
19491            super(source);
19492        }
19493
19494        /**
19495         * Constructor called by derived classes when creating their SavedState objects
19496         *
19497         * @param superState The state of the superclass of this view
19498         */
19499        public BaseSavedState(Parcelable superState) {
19500            super(superState);
19501        }
19502
19503        public static final Parcelable.Creator<BaseSavedState> CREATOR =
19504                new Parcelable.Creator<BaseSavedState>() {
19505            public BaseSavedState createFromParcel(Parcel in) {
19506                return new BaseSavedState(in);
19507            }
19508
19509            public BaseSavedState[] newArray(int size) {
19510                return new BaseSavedState[size];
19511            }
19512        };
19513    }
19514
19515    /**
19516     * A set of information given to a view when it is attached to its parent
19517     * window.
19518     */
19519    static class AttachInfo {
19520        interface Callbacks {
19521            void playSoundEffect(int effectId);
19522            boolean performHapticFeedback(int effectId, boolean always);
19523        }
19524
19525        /**
19526         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
19527         * to a Handler. This class contains the target (View) to invalidate and
19528         * the coordinates of the dirty rectangle.
19529         *
19530         * For performance purposes, this class also implements a pool of up to
19531         * POOL_LIMIT objects that get reused. This reduces memory allocations
19532         * whenever possible.
19533         */
19534        static class InvalidateInfo {
19535            private static final int POOL_LIMIT = 10;
19536
19537            private static final SynchronizedPool<InvalidateInfo> sPool =
19538                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
19539
19540            View target;
19541
19542            int left;
19543            int top;
19544            int right;
19545            int bottom;
19546
19547            public static InvalidateInfo obtain() {
19548                InvalidateInfo instance = sPool.acquire();
19549                return (instance != null) ? instance : new InvalidateInfo();
19550            }
19551
19552            public void recycle() {
19553                target = null;
19554                sPool.release(this);
19555            }
19556        }
19557
19558        final IWindowSession mSession;
19559
19560        final IWindow mWindow;
19561
19562        final IBinder mWindowToken;
19563
19564        final Display mDisplay;
19565
19566        final Callbacks mRootCallbacks;
19567
19568        IWindowId mIWindowId;
19569        WindowId mWindowId;
19570
19571        /**
19572         * The top view of the hierarchy.
19573         */
19574        View mRootView;
19575
19576        IBinder mPanelParentWindowToken;
19577
19578        boolean mHardwareAccelerated;
19579        boolean mHardwareAccelerationRequested;
19580        HardwareRenderer mHardwareRenderer;
19581
19582        boolean mScreenOn;
19583
19584        /**
19585         * Scale factor used by the compatibility mode
19586         */
19587        float mApplicationScale;
19588
19589        /**
19590         * Indicates whether the application is in compatibility mode
19591         */
19592        boolean mScalingRequired;
19593
19594        /**
19595         * If set, ViewRootImpl doesn't use its lame animation for when the window resizes.
19596         */
19597        boolean mTurnOffWindowResizeAnim;
19598
19599        /**
19600         * Left position of this view's window
19601         */
19602        int mWindowLeft;
19603
19604        /**
19605         * Top position of this view's window
19606         */
19607        int mWindowTop;
19608
19609        /**
19610         * Indicates whether views need to use 32-bit drawing caches
19611         */
19612        boolean mUse32BitDrawingCache;
19613
19614        /**
19615         * For windows that are full-screen but using insets to layout inside
19616         * of the screen areas, these are the current insets to appear inside
19617         * the overscan area of the display.
19618         */
19619        final Rect mOverscanInsets = new Rect();
19620
19621        /**
19622         * For windows that are full-screen but using insets to layout inside
19623         * of the screen decorations, these are the current insets for the
19624         * content of the window.
19625         */
19626        final Rect mContentInsets = new Rect();
19627
19628        /**
19629         * For windows that are full-screen but using insets to layout inside
19630         * of the screen decorations, these are the current insets for the
19631         * actual visible parts of the window.
19632         */
19633        final Rect mVisibleInsets = new Rect();
19634
19635        /**
19636         * The internal insets given by this window.  This value is
19637         * supplied by the client (through
19638         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
19639         * be given to the window manager when changed to be used in laying
19640         * out windows behind it.
19641         */
19642        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
19643                = new ViewTreeObserver.InternalInsetsInfo();
19644
19645        /**
19646         * Set to true when mGivenInternalInsets is non-empty.
19647         */
19648        boolean mHasNonEmptyGivenInternalInsets;
19649
19650        /**
19651         * All views in the window's hierarchy that serve as scroll containers,
19652         * used to determine if the window can be resized or must be panned
19653         * to adjust for a soft input area.
19654         */
19655        final ArrayList<View> mScrollContainers = new ArrayList<View>();
19656
19657        final KeyEvent.DispatcherState mKeyDispatchState
19658                = new KeyEvent.DispatcherState();
19659
19660        /**
19661         * Indicates whether the view's window currently has the focus.
19662         */
19663        boolean mHasWindowFocus;
19664
19665        /**
19666         * The current visibility of the window.
19667         */
19668        int mWindowVisibility;
19669
19670        /**
19671         * Indicates the time at which drawing started to occur.
19672         */
19673        long mDrawingTime;
19674
19675        /**
19676         * Indicates whether or not ignoring the DIRTY_MASK flags.
19677         */
19678        boolean mIgnoreDirtyState;
19679
19680        /**
19681         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
19682         * to avoid clearing that flag prematurely.
19683         */
19684        boolean mSetIgnoreDirtyState = false;
19685
19686        /**
19687         * Indicates whether the view's window is currently in touch mode.
19688         */
19689        boolean mInTouchMode;
19690
19691        /**
19692         * Indicates that ViewAncestor should trigger a global layout change
19693         * the next time it performs a traversal
19694         */
19695        boolean mRecomputeGlobalAttributes;
19696
19697        /**
19698         * Always report new attributes at next traversal.
19699         */
19700        boolean mForceReportNewAttributes;
19701
19702        /**
19703         * Set during a traveral if any views want to keep the screen on.
19704         */
19705        boolean mKeepScreenOn;
19706
19707        /**
19708         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
19709         */
19710        int mSystemUiVisibility;
19711
19712        /**
19713         * Hack to force certain system UI visibility flags to be cleared.
19714         */
19715        int mDisabledSystemUiVisibility;
19716
19717        /**
19718         * Last global system UI visibility reported by the window manager.
19719         */
19720        int mGlobalSystemUiVisibility;
19721
19722        /**
19723         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
19724         * attached.
19725         */
19726        boolean mHasSystemUiListeners;
19727
19728        /**
19729         * Set if the window has requested to extend into the overscan region
19730         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
19731         */
19732        boolean mOverscanRequested;
19733
19734        /**
19735         * Set if the visibility of any views has changed.
19736         */
19737        boolean mViewVisibilityChanged;
19738
19739        /**
19740         * Set to true if a view has been scrolled.
19741         */
19742        boolean mViewScrollChanged;
19743
19744        /**
19745         * Global to the view hierarchy used as a temporary for dealing with
19746         * x/y points in the transparent region computations.
19747         */
19748        final int[] mTransparentLocation = new int[2];
19749
19750        /**
19751         * Global to the view hierarchy used as a temporary for dealing with
19752         * x/y points in the ViewGroup.invalidateChild implementation.
19753         */
19754        final int[] mInvalidateChildLocation = new int[2];
19755
19756
19757        /**
19758         * Global to the view hierarchy used as a temporary for dealing with
19759         * x/y location when view is transformed.
19760         */
19761        final float[] mTmpTransformLocation = new float[2];
19762
19763        /**
19764         * The view tree observer used to dispatch global events like
19765         * layout, pre-draw, touch mode change, etc.
19766         */
19767        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
19768
19769        /**
19770         * A Canvas used by the view hierarchy to perform bitmap caching.
19771         */
19772        Canvas mCanvas;
19773
19774        /**
19775         * The view root impl.
19776         */
19777        final ViewRootImpl mViewRootImpl;
19778
19779        /**
19780         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
19781         * handler can be used to pump events in the UI events queue.
19782         */
19783        final Handler mHandler;
19784
19785        /**
19786         * Temporary for use in computing invalidate rectangles while
19787         * calling up the hierarchy.
19788         */
19789        final Rect mTmpInvalRect = new Rect();
19790
19791        /**
19792         * Temporary for use in computing hit areas with transformed views
19793         */
19794        final RectF mTmpTransformRect = new RectF();
19795
19796        /**
19797         * Temporary for use in transforming invalidation rect
19798         */
19799        final Matrix mTmpMatrix = new Matrix();
19800
19801        /**
19802         * Temporary for use in transforming invalidation rect
19803         */
19804        final Transformation mTmpTransformation = new Transformation();
19805
19806        /**
19807         * Temporary list for use in collecting focusable descendents of a view.
19808         */
19809        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
19810
19811        /**
19812         * The id of the window for accessibility purposes.
19813         */
19814        int mAccessibilityWindowId = View.NO_ID;
19815
19816        /**
19817         * Flags related to accessibility processing.
19818         *
19819         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
19820         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
19821         */
19822        int mAccessibilityFetchFlags;
19823
19824        /**
19825         * The drawable for highlighting accessibility focus.
19826         */
19827        Drawable mAccessibilityFocusDrawable;
19828
19829        /**
19830         * Show where the margins, bounds and layout bounds are for each view.
19831         */
19832        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
19833
19834        /**
19835         * Point used to compute visible regions.
19836         */
19837        final Point mPoint = new Point();
19838
19839        /**
19840         * Used to track which View originated a requestLayout() call, used when
19841         * requestLayout() is called during layout.
19842         */
19843        View mViewRequestingLayout;
19844
19845        /**
19846         * Creates a new set of attachment information with the specified
19847         * events handler and thread.
19848         *
19849         * @param handler the events handler the view must use
19850         */
19851        AttachInfo(IWindowSession session, IWindow window, Display display,
19852                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
19853            mSession = session;
19854            mWindow = window;
19855            mWindowToken = window.asBinder();
19856            mDisplay = display;
19857            mViewRootImpl = viewRootImpl;
19858            mHandler = handler;
19859            mRootCallbacks = effectPlayer;
19860        }
19861    }
19862
19863    /**
19864     * <p>ScrollabilityCache holds various fields used by a View when scrolling
19865     * is supported. This avoids keeping too many unused fields in most
19866     * instances of View.</p>
19867     */
19868    private static class ScrollabilityCache implements Runnable {
19869
19870        /**
19871         * Scrollbars are not visible
19872         */
19873        public static final int OFF = 0;
19874
19875        /**
19876         * Scrollbars are visible
19877         */
19878        public static final int ON = 1;
19879
19880        /**
19881         * Scrollbars are fading away
19882         */
19883        public static final int FADING = 2;
19884
19885        public boolean fadeScrollBars;
19886
19887        public int fadingEdgeLength;
19888        public int scrollBarDefaultDelayBeforeFade;
19889        public int scrollBarFadeDuration;
19890
19891        public int scrollBarSize;
19892        public ScrollBarDrawable scrollBar;
19893        public float[] interpolatorValues;
19894        public View host;
19895
19896        public final Paint paint;
19897        public final Matrix matrix;
19898        public Shader shader;
19899
19900        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
19901
19902        private static final float[] OPAQUE = { 255 };
19903        private static final float[] TRANSPARENT = { 0.0f };
19904
19905        /**
19906         * When fading should start. This time moves into the future every time
19907         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
19908         */
19909        public long fadeStartTime;
19910
19911
19912        /**
19913         * The current state of the scrollbars: ON, OFF, or FADING
19914         */
19915        public int state = OFF;
19916
19917        private int mLastColor;
19918
19919        public ScrollabilityCache(ViewConfiguration configuration, View host) {
19920            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
19921            scrollBarSize = configuration.getScaledScrollBarSize();
19922            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
19923            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
19924
19925            paint = new Paint();
19926            matrix = new Matrix();
19927            // use use a height of 1, and then wack the matrix each time we
19928            // actually use it.
19929            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
19930            paint.setShader(shader);
19931            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
19932
19933            this.host = host;
19934        }
19935
19936        public void setFadeColor(int color) {
19937            if (color != mLastColor) {
19938                mLastColor = color;
19939
19940                if (color != 0) {
19941                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
19942                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
19943                    paint.setShader(shader);
19944                    // Restore the default transfer mode (src_over)
19945                    paint.setXfermode(null);
19946                } else {
19947                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
19948                    paint.setShader(shader);
19949                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
19950                }
19951            }
19952        }
19953
19954        public void run() {
19955            long now = AnimationUtils.currentAnimationTimeMillis();
19956            if (now >= fadeStartTime) {
19957
19958                // the animation fades the scrollbars out by changing
19959                // the opacity (alpha) from fully opaque to fully
19960                // transparent
19961                int nextFrame = (int) now;
19962                int framesCount = 0;
19963
19964                Interpolator interpolator = scrollBarInterpolator;
19965
19966                // Start opaque
19967                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
19968
19969                // End transparent
19970                nextFrame += scrollBarFadeDuration;
19971                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
19972
19973                state = FADING;
19974
19975                // Kick off the fade animation
19976                host.invalidate(true);
19977            }
19978        }
19979    }
19980
19981    /**
19982     * Resuable callback for sending
19983     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
19984     */
19985    private class SendViewScrolledAccessibilityEvent implements Runnable {
19986        public volatile boolean mIsPending;
19987
19988        public void run() {
19989            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
19990            mIsPending = false;
19991        }
19992    }
19993
19994    /**
19995     * <p>
19996     * This class represents a delegate that can be registered in a {@link View}
19997     * to enhance accessibility support via composition rather via inheritance.
19998     * It is specifically targeted to widget developers that extend basic View
19999     * classes i.e. classes in package android.view, that would like their
20000     * applications to be backwards compatible.
20001     * </p>
20002     * <div class="special reference">
20003     * <h3>Developer Guides</h3>
20004     * <p>For more information about making applications accessible, read the
20005     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
20006     * developer guide.</p>
20007     * </div>
20008     * <p>
20009     * A scenario in which a developer would like to use an accessibility delegate
20010     * is overriding a method introduced in a later API version then the minimal API
20011     * version supported by the application. For example, the method
20012     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
20013     * in API version 4 when the accessibility APIs were first introduced. If a
20014     * developer would like his application to run on API version 4 devices (assuming
20015     * all other APIs used by the application are version 4 or lower) and take advantage
20016     * of this method, instead of overriding the method which would break the application's
20017     * backwards compatibility, he can override the corresponding method in this
20018     * delegate and register the delegate in the target View if the API version of
20019     * the system is high enough i.e. the API version is same or higher to the API
20020     * version that introduced
20021     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
20022     * </p>
20023     * <p>
20024     * Here is an example implementation:
20025     * </p>
20026     * <code><pre><p>
20027     * if (Build.VERSION.SDK_INT >= 14) {
20028     *     // If the API version is equal of higher than the version in
20029     *     // which onInitializeAccessibilityNodeInfo was introduced we
20030     *     // register a delegate with a customized implementation.
20031     *     View view = findViewById(R.id.view_id);
20032     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
20033     *         public void onInitializeAccessibilityNodeInfo(View host,
20034     *                 AccessibilityNodeInfo info) {
20035     *             // Let the default implementation populate the info.
20036     *             super.onInitializeAccessibilityNodeInfo(host, info);
20037     *             // Set some other information.
20038     *             info.setEnabled(host.isEnabled());
20039     *         }
20040     *     });
20041     * }
20042     * </code></pre></p>
20043     * <p>
20044     * This delegate contains methods that correspond to the accessibility methods
20045     * in View. If a delegate has been specified the implementation in View hands
20046     * off handling to the corresponding method in this delegate. The default
20047     * implementation the delegate methods behaves exactly as the corresponding
20048     * method in View for the case of no accessibility delegate been set. Hence,
20049     * to customize the behavior of a View method, clients can override only the
20050     * corresponding delegate method without altering the behavior of the rest
20051     * accessibility related methods of the host view.
20052     * </p>
20053     */
20054    public static class AccessibilityDelegate {
20055
20056        /**
20057         * Sends an accessibility event of the given type. If accessibility is not
20058         * enabled this method has no effect.
20059         * <p>
20060         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
20061         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
20062         * been set.
20063         * </p>
20064         *
20065         * @param host The View hosting the delegate.
20066         * @param eventType The type of the event to send.
20067         *
20068         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
20069         */
20070        public void sendAccessibilityEvent(View host, int eventType) {
20071            host.sendAccessibilityEventInternal(eventType);
20072        }
20073
20074        /**
20075         * Performs the specified accessibility action on the view. For
20076         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
20077         * <p>
20078         * The default implementation behaves as
20079         * {@link View#performAccessibilityAction(int, Bundle)
20080         *  View#performAccessibilityAction(int, Bundle)} for the case of
20081         *  no accessibility delegate been set.
20082         * </p>
20083         *
20084         * @param action The action to perform.
20085         * @return Whether the action was performed.
20086         *
20087         * @see View#performAccessibilityAction(int, Bundle)
20088         *      View#performAccessibilityAction(int, Bundle)
20089         */
20090        public boolean performAccessibilityAction(View host, int action, Bundle args) {
20091            return host.performAccessibilityActionInternal(action, args);
20092        }
20093
20094        /**
20095         * Sends an accessibility event. This method behaves exactly as
20096         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
20097         * empty {@link AccessibilityEvent} and does not perform a check whether
20098         * accessibility is enabled.
20099         * <p>
20100         * The default implementation behaves as
20101         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
20102         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
20103         * the case of no accessibility delegate been set.
20104         * </p>
20105         *
20106         * @param host The View hosting the delegate.
20107         * @param event The event to send.
20108         *
20109         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
20110         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
20111         */
20112        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
20113            host.sendAccessibilityEventUncheckedInternal(event);
20114        }
20115
20116        /**
20117         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
20118         * to its children for adding their text content to the event.
20119         * <p>
20120         * The default implementation behaves as
20121         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
20122         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
20123         * the case of no accessibility delegate been set.
20124         * </p>
20125         *
20126         * @param host The View hosting the delegate.
20127         * @param event The event.
20128         * @return True if the event population was completed.
20129         *
20130         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
20131         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
20132         */
20133        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
20134            return host.dispatchPopulateAccessibilityEventInternal(event);
20135        }
20136
20137        /**
20138         * Gives a chance to the host View to populate the accessibility event with its
20139         * text content.
20140         * <p>
20141         * The default implementation behaves as
20142         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
20143         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
20144         * the case of no accessibility delegate been set.
20145         * </p>
20146         *
20147         * @param host The View hosting the delegate.
20148         * @param event The accessibility event which to populate.
20149         *
20150         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
20151         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
20152         */
20153        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
20154            host.onPopulateAccessibilityEventInternal(event);
20155        }
20156
20157        /**
20158         * Initializes an {@link AccessibilityEvent} with information about the
20159         * the host View which is the event source.
20160         * <p>
20161         * The default implementation behaves as
20162         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
20163         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
20164         * the case of no accessibility delegate been set.
20165         * </p>
20166         *
20167         * @param host The View hosting the delegate.
20168         * @param event The event to initialize.
20169         *
20170         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
20171         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
20172         */
20173        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
20174            host.onInitializeAccessibilityEventInternal(event);
20175        }
20176
20177        /**
20178         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
20179         * <p>
20180         * The default implementation behaves as
20181         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
20182         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
20183         * the case of no accessibility delegate been set.
20184         * </p>
20185         *
20186         * @param host The View hosting the delegate.
20187         * @param info The instance to initialize.
20188         *
20189         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
20190         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
20191         */
20192        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
20193            host.onInitializeAccessibilityNodeInfoInternal(info);
20194        }
20195
20196        /**
20197         * Called when a child of the host View has requested sending an
20198         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
20199         * to augment the event.
20200         * <p>
20201         * The default implementation behaves as
20202         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
20203         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
20204         * the case of no accessibility delegate been set.
20205         * </p>
20206         *
20207         * @param host The View hosting the delegate.
20208         * @param child The child which requests sending the event.
20209         * @param event The event to be sent.
20210         * @return True if the event should be sent
20211         *
20212         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
20213         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
20214         */
20215        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
20216                AccessibilityEvent event) {
20217            return host.onRequestSendAccessibilityEventInternal(child, event);
20218        }
20219
20220        /**
20221         * Gets the provider for managing a virtual view hierarchy rooted at this View
20222         * and reported to {@link android.accessibilityservice.AccessibilityService}s
20223         * that explore the window content.
20224         * <p>
20225         * The default implementation behaves as
20226         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
20227         * the case of no accessibility delegate been set.
20228         * </p>
20229         *
20230         * @return The provider.
20231         *
20232         * @see AccessibilityNodeProvider
20233         */
20234        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
20235            return null;
20236        }
20237
20238        /**
20239         * Returns an {@link AccessibilityNodeInfo} representing the host view from the
20240         * point of view of an {@link android.accessibilityservice.AccessibilityService}.
20241         * This method is responsible for obtaining an accessibility node info from a
20242         * pool of reusable instances and calling
20243         * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host
20244         * view to initialize the former.
20245         * <p>
20246         * <strong>Note:</strong> The client is responsible for recycling the obtained
20247         * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object
20248         * creation.
20249         * </p>
20250         * <p>
20251         * The default implementation behaves as
20252         * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for
20253         * the case of no accessibility delegate been set.
20254         * </p>
20255         * @return A populated {@link AccessibilityNodeInfo}.
20256         *
20257         * @see AccessibilityNodeInfo
20258         *
20259         * @hide
20260         */
20261        public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) {
20262            return host.createAccessibilityNodeInfoInternal();
20263        }
20264    }
20265
20266    private class MatchIdPredicate implements Predicate<View> {
20267        public int mId;
20268
20269        @Override
20270        public boolean apply(View view) {
20271            return (view.mID == mId);
20272        }
20273    }
20274
20275    private class MatchLabelForPredicate implements Predicate<View> {
20276        private int mLabeledId;
20277
20278        @Override
20279        public boolean apply(View view) {
20280            return (view.mLabelForId == mLabeledId);
20281        }
20282    }
20283
20284    private class SendViewStateChangedAccessibilityEvent implements Runnable {
20285        private int mChangeTypes = 0;
20286        private boolean mPosted;
20287        private boolean mPostedWithDelay;
20288        private long mLastEventTimeMillis;
20289
20290        @Override
20291        public void run() {
20292            mPosted = false;
20293            mPostedWithDelay = false;
20294            mLastEventTimeMillis = SystemClock.uptimeMillis();
20295            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
20296                final AccessibilityEvent event = AccessibilityEvent.obtain();
20297                event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
20298                event.setContentChangeTypes(mChangeTypes);
20299                sendAccessibilityEventUnchecked(event);
20300            }
20301            mChangeTypes = 0;
20302        }
20303
20304        public void runOrPost(int changeType) {
20305            mChangeTypes |= changeType;
20306
20307            // If this is a live region or the child of a live region, collect
20308            // all events from this frame and send them on the next frame.
20309            if (inLiveRegion()) {
20310                // If we're already posted with a delay, remove that.
20311                if (mPostedWithDelay) {
20312                    removeCallbacks(this);
20313                    mPostedWithDelay = false;
20314                }
20315                // Only post if we're not already posted.
20316                if (!mPosted) {
20317                    post(this);
20318                    mPosted = true;
20319                }
20320                return;
20321            }
20322
20323            if (mPosted) {
20324                return;
20325            }
20326            final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
20327            final long minEventIntevalMillis =
20328                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
20329            if (timeSinceLastMillis >= minEventIntevalMillis) {
20330                removeCallbacks(this);
20331                run();
20332            } else {
20333                postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
20334                mPosted = true;
20335                mPostedWithDelay = true;
20336            }
20337        }
20338    }
20339
20340    private boolean inLiveRegion() {
20341        if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) {
20342            return true;
20343        }
20344
20345        ViewParent parent = getParent();
20346        while (parent instanceof View) {
20347            if (((View) parent).getAccessibilityLiveRegion()
20348                    != View.ACCESSIBILITY_LIVE_REGION_NONE) {
20349                return true;
20350            }
20351            parent = parent.getParent();
20352        }
20353
20354        return false;
20355    }
20356
20357    /**
20358     * Dump all private flags in readable format, useful for documentation and
20359     * sanity checking.
20360     */
20361    private static void dumpFlags() {
20362        final HashMap<String, String> found = Maps.newHashMap();
20363        try {
20364            for (Field field : View.class.getDeclaredFields()) {
20365                final int modifiers = field.getModifiers();
20366                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
20367                    if (field.getType().equals(int.class)) {
20368                        final int value = field.getInt(null);
20369                        dumpFlag(found, field.getName(), value);
20370                    } else if (field.getType().equals(int[].class)) {
20371                        final int[] values = (int[]) field.get(null);
20372                        for (int i = 0; i < values.length; i++) {
20373                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
20374                        }
20375                    }
20376                }
20377            }
20378        } catch (IllegalAccessException e) {
20379            throw new RuntimeException(e);
20380        }
20381
20382        final ArrayList<String> keys = Lists.newArrayList();
20383        keys.addAll(found.keySet());
20384        Collections.sort(keys);
20385        for (String key : keys) {
20386            Log.d(VIEW_LOG_TAG, found.get(key));
20387        }
20388    }
20389
20390    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
20391        // Sort flags by prefix, then by bits, always keeping unique keys
20392        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
20393        final int prefix = name.indexOf('_');
20394        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
20395        final String output = bits + " " + name;
20396        found.put(key, output);
20397    }
20398}
20399