View.java revision 44fd8d24f761f82d21e9b00932648a1b6bf91449
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                && isImportantForAccessibility()) {
5143            AccessibilityEvent event = AccessibilityEvent.obtain(
5144                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
5145            onInitializeAccessibilityEvent(event);
5146            event.getText().add(text);
5147            event.setContentDescription(null);
5148            mParent.requestSendAccessibilityEvent(this, event);
5149        }
5150    }
5151
5152    /**
5153     * @see #sendAccessibilityEvent(int)
5154     *
5155     * Note: Called from the default {@link AccessibilityDelegate}.
5156     */
5157    void sendAccessibilityEventInternal(int eventType) {
5158        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
5159            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
5160        }
5161    }
5162
5163    /**
5164     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
5165     * takes as an argument an empty {@link AccessibilityEvent} and does not
5166     * perform a check whether accessibility is enabled.
5167     * <p>
5168     * If an {@link AccessibilityDelegate} has been specified via calling
5169     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5170     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
5171     * is responsible for handling this call.
5172     * </p>
5173     *
5174     * @param event The event to send.
5175     *
5176     * @see #sendAccessibilityEvent(int)
5177     */
5178    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
5179        if (mAccessibilityDelegate != null) {
5180            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
5181        } else {
5182            sendAccessibilityEventUncheckedInternal(event);
5183        }
5184    }
5185
5186    /**
5187     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
5188     *
5189     * Note: Called from the default {@link AccessibilityDelegate}.
5190     */
5191    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
5192        if (!isShown() || !isImportantForAccessibility()) {
5193            return;
5194        }
5195        onInitializeAccessibilityEvent(event);
5196        // Only a subset of accessibility events populates text content.
5197        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
5198            dispatchPopulateAccessibilityEvent(event);
5199        }
5200        // In the beginning we called #isShown(), so we know that getParent() is not null.
5201        getParent().requestSendAccessibilityEvent(this, event);
5202    }
5203
5204    /**
5205     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
5206     * to its children for adding their text content to the event. Note that the
5207     * event text is populated in a separate dispatch path since we add to the
5208     * event not only the text of the source but also the text of all its descendants.
5209     * A typical implementation will call
5210     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
5211     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
5212     * on each child. Override this method if custom population of the event text
5213     * content is required.
5214     * <p>
5215     * If an {@link AccessibilityDelegate} has been specified via calling
5216     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5217     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
5218     * is responsible for handling this call.
5219     * </p>
5220     * <p>
5221     * <em>Note:</em> Accessibility events of certain types are not dispatched for
5222     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
5223     * </p>
5224     *
5225     * @param event The event.
5226     *
5227     * @return True if the event population was completed.
5228     */
5229    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
5230        if (mAccessibilityDelegate != null) {
5231            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
5232        } else {
5233            return dispatchPopulateAccessibilityEventInternal(event);
5234        }
5235    }
5236
5237    /**
5238     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5239     *
5240     * Note: Called from the default {@link AccessibilityDelegate}.
5241     */
5242    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
5243        onPopulateAccessibilityEvent(event);
5244        return false;
5245    }
5246
5247    /**
5248     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
5249     * giving a chance to this View to populate the accessibility event with its
5250     * text content. While this method is free to modify event
5251     * attributes other than text content, doing so should normally be performed in
5252     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
5253     * <p>
5254     * Example: Adding formatted date string to an accessibility event in addition
5255     *          to the text added by the super implementation:
5256     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
5257     *     super.onPopulateAccessibilityEvent(event);
5258     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
5259     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
5260     *         mCurrentDate.getTimeInMillis(), flags);
5261     *     event.getText().add(selectedDateUtterance);
5262     * }</pre>
5263     * <p>
5264     * If an {@link AccessibilityDelegate} has been specified via calling
5265     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5266     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
5267     * is responsible for handling this call.
5268     * </p>
5269     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
5270     * information to the event, in case the default implementation has basic information to add.
5271     * </p>
5272     *
5273     * @param event The accessibility event which to populate.
5274     *
5275     * @see #sendAccessibilityEvent(int)
5276     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5277     */
5278    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
5279        if (mAccessibilityDelegate != null) {
5280            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
5281        } else {
5282            onPopulateAccessibilityEventInternal(event);
5283        }
5284    }
5285
5286    /**
5287     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
5288     *
5289     * Note: Called from the default {@link AccessibilityDelegate}.
5290     */
5291    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
5292    }
5293
5294    /**
5295     * Initializes an {@link AccessibilityEvent} with information about
5296     * this View which is the event source. In other words, the source of
5297     * an accessibility event is the view whose state change triggered firing
5298     * the event.
5299     * <p>
5300     * Example: Setting the password property of an event in addition
5301     *          to properties set by the super implementation:
5302     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
5303     *     super.onInitializeAccessibilityEvent(event);
5304     *     event.setPassword(true);
5305     * }</pre>
5306     * <p>
5307     * If an {@link AccessibilityDelegate} has been specified via calling
5308     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5309     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
5310     * is responsible for handling this call.
5311     * </p>
5312     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
5313     * information to the event, in case the default implementation has basic information to add.
5314     * </p>
5315     * @param event The event to initialize.
5316     *
5317     * @see #sendAccessibilityEvent(int)
5318     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5319     */
5320    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
5321        if (mAccessibilityDelegate != null) {
5322            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
5323        } else {
5324            onInitializeAccessibilityEventInternal(event);
5325        }
5326    }
5327
5328    /**
5329     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
5330     *
5331     * Note: Called from the default {@link AccessibilityDelegate}.
5332     */
5333    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
5334        event.setSource(this);
5335        event.setClassName(View.class.getName());
5336        event.setPackageName(getContext().getPackageName());
5337        event.setEnabled(isEnabled());
5338        event.setContentDescription(mContentDescription);
5339
5340        switch (event.getEventType()) {
5341            case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
5342                ArrayList<View> focusablesTempList = (mAttachInfo != null)
5343                        ? mAttachInfo.mTempArrayList : new ArrayList<View>();
5344                getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
5345                event.setItemCount(focusablesTempList.size());
5346                event.setCurrentItemIndex(focusablesTempList.indexOf(this));
5347                if (mAttachInfo != null) {
5348                    focusablesTempList.clear();
5349                }
5350            } break;
5351            case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: {
5352                CharSequence text = getIterableTextForAccessibility();
5353                if (text != null && text.length() > 0) {
5354                    event.setFromIndex(getAccessibilitySelectionStart());
5355                    event.setToIndex(getAccessibilitySelectionEnd());
5356                    event.setItemCount(text.length());
5357                }
5358            } break;
5359        }
5360    }
5361
5362    /**
5363     * Returns an {@link AccessibilityNodeInfo} representing this view from the
5364     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
5365     * This method is responsible for obtaining an accessibility node info from a
5366     * pool of reusable instances and calling
5367     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
5368     * initialize the former.
5369     * <p>
5370     * Note: The client is responsible for recycling the obtained instance by calling
5371     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
5372     * </p>
5373     *
5374     * @return A populated {@link AccessibilityNodeInfo}.
5375     *
5376     * @see AccessibilityNodeInfo
5377     */
5378    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
5379        if (mAccessibilityDelegate != null) {
5380            return mAccessibilityDelegate.createAccessibilityNodeInfo(this);
5381        } else {
5382            return createAccessibilityNodeInfoInternal();
5383        }
5384    }
5385
5386    /**
5387     * @see #createAccessibilityNodeInfo()
5388     */
5389    AccessibilityNodeInfo createAccessibilityNodeInfoInternal() {
5390        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
5391        if (provider != null) {
5392            return provider.createAccessibilityNodeInfo(View.NO_ID);
5393        } else {
5394            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
5395            onInitializeAccessibilityNodeInfo(info);
5396            return info;
5397        }
5398    }
5399
5400    /**
5401     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
5402     * The base implementation sets:
5403     * <ul>
5404     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
5405     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
5406     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
5407     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
5408     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
5409     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
5410     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
5411     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
5412     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
5413     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
5414     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
5415     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
5416     * </ul>
5417     * <p>
5418     * Subclasses should override this method, call the super implementation,
5419     * and set additional attributes.
5420     * </p>
5421     * <p>
5422     * If an {@link AccessibilityDelegate} has been specified via calling
5423     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5424     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
5425     * is responsible for handling this call.
5426     * </p>
5427     *
5428     * @param info The instance to initialize.
5429     */
5430    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
5431        if (mAccessibilityDelegate != null) {
5432            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
5433        } else {
5434            onInitializeAccessibilityNodeInfoInternal(info);
5435        }
5436    }
5437
5438    /**
5439     * Gets the location of this view in screen coordintates.
5440     *
5441     * @param outRect The output location
5442     */
5443    void getBoundsOnScreen(Rect outRect) {
5444        if (mAttachInfo == null) {
5445            return;
5446        }
5447
5448        RectF position = mAttachInfo.mTmpTransformRect;
5449        position.set(0, 0, mRight - mLeft, mBottom - mTop);
5450
5451        if (!hasIdentityMatrix()) {
5452            getMatrix().mapRect(position);
5453        }
5454
5455        position.offset(mLeft, mTop);
5456
5457        ViewParent parent = mParent;
5458        while (parent instanceof View) {
5459            View parentView = (View) parent;
5460
5461            position.offset(-parentView.mScrollX, -parentView.mScrollY);
5462
5463            if (!parentView.hasIdentityMatrix()) {
5464                parentView.getMatrix().mapRect(position);
5465            }
5466
5467            position.offset(parentView.mLeft, parentView.mTop);
5468
5469            parent = parentView.mParent;
5470        }
5471
5472        if (parent instanceof ViewRootImpl) {
5473            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
5474            position.offset(0, -viewRootImpl.mCurScrollY);
5475        }
5476
5477        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
5478
5479        outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f),
5480                (int) (position.right + 0.5f), (int) (position.bottom + 0.5f));
5481    }
5482
5483    /**
5484     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
5485     *
5486     * Note: Called from the default {@link AccessibilityDelegate}.
5487     */
5488    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
5489        Rect bounds = mAttachInfo.mTmpInvalRect;
5490
5491        getDrawingRect(bounds);
5492        info.setBoundsInParent(bounds);
5493
5494        getBoundsOnScreen(bounds);
5495        info.setBoundsInScreen(bounds);
5496
5497        ViewParent parent = getParentForAccessibility();
5498        if (parent instanceof View) {
5499            info.setParent((View) parent);
5500        }
5501
5502        if (mID != View.NO_ID) {
5503            View rootView = getRootView();
5504            if (rootView == null) {
5505                rootView = this;
5506            }
5507            View label = rootView.findLabelForView(this, mID);
5508            if (label != null) {
5509                info.setLabeledBy(label);
5510            }
5511
5512            if ((mAttachInfo.mAccessibilityFetchFlags
5513                    & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0
5514                    && Resources.resourceHasPackage(mID)) {
5515                try {
5516                    String viewId = getResources().getResourceName(mID);
5517                    info.setViewIdResourceName(viewId);
5518                } catch (Resources.NotFoundException nfe) {
5519                    /* ignore */
5520                }
5521            }
5522        }
5523
5524        if (mLabelForId != View.NO_ID) {
5525            View rootView = getRootView();
5526            if (rootView == null) {
5527                rootView = this;
5528            }
5529            View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId);
5530            if (labeled != null) {
5531                info.setLabelFor(labeled);
5532            }
5533        }
5534
5535        info.setVisibleToUser(isVisibleToUser());
5536
5537        info.setPackageName(mContext.getPackageName());
5538        info.setClassName(View.class.getName());
5539        info.setContentDescription(getContentDescription());
5540
5541        info.setEnabled(isEnabled());
5542        info.setClickable(isClickable());
5543        info.setFocusable(isFocusable());
5544        info.setFocused(isFocused());
5545        info.setAccessibilityFocused(isAccessibilityFocused());
5546        info.setSelected(isSelected());
5547        info.setLongClickable(isLongClickable());
5548        info.setLiveRegion(getAccessibilityLiveRegion());
5549
5550        // TODO: These make sense only if we are in an AdapterView but all
5551        // views can be selected. Maybe from accessibility perspective
5552        // we should report as selectable view in an AdapterView.
5553        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
5554        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
5555
5556        if (isFocusable()) {
5557            if (isFocused()) {
5558                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
5559            } else {
5560                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
5561            }
5562        }
5563
5564        if (!isAccessibilityFocused()) {
5565            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
5566        } else {
5567            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
5568        }
5569
5570        if (isClickable() && isEnabled()) {
5571            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
5572        }
5573
5574        if (isLongClickable() && isEnabled()) {
5575            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
5576        }
5577
5578        CharSequence text = getIterableTextForAccessibility();
5579        if (text != null && text.length() > 0) {
5580            info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd());
5581
5582            info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION);
5583            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
5584            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
5585            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
5586                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
5587                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
5588        }
5589    }
5590
5591    private View findLabelForView(View view, int labeledId) {
5592        if (mMatchLabelForPredicate == null) {
5593            mMatchLabelForPredicate = new MatchLabelForPredicate();
5594        }
5595        mMatchLabelForPredicate.mLabeledId = labeledId;
5596        return findViewByPredicateInsideOut(view, mMatchLabelForPredicate);
5597    }
5598
5599    /**
5600     * Computes whether this view is visible to the user. Such a view is
5601     * attached, visible, all its predecessors are visible, it is not clipped
5602     * entirely by its predecessors, and has an alpha greater than zero.
5603     *
5604     * @return Whether the view is visible on the screen.
5605     *
5606     * @hide
5607     */
5608    protected boolean isVisibleToUser() {
5609        return isVisibleToUser(null);
5610    }
5611
5612    /**
5613     * Computes whether the given portion of this view is visible to the user.
5614     * Such a view is attached, visible, all its predecessors are visible,
5615     * has an alpha greater than zero, and the specified portion is not
5616     * clipped entirely by its predecessors.
5617     *
5618     * @param boundInView the portion of the view to test; coordinates should be relative; may be
5619     *                    <code>null</code>, and the entire view will be tested in this case.
5620     *                    When <code>true</code> is returned by the function, the actual visible
5621     *                    region will be stored in this parameter; that is, if boundInView is fully
5622     *                    contained within the view, no modification will be made, otherwise regions
5623     *                    outside of the visible area of the view will be clipped.
5624     *
5625     * @return Whether the specified portion of the view is visible on the screen.
5626     *
5627     * @hide
5628     */
5629    protected boolean isVisibleToUser(Rect boundInView) {
5630        if (mAttachInfo != null) {
5631            // Attached to invisible window means this view is not visible.
5632            if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
5633                return false;
5634            }
5635            // An invisible predecessor or one with alpha zero means
5636            // that this view is not visible to the user.
5637            Object current = this;
5638            while (current instanceof View) {
5639                View view = (View) current;
5640                // We have attach info so this view is attached and there is no
5641                // need to check whether we reach to ViewRootImpl on the way up.
5642                if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 ||
5643                        view.getVisibility() != VISIBLE) {
5644                    return false;
5645                }
5646                current = view.mParent;
5647            }
5648            // Check if the view is entirely covered by its predecessors.
5649            Rect visibleRect = mAttachInfo.mTmpInvalRect;
5650            Point offset = mAttachInfo.mPoint;
5651            if (!getGlobalVisibleRect(visibleRect, offset)) {
5652                return false;
5653            }
5654            // Check if the visible portion intersects the rectangle of interest.
5655            if (boundInView != null) {
5656                visibleRect.offset(-offset.x, -offset.y);
5657                return boundInView.intersect(visibleRect);
5658            }
5659            return true;
5660        }
5661        return false;
5662    }
5663
5664    /**
5665     * Returns the delegate for implementing accessibility support via
5666     * composition. For more details see {@link AccessibilityDelegate}.
5667     *
5668     * @return The delegate, or null if none set.
5669     *
5670     * @hide
5671     */
5672    public AccessibilityDelegate getAccessibilityDelegate() {
5673        return mAccessibilityDelegate;
5674    }
5675
5676    /**
5677     * Sets a delegate for implementing accessibility support via composition as
5678     * opposed to inheritance. The delegate's primary use is for implementing
5679     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
5680     *
5681     * @param delegate The delegate instance.
5682     *
5683     * @see AccessibilityDelegate
5684     */
5685    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
5686        mAccessibilityDelegate = delegate;
5687    }
5688
5689    /**
5690     * Gets the provider for managing a virtual view hierarchy rooted at this View
5691     * and reported to {@link android.accessibilityservice.AccessibilityService}s
5692     * that explore the window content.
5693     * <p>
5694     * If this method returns an instance, this instance is responsible for managing
5695     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
5696     * View including the one representing the View itself. Similarly the returned
5697     * instance is responsible for performing accessibility actions on any virtual
5698     * view or the root view itself.
5699     * </p>
5700     * <p>
5701     * If an {@link AccessibilityDelegate} has been specified via calling
5702     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5703     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
5704     * is responsible for handling this call.
5705     * </p>
5706     *
5707     * @return The provider.
5708     *
5709     * @see AccessibilityNodeProvider
5710     */
5711    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
5712        if (mAccessibilityDelegate != null) {
5713            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
5714        } else {
5715            return null;
5716        }
5717    }
5718
5719    /**
5720     * Gets the unique identifier of this view on the screen for accessibility purposes.
5721     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
5722     *
5723     * @return The view accessibility id.
5724     *
5725     * @hide
5726     */
5727    public int getAccessibilityViewId() {
5728        if (mAccessibilityViewId == NO_ID) {
5729            mAccessibilityViewId = sNextAccessibilityViewId++;
5730        }
5731        return mAccessibilityViewId;
5732    }
5733
5734    /**
5735     * Gets the unique identifier of the window in which this View reseides.
5736     *
5737     * @return The window accessibility id.
5738     *
5739     * @hide
5740     */
5741    public int getAccessibilityWindowId() {
5742        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID;
5743    }
5744
5745    /**
5746     * Gets the {@link View} description. It briefly describes the view and is
5747     * primarily used for accessibility support. Set this property to enable
5748     * better accessibility support for your application. This is especially
5749     * true for views that do not have textual representation (For example,
5750     * ImageButton).
5751     *
5752     * @return The content description.
5753     *
5754     * @attr ref android.R.styleable#View_contentDescription
5755     */
5756    @ViewDebug.ExportedProperty(category = "accessibility")
5757    public CharSequence getContentDescription() {
5758        return mContentDescription;
5759    }
5760
5761    /**
5762     * Sets the {@link View} description. It briefly describes the view and is
5763     * primarily used for accessibility support. Set this property to enable
5764     * better accessibility support for your application. This is especially
5765     * true for views that do not have textual representation (For example,
5766     * ImageButton).
5767     *
5768     * @param contentDescription The content description.
5769     *
5770     * @attr ref android.R.styleable#View_contentDescription
5771     */
5772    @RemotableViewMethod
5773    public void setContentDescription(CharSequence contentDescription) {
5774        if (mContentDescription == null) {
5775            if (contentDescription == null) {
5776                return;
5777            }
5778        } else if (mContentDescription.equals(contentDescription)) {
5779            return;
5780        }
5781        mContentDescription = contentDescription;
5782        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
5783        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
5784            setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
5785            notifySubtreeAccessibilityStateChangedIfNeeded();
5786        } else {
5787            notifyViewAccessibilityStateChangedIfNeeded(
5788                    AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION);
5789        }
5790    }
5791
5792    /**
5793     * Gets the id of a view for which this view serves as a label for
5794     * accessibility purposes.
5795     *
5796     * @return The labeled view id.
5797     */
5798    @ViewDebug.ExportedProperty(category = "accessibility")
5799    public int getLabelFor() {
5800        return mLabelForId;
5801    }
5802
5803    /**
5804     * Sets the id of a view for which this view serves as a label for
5805     * accessibility purposes.
5806     *
5807     * @param id The labeled view id.
5808     */
5809    @RemotableViewMethod
5810    public void setLabelFor(int id) {
5811        mLabelForId = id;
5812        if (mLabelForId != View.NO_ID
5813                && mID == View.NO_ID) {
5814            mID = generateViewId();
5815        }
5816    }
5817
5818    /**
5819     * Invoked whenever this view loses focus, either by losing window focus or by losing
5820     * focus within its window. This method can be used to clear any state tied to the
5821     * focus. For instance, if a button is held pressed with the trackball and the window
5822     * loses focus, this method can be used to cancel the press.
5823     *
5824     * Subclasses of View overriding this method should always call super.onFocusLost().
5825     *
5826     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
5827     * @see #onWindowFocusChanged(boolean)
5828     *
5829     * @hide pending API council approval
5830     */
5831    protected void onFocusLost() {
5832        resetPressedState();
5833    }
5834
5835    private void resetPressedState() {
5836        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
5837            return;
5838        }
5839
5840        if (isPressed()) {
5841            setPressed(false);
5842
5843            if (!mHasPerformedLongPress) {
5844                removeLongPressCallback();
5845            }
5846        }
5847    }
5848
5849    /**
5850     * Returns true if this view has focus
5851     *
5852     * @return True if this view has focus, false otherwise.
5853     */
5854    @ViewDebug.ExportedProperty(category = "focus")
5855    public boolean isFocused() {
5856        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
5857    }
5858
5859    /**
5860     * Find the view in the hierarchy rooted at this view that currently has
5861     * focus.
5862     *
5863     * @return The view that currently has focus, or null if no focused view can
5864     *         be found.
5865     */
5866    public View findFocus() {
5867        return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
5868    }
5869
5870    /**
5871     * Indicates whether this view is one of the set of scrollable containers in
5872     * its window.
5873     *
5874     * @return whether this view is one of the set of scrollable containers in
5875     * its window
5876     *
5877     * @attr ref android.R.styleable#View_isScrollContainer
5878     */
5879    public boolean isScrollContainer() {
5880        return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0;
5881    }
5882
5883    /**
5884     * Change whether this view is one of the set of scrollable containers in
5885     * its window.  This will be used to determine whether the window can
5886     * resize or must pan when a soft input area is open -- scrollable
5887     * containers allow the window to use resize mode since the container
5888     * will appropriately shrink.
5889     *
5890     * @attr ref android.R.styleable#View_isScrollContainer
5891     */
5892    public void setScrollContainer(boolean isScrollContainer) {
5893        if (isScrollContainer) {
5894            if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) {
5895                mAttachInfo.mScrollContainers.add(this);
5896                mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
5897            }
5898            mPrivateFlags |= PFLAG_SCROLL_CONTAINER;
5899        } else {
5900            if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
5901                mAttachInfo.mScrollContainers.remove(this);
5902            }
5903            mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED);
5904        }
5905    }
5906
5907    /**
5908     * Returns the quality of the drawing cache.
5909     *
5910     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5911     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5912     *
5913     * @see #setDrawingCacheQuality(int)
5914     * @see #setDrawingCacheEnabled(boolean)
5915     * @see #isDrawingCacheEnabled()
5916     *
5917     * @attr ref android.R.styleable#View_drawingCacheQuality
5918     */
5919    @DrawingCacheQuality
5920    public int getDrawingCacheQuality() {
5921        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
5922    }
5923
5924    /**
5925     * Set the drawing cache quality of this view. This value is used only when the
5926     * drawing cache is enabled
5927     *
5928     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5929     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5930     *
5931     * @see #getDrawingCacheQuality()
5932     * @see #setDrawingCacheEnabled(boolean)
5933     * @see #isDrawingCacheEnabled()
5934     *
5935     * @attr ref android.R.styleable#View_drawingCacheQuality
5936     */
5937    public void setDrawingCacheQuality(@DrawingCacheQuality int quality) {
5938        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
5939    }
5940
5941    /**
5942     * Returns whether the screen should remain on, corresponding to the current
5943     * value of {@link #KEEP_SCREEN_ON}.
5944     *
5945     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
5946     *
5947     * @see #setKeepScreenOn(boolean)
5948     *
5949     * @attr ref android.R.styleable#View_keepScreenOn
5950     */
5951    public boolean getKeepScreenOn() {
5952        return (mViewFlags & KEEP_SCREEN_ON) != 0;
5953    }
5954
5955    /**
5956     * Controls whether the screen should remain on, modifying the
5957     * value of {@link #KEEP_SCREEN_ON}.
5958     *
5959     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
5960     *
5961     * @see #getKeepScreenOn()
5962     *
5963     * @attr ref android.R.styleable#View_keepScreenOn
5964     */
5965    public void setKeepScreenOn(boolean keepScreenOn) {
5966        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
5967    }
5968
5969    /**
5970     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5971     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5972     *
5973     * @attr ref android.R.styleable#View_nextFocusLeft
5974     */
5975    public int getNextFocusLeftId() {
5976        return mNextFocusLeftId;
5977    }
5978
5979    /**
5980     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5981     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
5982     * decide automatically.
5983     *
5984     * @attr ref android.R.styleable#View_nextFocusLeft
5985     */
5986    public void setNextFocusLeftId(int nextFocusLeftId) {
5987        mNextFocusLeftId = nextFocusLeftId;
5988    }
5989
5990    /**
5991     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5992     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5993     *
5994     * @attr ref android.R.styleable#View_nextFocusRight
5995     */
5996    public int getNextFocusRightId() {
5997        return mNextFocusRightId;
5998    }
5999
6000    /**
6001     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
6002     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
6003     * decide automatically.
6004     *
6005     * @attr ref android.R.styleable#View_nextFocusRight
6006     */
6007    public void setNextFocusRightId(int nextFocusRightId) {
6008        mNextFocusRightId = nextFocusRightId;
6009    }
6010
6011    /**
6012     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
6013     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6014     *
6015     * @attr ref android.R.styleable#View_nextFocusUp
6016     */
6017    public int getNextFocusUpId() {
6018        return mNextFocusUpId;
6019    }
6020
6021    /**
6022     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
6023     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
6024     * decide automatically.
6025     *
6026     * @attr ref android.R.styleable#View_nextFocusUp
6027     */
6028    public void setNextFocusUpId(int nextFocusUpId) {
6029        mNextFocusUpId = nextFocusUpId;
6030    }
6031
6032    /**
6033     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
6034     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6035     *
6036     * @attr ref android.R.styleable#View_nextFocusDown
6037     */
6038    public int getNextFocusDownId() {
6039        return mNextFocusDownId;
6040    }
6041
6042    /**
6043     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
6044     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
6045     * decide automatically.
6046     *
6047     * @attr ref android.R.styleable#View_nextFocusDown
6048     */
6049    public void setNextFocusDownId(int nextFocusDownId) {
6050        mNextFocusDownId = nextFocusDownId;
6051    }
6052
6053    /**
6054     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
6055     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6056     *
6057     * @attr ref android.R.styleable#View_nextFocusForward
6058     */
6059    public int getNextFocusForwardId() {
6060        return mNextFocusForwardId;
6061    }
6062
6063    /**
6064     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
6065     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
6066     * decide automatically.
6067     *
6068     * @attr ref android.R.styleable#View_nextFocusForward
6069     */
6070    public void setNextFocusForwardId(int nextFocusForwardId) {
6071        mNextFocusForwardId = nextFocusForwardId;
6072    }
6073
6074    /**
6075     * Returns the visibility of this view and all of its ancestors
6076     *
6077     * @return True if this view and all of its ancestors are {@link #VISIBLE}
6078     */
6079    public boolean isShown() {
6080        View current = this;
6081        //noinspection ConstantConditions
6082        do {
6083            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6084                return false;
6085            }
6086            ViewParent parent = current.mParent;
6087            if (parent == null) {
6088                return false; // We are not attached to the view root
6089            }
6090            if (!(parent instanceof View)) {
6091                return true;
6092            }
6093            current = (View) parent;
6094        } while (current != null);
6095
6096        return false;
6097    }
6098
6099    /**
6100     * Called by the view hierarchy when the content insets for a window have
6101     * changed, to allow it to adjust its content to fit within those windows.
6102     * The content insets tell you the space that the status bar, input method,
6103     * and other system windows infringe on the application's window.
6104     *
6105     * <p>You do not normally need to deal with this function, since the default
6106     * window decoration given to applications takes care of applying it to the
6107     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
6108     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
6109     * and your content can be placed under those system elements.  You can then
6110     * use this method within your view hierarchy if you have parts of your UI
6111     * which you would like to ensure are not being covered.
6112     *
6113     * <p>The default implementation of this method simply applies the content
6114     * insets to the view's padding, consuming that content (modifying the
6115     * insets to be 0), and returning true.  This behavior is off by default, but can
6116     * be enabled through {@link #setFitsSystemWindows(boolean)}.
6117     *
6118     * <p>This function's traversal down the hierarchy is depth-first.  The same content
6119     * insets object is propagated down the hierarchy, so any changes made to it will
6120     * be seen by all following views (including potentially ones above in
6121     * the hierarchy since this is a depth-first traversal).  The first view
6122     * that returns true will abort the entire traversal.
6123     *
6124     * <p>The default implementation works well for a situation where it is
6125     * used with a container that covers the entire window, allowing it to
6126     * apply the appropriate insets to its content on all edges.  If you need
6127     * a more complicated layout (such as two different views fitting system
6128     * windows, one on the top of the window, and one on the bottom),
6129     * you can override the method and handle the insets however you would like.
6130     * Note that the insets provided by the framework are always relative to the
6131     * far edges of the window, not accounting for the location of the called view
6132     * within that window.  (In fact when this method is called you do not yet know
6133     * where the layout will place the view, as it is done before layout happens.)
6134     *
6135     * <p>Note: unlike many View methods, there is no dispatch phase to this
6136     * call.  If you are overriding it in a ViewGroup and want to allow the
6137     * call to continue to your children, you must be sure to call the super
6138     * implementation.
6139     *
6140     * <p>Here is a sample layout that makes use of fitting system windows
6141     * to have controls for a video view placed inside of the window decorations
6142     * that it hides and shows.  This can be used with code like the second
6143     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
6144     *
6145     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
6146     *
6147     * @param insets Current content insets of the window.  Prior to
6148     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
6149     * the insets or else you and Android will be unhappy.
6150     *
6151     * @return {@code true} if this view applied the insets and it should not
6152     * continue propagating further down the hierarchy, {@code false} otherwise.
6153     * @see #getFitsSystemWindows()
6154     * @see #setFitsSystemWindows(boolean)
6155     * @see #setSystemUiVisibility(int)
6156     *
6157     * @deprecated As of API XX use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply
6158     * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use
6159     * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)}
6160     * to implement handling their own insets.
6161     */
6162    protected boolean fitSystemWindows(Rect insets) {
6163        if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) {
6164            // If we're not in the process of dispatching the newer apply insets call,
6165            // that means we're not in the compatibility path. Dispatch into the newer
6166            // apply insets path and take things from there.
6167            try {
6168                mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS;
6169                return !dispatchApplyWindowInsets(new WindowInsets(insets)).hasInsets();
6170            } finally {
6171                mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS;
6172            }
6173        } else {
6174            // We're being called from the newer apply insets path.
6175            // Perform the standard fallback behavior.
6176            return fitSystemWindowsInt(insets);
6177        }
6178    }
6179
6180    private boolean fitSystemWindowsInt(Rect insets) {
6181        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
6182            mUserPaddingStart = UNDEFINED_PADDING;
6183            mUserPaddingEnd = UNDEFINED_PADDING;
6184            Rect localInsets = sThreadLocal.get();
6185            if (localInsets == null) {
6186                localInsets = new Rect();
6187                sThreadLocal.set(localInsets);
6188            }
6189            boolean res = computeFitSystemWindows(insets, localInsets);
6190            mUserPaddingLeftInitial = localInsets.left;
6191            mUserPaddingRightInitial = localInsets.right;
6192            internalSetPadding(localInsets.left, localInsets.top,
6193                    localInsets.right, localInsets.bottom);
6194            return res;
6195        }
6196        return false;
6197    }
6198
6199    /**
6200     * Called when the view should apply {@link WindowInsets} according to its internal policy.
6201     *
6202     * <p>This method should be overridden by views that wish to apply a policy different from or
6203     * in addition to the default behavior. Clients that wish to force a view subtree
6204     * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p>
6205     *
6206     * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set
6207     * it will be called during dispatch instead of this method. The listener may optionally
6208     * call this method from its own implementation if it wishes to apply the view's default
6209     * insets policy in addition to its own.</p>
6210     *
6211     * <p>Implementations of this method should either return the insets parameter unchanged
6212     * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed
6213     * that this view applied itself. This allows new inset types added in future platform
6214     * versions to pass through existing implementations unchanged without being erroneously
6215     * consumed.</p>
6216     *
6217     * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows}
6218     * property is set then the view will consume the system window insets and apply them
6219     * as padding for the view.</p>
6220     *
6221     * @param insets Insets to apply
6222     * @return The supplied insets with any applied insets consumed
6223     */
6224    public WindowInsets onApplyWindowInsets(WindowInsets insets) {
6225        if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) {
6226            // We weren't called from within a direct call to fitSystemWindows,
6227            // call into it as a fallback in case we're in a class that overrides it
6228            // and has logic to perform.
6229            if (fitSystemWindows(insets.getSystemWindowInsets())) {
6230                return insets.cloneWithSystemWindowInsetsConsumed();
6231            }
6232        } else {
6233            // We were called from within a direct call to fitSystemWindows.
6234            if (fitSystemWindowsInt(insets.getSystemWindowInsets())) {
6235                return insets.cloneWithSystemWindowInsetsConsumed();
6236            }
6237        }
6238        return insets;
6239    }
6240
6241    /**
6242     * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying
6243     * window insets to this view. The listener's
6244     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
6245     * method will be called instead of the view's
6246     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
6247     *
6248     * @param listener Listener to set
6249     *
6250     * @see #onApplyWindowInsets(WindowInsets)
6251     */
6252    public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) {
6253        getListenerInfo().mOnApplyWindowInsetsListener = listener;
6254    }
6255
6256    /**
6257     * Request to apply the given window insets to this view or another view in its subtree.
6258     *
6259     * <p>This method should be called by clients wishing to apply insets corresponding to areas
6260     * obscured by window decorations or overlays. This can include the status and navigation bars,
6261     * action bars, input methods and more. New inset categories may be added in the future.
6262     * The method returns the insets provided minus any that were applied by this view or its
6263     * children.</p>
6264     *
6265     * <p>Clients wishing to provide custom behavior should override the
6266     * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a
6267     * {@link OnApplyWindowInsetsListener} via the
6268     * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener}
6269     * method.</p>
6270     *
6271     * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method.
6272     * </p>
6273     *
6274     * @param insets Insets to apply
6275     * @return The provided insets minus the insets that were consumed
6276     */
6277    public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) {
6278        try {
6279            mPrivateFlags3 |= PFLAG3_APPLYING_INSETS;
6280            if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) {
6281                return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets);
6282            } else {
6283                return onApplyWindowInsets(insets);
6284            }
6285        } finally {
6286            mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS;
6287        }
6288    }
6289
6290    /**
6291     * @hide Compute the insets that should be consumed by this view and the ones
6292     * that should propagate to those under it.
6293     */
6294    protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) {
6295        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
6296                || mAttachInfo == null
6297                || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0
6298                        && !mAttachInfo.mOverscanRequested)) {
6299            outLocalInsets.set(inoutInsets);
6300            inoutInsets.set(0, 0, 0, 0);
6301            return true;
6302        } else {
6303            // The application wants to take care of fitting system window for
6304            // the content...  however we still need to take care of any overscan here.
6305            final Rect overscan = mAttachInfo.mOverscanInsets;
6306            outLocalInsets.set(overscan);
6307            inoutInsets.left -= overscan.left;
6308            inoutInsets.top -= overscan.top;
6309            inoutInsets.right -= overscan.right;
6310            inoutInsets.bottom -= overscan.bottom;
6311            return false;
6312        }
6313    }
6314
6315    /**
6316     * Sets whether or not this view should account for system screen decorations
6317     * such as the status bar and inset its content; that is, controlling whether
6318     * the default implementation of {@link #fitSystemWindows(Rect)} will be
6319     * executed.  See that method for more details.
6320     *
6321     * <p>Note that if you are providing your own implementation of
6322     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
6323     * flag to true -- your implementation will be overriding the default
6324     * implementation that checks this flag.
6325     *
6326     * @param fitSystemWindows If true, then the default implementation of
6327     * {@link #fitSystemWindows(Rect)} will be executed.
6328     *
6329     * @attr ref android.R.styleable#View_fitsSystemWindows
6330     * @see #getFitsSystemWindows()
6331     * @see #fitSystemWindows(Rect)
6332     * @see #setSystemUiVisibility(int)
6333     */
6334    public void setFitsSystemWindows(boolean fitSystemWindows) {
6335        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
6336    }
6337
6338    /**
6339     * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method
6340     * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)}
6341     * will be executed.
6342     *
6343     * @return {@code true} if the default implementation of
6344     * {@link #fitSystemWindows(Rect)} will be executed.
6345     *
6346     * @attr ref android.R.styleable#View_fitsSystemWindows
6347     * @see #setFitsSystemWindows(boolean)
6348     * @see #fitSystemWindows(Rect)
6349     * @see #setSystemUiVisibility(int)
6350     */
6351    public boolean getFitsSystemWindows() {
6352        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
6353    }
6354
6355    /** @hide */
6356    public boolean fitsSystemWindows() {
6357        return getFitsSystemWindows();
6358    }
6359
6360    /**
6361     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
6362     * @deprecated Use {@link #requestApplyInsets()} for newer platform versions.
6363     */
6364    public void requestFitSystemWindows() {
6365        if (mParent != null) {
6366            mParent.requestFitSystemWindows();
6367        }
6368    }
6369
6370    /**
6371     * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed.
6372     */
6373    public void requestApplyInsets() {
6374        requestFitSystemWindows();
6375    }
6376
6377    /**
6378     * For use by PhoneWindow to make its own system window fitting optional.
6379     * @hide
6380     */
6381    public void makeOptionalFitsSystemWindows() {
6382        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
6383    }
6384
6385    /**
6386     * Returns the visibility status for this view.
6387     *
6388     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
6389     * @attr ref android.R.styleable#View_visibility
6390     */
6391    @ViewDebug.ExportedProperty(mapping = {
6392        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
6393        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
6394        @ViewDebug.IntToString(from = GONE,      to = "GONE")
6395    })
6396    @Visibility
6397    public int getVisibility() {
6398        return mViewFlags & VISIBILITY_MASK;
6399    }
6400
6401    /**
6402     * Set the enabled state of this view.
6403     *
6404     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
6405     * @attr ref android.R.styleable#View_visibility
6406     */
6407    @RemotableViewMethod
6408    public void setVisibility(@Visibility int visibility) {
6409        setFlags(visibility, VISIBILITY_MASK);
6410        if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false);
6411    }
6412
6413    /**
6414     * Returns the enabled status for this view. The interpretation of the
6415     * enabled state varies by subclass.
6416     *
6417     * @return True if this view is enabled, false otherwise.
6418     */
6419    @ViewDebug.ExportedProperty
6420    public boolean isEnabled() {
6421        return (mViewFlags & ENABLED_MASK) == ENABLED;
6422    }
6423
6424    /**
6425     * Set the enabled state of this view. The interpretation of the enabled
6426     * state varies by subclass.
6427     *
6428     * @param enabled True if this view is enabled, false otherwise.
6429     */
6430    @RemotableViewMethod
6431    public void setEnabled(boolean enabled) {
6432        if (enabled == isEnabled()) return;
6433
6434        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
6435
6436        /*
6437         * The View most likely has to change its appearance, so refresh
6438         * the drawable state.
6439         */
6440        refreshDrawableState();
6441
6442        // Invalidate too, since the default behavior for views is to be
6443        // be drawn at 50% alpha rather than to change the drawable.
6444        invalidate(true);
6445
6446        if (!enabled) {
6447            cancelPendingInputEvents();
6448        }
6449    }
6450
6451    /**
6452     * Set whether this view can receive the focus.
6453     *
6454     * Setting this to false will also ensure that this view is not focusable
6455     * in touch mode.
6456     *
6457     * @param focusable If true, this view can receive the focus.
6458     *
6459     * @see #setFocusableInTouchMode(boolean)
6460     * @attr ref android.R.styleable#View_focusable
6461     */
6462    public void setFocusable(boolean focusable) {
6463        if (!focusable) {
6464            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
6465        }
6466        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
6467    }
6468
6469    /**
6470     * Set whether this view can receive focus while in touch mode.
6471     *
6472     * Setting this to true will also ensure that this view is focusable.
6473     *
6474     * @param focusableInTouchMode If true, this view can receive the focus while
6475     *   in touch mode.
6476     *
6477     * @see #setFocusable(boolean)
6478     * @attr ref android.R.styleable#View_focusableInTouchMode
6479     */
6480    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
6481        // Focusable in touch mode should always be set before the focusable flag
6482        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
6483        // which, in touch mode, will not successfully request focus on this view
6484        // because the focusable in touch mode flag is not set
6485        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
6486        if (focusableInTouchMode) {
6487            setFlags(FOCUSABLE, FOCUSABLE_MASK);
6488        }
6489    }
6490
6491    /**
6492     * Set whether this view should have sound effects enabled for events such as
6493     * clicking and touching.
6494     *
6495     * <p>You may wish to disable sound effects for a view if you already play sounds,
6496     * for instance, a dial key that plays dtmf tones.
6497     *
6498     * @param soundEffectsEnabled whether sound effects are enabled for this view.
6499     * @see #isSoundEffectsEnabled()
6500     * @see #playSoundEffect(int)
6501     * @attr ref android.R.styleable#View_soundEffectsEnabled
6502     */
6503    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
6504        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
6505    }
6506
6507    /**
6508     * @return whether this view should have sound effects enabled for events such as
6509     *     clicking and touching.
6510     *
6511     * @see #setSoundEffectsEnabled(boolean)
6512     * @see #playSoundEffect(int)
6513     * @attr ref android.R.styleable#View_soundEffectsEnabled
6514     */
6515    @ViewDebug.ExportedProperty
6516    public boolean isSoundEffectsEnabled() {
6517        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
6518    }
6519
6520    /**
6521     * Set whether this view should have haptic feedback for events such as
6522     * long presses.
6523     *
6524     * <p>You may wish to disable haptic feedback if your view already controls
6525     * its own haptic feedback.
6526     *
6527     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
6528     * @see #isHapticFeedbackEnabled()
6529     * @see #performHapticFeedback(int)
6530     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
6531     */
6532    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
6533        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
6534    }
6535
6536    /**
6537     * @return whether this view should have haptic feedback enabled for events
6538     * long presses.
6539     *
6540     * @see #setHapticFeedbackEnabled(boolean)
6541     * @see #performHapticFeedback(int)
6542     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
6543     */
6544    @ViewDebug.ExportedProperty
6545    public boolean isHapticFeedbackEnabled() {
6546        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
6547    }
6548
6549    /**
6550     * Returns the layout direction for this view.
6551     *
6552     * @return One of {@link #LAYOUT_DIRECTION_LTR},
6553     *   {@link #LAYOUT_DIRECTION_RTL},
6554     *   {@link #LAYOUT_DIRECTION_INHERIT} or
6555     *   {@link #LAYOUT_DIRECTION_LOCALE}.
6556     *
6557     * @attr ref android.R.styleable#View_layoutDirection
6558     *
6559     * @hide
6560     */
6561    @ViewDebug.ExportedProperty(category = "layout", mapping = {
6562        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
6563        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
6564        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
6565        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
6566    })
6567    @LayoutDir
6568    public int getRawLayoutDirection() {
6569        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
6570    }
6571
6572    /**
6573     * Set the layout direction for this view. This will propagate a reset of layout direction
6574     * resolution to the view's children and resolve layout direction for this view.
6575     *
6576     * @param layoutDirection the layout direction to set. Should be one of:
6577     *
6578     * {@link #LAYOUT_DIRECTION_LTR},
6579     * {@link #LAYOUT_DIRECTION_RTL},
6580     * {@link #LAYOUT_DIRECTION_INHERIT},
6581     * {@link #LAYOUT_DIRECTION_LOCALE}.
6582     *
6583     * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution
6584     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
6585     * will return the default {@link #LAYOUT_DIRECTION_LTR}.
6586     *
6587     * @attr ref android.R.styleable#View_layoutDirection
6588     */
6589    @RemotableViewMethod
6590    public void setLayoutDirection(@LayoutDir int layoutDirection) {
6591        if (getRawLayoutDirection() != layoutDirection) {
6592            // Reset the current layout direction and the resolved one
6593            mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK;
6594            resetRtlProperties();
6595            // Set the new layout direction (filtered)
6596            mPrivateFlags2 |=
6597                    ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK);
6598            // We need to resolve all RTL properties as they all depend on layout direction
6599            resolveRtlPropertiesIfNeeded();
6600            requestLayout();
6601            invalidate(true);
6602        }
6603    }
6604
6605    /**
6606     * Returns the resolved layout direction for this view.
6607     *
6608     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
6609     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
6610     *
6611     * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version
6612     * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}.
6613     *
6614     * @attr ref android.R.styleable#View_layoutDirection
6615     */
6616    @ViewDebug.ExportedProperty(category = "layout", mapping = {
6617        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
6618        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
6619    })
6620    @ResolvedLayoutDir
6621    public int getLayoutDirection() {
6622        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
6623        if (targetSdkVersion < JELLY_BEAN_MR1) {
6624            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
6625            return LAYOUT_DIRECTION_RESOLVED_DEFAULT;
6626        }
6627        return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ==
6628                PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
6629    }
6630
6631    /**
6632     * Indicates whether or not this view's layout is right-to-left. This is resolved from
6633     * layout attribute and/or the inherited value from the parent
6634     *
6635     * @return true if the layout is right-to-left.
6636     *
6637     * @hide
6638     */
6639    @ViewDebug.ExportedProperty(category = "layout")
6640    public boolean isLayoutRtl() {
6641        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
6642    }
6643
6644    /**
6645     * Indicates whether the view is currently tracking transient state that the
6646     * app should not need to concern itself with saving and restoring, but that
6647     * the framework should take special note to preserve when possible.
6648     *
6649     * <p>A view with transient state cannot be trivially rebound from an external
6650     * data source, such as an adapter binding item views in a list. This may be
6651     * because the view is performing an animation, tracking user selection
6652     * of content, or similar.</p>
6653     *
6654     * @return true if the view has transient state
6655     */
6656    @ViewDebug.ExportedProperty(category = "layout")
6657    public boolean hasTransientState() {
6658        return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE;
6659    }
6660
6661    /**
6662     * Set whether this view is currently tracking transient state that the
6663     * framework should attempt to preserve when possible. This flag is reference counted,
6664     * so every call to setHasTransientState(true) should be paired with a later call
6665     * to setHasTransientState(false).
6666     *
6667     * <p>A view with transient state cannot be trivially rebound from an external
6668     * data source, such as an adapter binding item views in a list. This may be
6669     * because the view is performing an animation, tracking user selection
6670     * of content, or similar.</p>
6671     *
6672     * @param hasTransientState true if this view has transient state
6673     */
6674    public void setHasTransientState(boolean hasTransientState) {
6675        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
6676                mTransientStateCount - 1;
6677        if (mTransientStateCount < 0) {
6678            mTransientStateCount = 0;
6679            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
6680                    "unmatched pair of setHasTransientState calls");
6681        } else if ((hasTransientState && mTransientStateCount == 1) ||
6682                (!hasTransientState && mTransientStateCount == 0)) {
6683            // update flag if we've just incremented up from 0 or decremented down to 0
6684            mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) |
6685                    (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0);
6686            if (mParent != null) {
6687                try {
6688                    mParent.childHasTransientStateChanged(this, hasTransientState);
6689                } catch (AbstractMethodError e) {
6690                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
6691                            " does not fully implement ViewParent", e);
6692                }
6693            }
6694        }
6695    }
6696
6697    /**
6698     * Returns true if this view is currently attached to a window.
6699     */
6700    public boolean isAttachedToWindow() {
6701        return mAttachInfo != null;
6702    }
6703
6704    /**
6705     * Returns true if this view has been through at least one layout since it
6706     * was last attached to or detached from a window.
6707     */
6708    public boolean isLaidOut() {
6709        return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT;
6710    }
6711
6712    /**
6713     * If this view doesn't do any drawing on its own, set this flag to
6714     * allow further optimizations. By default, this flag is not set on
6715     * View, but could be set on some View subclasses such as ViewGroup.
6716     *
6717     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
6718     * you should clear this flag.
6719     *
6720     * @param willNotDraw whether or not this View draw on its own
6721     */
6722    public void setWillNotDraw(boolean willNotDraw) {
6723        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
6724    }
6725
6726    /**
6727     * Returns whether or not this View draws on its own.
6728     *
6729     * @return true if this view has nothing to draw, false otherwise
6730     */
6731    @ViewDebug.ExportedProperty(category = "drawing")
6732    public boolean willNotDraw() {
6733        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
6734    }
6735
6736    /**
6737     * When a View's drawing cache is enabled, drawing is redirected to an
6738     * offscreen bitmap. Some views, like an ImageView, must be able to
6739     * bypass this mechanism if they already draw a single bitmap, to avoid
6740     * unnecessary usage of the memory.
6741     *
6742     * @param willNotCacheDrawing true if this view does not cache its
6743     *        drawing, false otherwise
6744     */
6745    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
6746        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
6747    }
6748
6749    /**
6750     * Returns whether or not this View can cache its drawing or not.
6751     *
6752     * @return true if this view does not cache its drawing, false otherwise
6753     */
6754    @ViewDebug.ExportedProperty(category = "drawing")
6755    public boolean willNotCacheDrawing() {
6756        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
6757    }
6758
6759    /**
6760     * Indicates whether this view reacts to click events or not.
6761     *
6762     * @return true if the view is clickable, false otherwise
6763     *
6764     * @see #setClickable(boolean)
6765     * @attr ref android.R.styleable#View_clickable
6766     */
6767    @ViewDebug.ExportedProperty
6768    public boolean isClickable() {
6769        return (mViewFlags & CLICKABLE) == CLICKABLE;
6770    }
6771
6772    /**
6773     * Enables or disables click events for this view. When a view
6774     * is clickable it will change its state to "pressed" on every click.
6775     * Subclasses should set the view clickable to visually react to
6776     * user's clicks.
6777     *
6778     * @param clickable true to make the view clickable, false otherwise
6779     *
6780     * @see #isClickable()
6781     * @attr ref android.R.styleable#View_clickable
6782     */
6783    public void setClickable(boolean clickable) {
6784        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
6785    }
6786
6787    /**
6788     * Indicates whether this view reacts to long click events or not.
6789     *
6790     * @return true if the view is long clickable, false otherwise
6791     *
6792     * @see #setLongClickable(boolean)
6793     * @attr ref android.R.styleable#View_longClickable
6794     */
6795    public boolean isLongClickable() {
6796        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
6797    }
6798
6799    /**
6800     * Enables or disables long click events for this view. When a view is long
6801     * clickable it reacts to the user holding down the button for a longer
6802     * duration than a tap. This event can either launch the listener or a
6803     * context menu.
6804     *
6805     * @param longClickable true to make the view long clickable, false otherwise
6806     * @see #isLongClickable()
6807     * @attr ref android.R.styleable#View_longClickable
6808     */
6809    public void setLongClickable(boolean longClickable) {
6810        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
6811    }
6812
6813    /**
6814     * Sets the pressed state for this view.
6815     *
6816     * @see #isClickable()
6817     * @see #setClickable(boolean)
6818     *
6819     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
6820     *        the View's internal state from a previously set "pressed" state.
6821     */
6822    public void setPressed(boolean pressed) {
6823        final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
6824
6825        if (pressed) {
6826            mPrivateFlags |= PFLAG_PRESSED;
6827        } else {
6828            mPrivateFlags &= ~PFLAG_PRESSED;
6829        }
6830
6831        if (needsRefresh) {
6832            refreshDrawableState();
6833        }
6834        dispatchSetPressed(pressed);
6835    }
6836
6837    /**
6838     * Dispatch setPressed to all of this View's children.
6839     *
6840     * @see #setPressed(boolean)
6841     *
6842     * @param pressed The new pressed state
6843     */
6844    protected void dispatchSetPressed(boolean pressed) {
6845    }
6846
6847    /**
6848     * Indicates whether the view is currently in pressed state. Unless
6849     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
6850     * the pressed state.
6851     *
6852     * @see #setPressed(boolean)
6853     * @see #isClickable()
6854     * @see #setClickable(boolean)
6855     *
6856     * @return true if the view is currently pressed, false otherwise
6857     */
6858    public boolean isPressed() {
6859        return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED;
6860    }
6861
6862    /**
6863     * Indicates whether this view will save its state (that is,
6864     * whether its {@link #onSaveInstanceState} method will be called).
6865     *
6866     * @return Returns true if the view state saving is enabled, else false.
6867     *
6868     * @see #setSaveEnabled(boolean)
6869     * @attr ref android.R.styleable#View_saveEnabled
6870     */
6871    public boolean isSaveEnabled() {
6872        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
6873    }
6874
6875    /**
6876     * Controls whether the saving of this view's state is
6877     * enabled (that is, whether its {@link #onSaveInstanceState} method
6878     * will be called).  Note that even if freezing is enabled, the
6879     * view still must have an id assigned to it (via {@link #setId(int)})
6880     * for its state to be saved.  This flag can only disable the
6881     * saving of this view; any child views may still have their state saved.
6882     *
6883     * @param enabled Set to false to <em>disable</em> state saving, or true
6884     * (the default) to allow it.
6885     *
6886     * @see #isSaveEnabled()
6887     * @see #setId(int)
6888     * @see #onSaveInstanceState()
6889     * @attr ref android.R.styleable#View_saveEnabled
6890     */
6891    public void setSaveEnabled(boolean enabled) {
6892        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
6893    }
6894
6895    /**
6896     * Gets whether the framework should discard touches when the view's
6897     * window is obscured by another visible window.
6898     * Refer to the {@link View} security documentation for more details.
6899     *
6900     * @return True if touch filtering is enabled.
6901     *
6902     * @see #setFilterTouchesWhenObscured(boolean)
6903     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
6904     */
6905    @ViewDebug.ExportedProperty
6906    public boolean getFilterTouchesWhenObscured() {
6907        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
6908    }
6909
6910    /**
6911     * Sets whether the framework should discard touches when the view's
6912     * window is obscured by another visible window.
6913     * Refer to the {@link View} security documentation for more details.
6914     *
6915     * @param enabled True if touch filtering should be enabled.
6916     *
6917     * @see #getFilterTouchesWhenObscured
6918     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
6919     */
6920    public void setFilterTouchesWhenObscured(boolean enabled) {
6921        setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
6922                FILTER_TOUCHES_WHEN_OBSCURED);
6923    }
6924
6925    /**
6926     * Indicates whether the entire hierarchy under this view will save its
6927     * state when a state saving traversal occurs from its parent.  The default
6928     * is true; if false, these views will not be saved unless
6929     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
6930     *
6931     * @return Returns true if the view state saving from parent is enabled, else false.
6932     *
6933     * @see #setSaveFromParentEnabled(boolean)
6934     */
6935    public boolean isSaveFromParentEnabled() {
6936        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
6937    }
6938
6939    /**
6940     * Controls whether the entire hierarchy under this view will save its
6941     * state when a state saving traversal occurs from its parent.  The default
6942     * is true; if false, these views will not be saved unless
6943     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
6944     *
6945     * @param enabled Set to false to <em>disable</em> state saving, or true
6946     * (the default) to allow it.
6947     *
6948     * @see #isSaveFromParentEnabled()
6949     * @see #setId(int)
6950     * @see #onSaveInstanceState()
6951     */
6952    public void setSaveFromParentEnabled(boolean enabled) {
6953        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
6954    }
6955
6956
6957    /**
6958     * Returns whether this View is able to take focus.
6959     *
6960     * @return True if this view can take focus, or false otherwise.
6961     * @attr ref android.R.styleable#View_focusable
6962     */
6963    @ViewDebug.ExportedProperty(category = "focus")
6964    public final boolean isFocusable() {
6965        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
6966    }
6967
6968    /**
6969     * When a view is focusable, it may not want to take focus when in touch mode.
6970     * For example, a button would like focus when the user is navigating via a D-pad
6971     * so that the user can click on it, but once the user starts touching the screen,
6972     * the button shouldn't take focus
6973     * @return Whether the view is focusable in touch mode.
6974     * @attr ref android.R.styleable#View_focusableInTouchMode
6975     */
6976    @ViewDebug.ExportedProperty
6977    public final boolean isFocusableInTouchMode() {
6978        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
6979    }
6980
6981    /**
6982     * Find the nearest view in the specified direction that can take focus.
6983     * This does not actually give focus to that view.
6984     *
6985     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6986     *
6987     * @return The nearest focusable in the specified direction, or null if none
6988     *         can be found.
6989     */
6990    public View focusSearch(@FocusRealDirection int direction) {
6991        if (mParent != null) {
6992            return mParent.focusSearch(this, direction);
6993        } else {
6994            return null;
6995        }
6996    }
6997
6998    /**
6999     * This method is the last chance for the focused view and its ancestors to
7000     * respond to an arrow key. This is called when the focused view did not
7001     * consume the key internally, nor could the view system find a new view in
7002     * the requested direction to give focus to.
7003     *
7004     * @param focused The currently focused view.
7005     * @param direction The direction focus wants to move. One of FOCUS_UP,
7006     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
7007     * @return True if the this view consumed this unhandled move.
7008     */
7009    public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) {
7010        return false;
7011    }
7012
7013    /**
7014     * If a user manually specified the next view id for a particular direction,
7015     * use the root to look up the view.
7016     * @param root The root view of the hierarchy containing this view.
7017     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
7018     * or FOCUS_BACKWARD.
7019     * @return The user specified next view, or null if there is none.
7020     */
7021    View findUserSetNextFocus(View root, @FocusDirection int direction) {
7022        switch (direction) {
7023            case FOCUS_LEFT:
7024                if (mNextFocusLeftId == View.NO_ID) return null;
7025                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
7026            case FOCUS_RIGHT:
7027                if (mNextFocusRightId == View.NO_ID) return null;
7028                return findViewInsideOutShouldExist(root, mNextFocusRightId);
7029            case FOCUS_UP:
7030                if (mNextFocusUpId == View.NO_ID) return null;
7031                return findViewInsideOutShouldExist(root, mNextFocusUpId);
7032            case FOCUS_DOWN:
7033                if (mNextFocusDownId == View.NO_ID) return null;
7034                return findViewInsideOutShouldExist(root, mNextFocusDownId);
7035            case FOCUS_FORWARD:
7036                if (mNextFocusForwardId == View.NO_ID) return null;
7037                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
7038            case FOCUS_BACKWARD: {
7039                if (mID == View.NO_ID) return null;
7040                final int id = mID;
7041                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
7042                    @Override
7043                    public boolean apply(View t) {
7044                        return t.mNextFocusForwardId == id;
7045                    }
7046                });
7047            }
7048        }
7049        return null;
7050    }
7051
7052    private View findViewInsideOutShouldExist(View root, int id) {
7053        if (mMatchIdPredicate == null) {
7054            mMatchIdPredicate = new MatchIdPredicate();
7055        }
7056        mMatchIdPredicate.mId = id;
7057        View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate);
7058        if (result == null) {
7059            Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id);
7060        }
7061        return result;
7062    }
7063
7064    /**
7065     * Find and return all focusable views that are descendants of this view,
7066     * possibly including this view if it is focusable itself.
7067     *
7068     * @param direction The direction of the focus
7069     * @return A list of focusable views
7070     */
7071    public ArrayList<View> getFocusables(@FocusDirection int direction) {
7072        ArrayList<View> result = new ArrayList<View>(24);
7073        addFocusables(result, direction);
7074        return result;
7075    }
7076
7077    /**
7078     * Add any focusable views that are descendants of this view (possibly
7079     * including this view if it is focusable itself) to views.  If we are in touch mode,
7080     * only add views that are also focusable in touch mode.
7081     *
7082     * @param views Focusable views found so far
7083     * @param direction The direction of the focus
7084     */
7085    public void addFocusables(ArrayList<View> views, @FocusDirection int direction) {
7086        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
7087    }
7088
7089    /**
7090     * Adds any focusable views that are descendants of this view (possibly
7091     * including this view if it is focusable itself) to views. This method
7092     * adds all focusable views regardless if we are in touch mode or
7093     * only views focusable in touch mode if we are in touch mode or
7094     * only views that can take accessibility focus if accessibility is enabeld
7095     * depending on the focusable mode paramater.
7096     *
7097     * @param views Focusable views found so far or null if all we are interested is
7098     *        the number of focusables.
7099     * @param direction The direction of the focus.
7100     * @param focusableMode The type of focusables to be added.
7101     *
7102     * @see #FOCUSABLES_ALL
7103     * @see #FOCUSABLES_TOUCH_MODE
7104     */
7105    public void addFocusables(ArrayList<View> views, @FocusDirection int direction,
7106            @FocusableMode int focusableMode) {
7107        if (views == null) {
7108            return;
7109        }
7110        if (!isFocusable()) {
7111            return;
7112        }
7113        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
7114                && isInTouchMode() && !isFocusableInTouchMode()) {
7115            return;
7116        }
7117        views.add(this);
7118    }
7119
7120    /**
7121     * Finds the Views that contain given text. The containment is case insensitive.
7122     * The search is performed by either the text that the View renders or the content
7123     * description that describes the view for accessibility purposes and the view does
7124     * not render or both. Clients can specify how the search is to be performed via
7125     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
7126     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
7127     *
7128     * @param outViews The output list of matching Views.
7129     * @param searched The text to match against.
7130     *
7131     * @see #FIND_VIEWS_WITH_TEXT
7132     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
7133     * @see #setContentDescription(CharSequence)
7134     */
7135    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched,
7136            @FindViewFlags int flags) {
7137        if (getAccessibilityNodeProvider() != null) {
7138            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
7139                outViews.add(this);
7140            }
7141        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
7142                && (searched != null && searched.length() > 0)
7143                && (mContentDescription != null && mContentDescription.length() > 0)) {
7144            String searchedLowerCase = searched.toString().toLowerCase();
7145            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
7146            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
7147                outViews.add(this);
7148            }
7149        }
7150    }
7151
7152    /**
7153     * Find and return all touchable views that are descendants of this view,
7154     * possibly including this view if it is touchable itself.
7155     *
7156     * @return A list of touchable views
7157     */
7158    public ArrayList<View> getTouchables() {
7159        ArrayList<View> result = new ArrayList<View>();
7160        addTouchables(result);
7161        return result;
7162    }
7163
7164    /**
7165     * Add any touchable views that are descendants of this view (possibly
7166     * including this view if it is touchable itself) to views.
7167     *
7168     * @param views Touchable views found so far
7169     */
7170    public void addTouchables(ArrayList<View> views) {
7171        final int viewFlags = mViewFlags;
7172
7173        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
7174                && (viewFlags & ENABLED_MASK) == ENABLED) {
7175            views.add(this);
7176        }
7177    }
7178
7179    /**
7180     * Returns whether this View is accessibility focused.
7181     *
7182     * @return True if this View is accessibility focused.
7183     */
7184    public boolean isAccessibilityFocused() {
7185        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
7186    }
7187
7188    /**
7189     * Call this to try to give accessibility focus to this view.
7190     *
7191     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
7192     * returns false or the view is no visible or the view already has accessibility
7193     * focus.
7194     *
7195     * See also {@link #focusSearch(int)}, which is what you call to say that you
7196     * have focus, and you want your parent to look for the next one.
7197     *
7198     * @return Whether this view actually took accessibility focus.
7199     *
7200     * @hide
7201     */
7202    public boolean requestAccessibilityFocus() {
7203        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
7204        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
7205            return false;
7206        }
7207        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
7208            return false;
7209        }
7210        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
7211            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
7212            ViewRootImpl viewRootImpl = getViewRootImpl();
7213            if (viewRootImpl != null) {
7214                viewRootImpl.setAccessibilityFocus(this, null);
7215            }
7216            invalidate();
7217            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
7218            return true;
7219        }
7220        return false;
7221    }
7222
7223    /**
7224     * Call this to try to clear accessibility focus of this view.
7225     *
7226     * See also {@link #focusSearch(int)}, which is what you call to say that you
7227     * have focus, and you want your parent to look for the next one.
7228     *
7229     * @hide
7230     */
7231    public void clearAccessibilityFocus() {
7232        clearAccessibilityFocusNoCallbacks();
7233        // Clear the global reference of accessibility focus if this
7234        // view or any of its descendants had accessibility focus.
7235        ViewRootImpl viewRootImpl = getViewRootImpl();
7236        if (viewRootImpl != null) {
7237            View focusHost = viewRootImpl.getAccessibilityFocusedHost();
7238            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
7239                viewRootImpl.setAccessibilityFocus(null, null);
7240            }
7241        }
7242    }
7243
7244    private void sendAccessibilityHoverEvent(int eventType) {
7245        // Since we are not delivering to a client accessibility events from not
7246        // important views (unless the clinet request that) we need to fire the
7247        // event from the deepest view exposed to the client. As a consequence if
7248        // the user crosses a not exposed view the client will see enter and exit
7249        // of the exposed predecessor followed by and enter and exit of that same
7250        // predecessor when entering and exiting the not exposed descendant. This
7251        // is fine since the client has a clear idea which view is hovered at the
7252        // price of a couple more events being sent. This is a simple and
7253        // working solution.
7254        View source = this;
7255        while (true) {
7256            if (source.includeForAccessibility()) {
7257                source.sendAccessibilityEvent(eventType);
7258                return;
7259            }
7260            ViewParent parent = source.getParent();
7261            if (parent instanceof View) {
7262                source = (View) parent;
7263            } else {
7264                return;
7265            }
7266        }
7267    }
7268
7269    /**
7270     * Clears accessibility focus without calling any callback methods
7271     * normally invoked in {@link #clearAccessibilityFocus()}. This method
7272     * is used for clearing accessibility focus when giving this focus to
7273     * another view.
7274     */
7275    void clearAccessibilityFocusNoCallbacks() {
7276        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
7277            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
7278            invalidate();
7279            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
7280        }
7281    }
7282
7283    /**
7284     * Call this to try to give focus to a specific view or to one of its
7285     * descendants.
7286     *
7287     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7288     * false), or if it is focusable and it is not focusable in touch mode
7289     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7290     *
7291     * See also {@link #focusSearch(int)}, which is what you call to say that you
7292     * have focus, and you want your parent to look for the next one.
7293     *
7294     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
7295     * {@link #FOCUS_DOWN} and <code>null</code>.
7296     *
7297     * @return Whether this view or one of its descendants actually took focus.
7298     */
7299    public final boolean requestFocus() {
7300        return requestFocus(View.FOCUS_DOWN);
7301    }
7302
7303    /**
7304     * Call this to try to give focus to a specific view or to one of its
7305     * descendants and give it a hint about what direction focus is heading.
7306     *
7307     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7308     * false), or if it is focusable and it is not focusable in touch mode
7309     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7310     *
7311     * See also {@link #focusSearch(int)}, which is what you call to say that you
7312     * have focus, and you want your parent to look for the next one.
7313     *
7314     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
7315     * <code>null</code> set for the previously focused rectangle.
7316     *
7317     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
7318     * @return Whether this view or one of its descendants actually took focus.
7319     */
7320    public final boolean requestFocus(int direction) {
7321        return requestFocus(direction, null);
7322    }
7323
7324    /**
7325     * Call this to try to give focus to a specific view or to one of its descendants
7326     * and give it hints about the direction and a specific rectangle that the focus
7327     * is coming from.  The rectangle can help give larger views a finer grained hint
7328     * about where focus is coming from, and therefore, where to show selection, or
7329     * forward focus change internally.
7330     *
7331     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7332     * false), or if it is focusable and it is not focusable in touch mode
7333     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7334     *
7335     * A View will not take focus if it is not visible.
7336     *
7337     * A View will not take focus if one of its parents has
7338     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
7339     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
7340     *
7341     * See also {@link #focusSearch(int)}, which is what you call to say that you
7342     * have focus, and you want your parent to look for the next one.
7343     *
7344     * You may wish to override this method if your custom {@link View} has an internal
7345     * {@link View} that it wishes to forward the request to.
7346     *
7347     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
7348     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
7349     *        to give a finer grained hint about where focus is coming from.  May be null
7350     *        if there is no hint.
7351     * @return Whether this view or one of its descendants actually took focus.
7352     */
7353    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
7354        return requestFocusNoSearch(direction, previouslyFocusedRect);
7355    }
7356
7357    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
7358        // need to be focusable
7359        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
7360                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
7361            return false;
7362        }
7363
7364        // need to be focusable in touch mode if in touch mode
7365        if (isInTouchMode() &&
7366            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
7367               return false;
7368        }
7369
7370        // need to not have any parents blocking us
7371        if (hasAncestorThatBlocksDescendantFocus()) {
7372            return false;
7373        }
7374
7375        handleFocusGainInternal(direction, previouslyFocusedRect);
7376        return true;
7377    }
7378
7379    /**
7380     * Call this to try to give focus to a specific view or to one of its descendants. This is a
7381     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
7382     * touch mode to request focus when they are touched.
7383     *
7384     * @return Whether this view or one of its descendants actually took focus.
7385     *
7386     * @see #isInTouchMode()
7387     *
7388     */
7389    public final boolean requestFocusFromTouch() {
7390        // Leave touch mode if we need to
7391        if (isInTouchMode()) {
7392            ViewRootImpl viewRoot = getViewRootImpl();
7393            if (viewRoot != null) {
7394                viewRoot.ensureTouchMode(false);
7395            }
7396        }
7397        return requestFocus(View.FOCUS_DOWN);
7398    }
7399
7400    /**
7401     * @return Whether any ancestor of this view blocks descendant focus.
7402     */
7403    private boolean hasAncestorThatBlocksDescendantFocus() {
7404        ViewParent ancestor = mParent;
7405        while (ancestor instanceof ViewGroup) {
7406            final ViewGroup vgAncestor = (ViewGroup) ancestor;
7407            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
7408                return true;
7409            } else {
7410                ancestor = vgAncestor.getParent();
7411            }
7412        }
7413        return false;
7414    }
7415
7416    /**
7417     * Gets the mode for determining whether this View is important for accessibility
7418     * which is if it fires accessibility events and if it is reported to
7419     * accessibility services that query the screen.
7420     *
7421     * @return The mode for determining whether a View is important for accessibility.
7422     *
7423     * @attr ref android.R.styleable#View_importantForAccessibility
7424     *
7425     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
7426     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
7427     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
7428     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
7429     */
7430    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
7431            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
7432            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
7433            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"),
7434            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS,
7435                    to = "noHideDescendants")
7436        })
7437    public int getImportantForAccessibility() {
7438        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
7439                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
7440    }
7441
7442    /**
7443     * Sets the live region mode for this view. This indicates to accessibility
7444     * services whether they should automatically notify the user about changes
7445     * to the view's content description or text, or to the content descriptions
7446     * or text of the view's children (where applicable).
7447     * <p>
7448     * For example, in a login screen with a TextView that displays an "incorrect
7449     * password" notification, that view should be marked as a live region with
7450     * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
7451     * <p>
7452     * To disable change notifications for this view, use
7453     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region
7454     * mode for most views.
7455     * <p>
7456     * To indicate that the user should be notified of changes, use
7457     * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
7458     * <p>
7459     * If the view's changes should interrupt ongoing speech and notify the user
7460     * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}.
7461     *
7462     * @param mode The live region mode for this view, one of:
7463     *        <ul>
7464     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE}
7465     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE}
7466     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}
7467     *        </ul>
7468     * @attr ref android.R.styleable#View_accessibilityLiveRegion
7469     */
7470    public void setAccessibilityLiveRegion(int mode) {
7471        if (mode != getAccessibilityLiveRegion()) {
7472            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
7473            mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT)
7474                    & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
7475            notifyViewAccessibilityStateChangedIfNeeded(
7476                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7477        }
7478    }
7479
7480    /**
7481     * Gets the live region mode for this View.
7482     *
7483     * @return The live region mode for the view.
7484     *
7485     * @attr ref android.R.styleable#View_accessibilityLiveRegion
7486     *
7487     * @see #setAccessibilityLiveRegion(int)
7488     */
7489    public int getAccessibilityLiveRegion() {
7490        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK)
7491                >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
7492    }
7493
7494    /**
7495     * Sets how to determine whether this view is important for accessibility
7496     * which is if it fires accessibility events and if it is reported to
7497     * accessibility services that query the screen.
7498     *
7499     * @param mode How to determine whether this view is important for accessibility.
7500     *
7501     * @attr ref android.R.styleable#View_importantForAccessibility
7502     *
7503     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
7504     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
7505     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
7506     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
7507     */
7508    public void setImportantForAccessibility(int mode) {
7509        final int oldMode = getImportantForAccessibility();
7510        if (mode != oldMode) {
7511            // If we're moving between AUTO and another state, we might not need
7512            // to send a subtree changed notification. We'll store the computed
7513            // importance, since we'll need to check it later to make sure.
7514            final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO
7515                    || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO;
7516            final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility();
7517            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
7518            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
7519                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
7520            if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) {
7521                notifySubtreeAccessibilityStateChangedIfNeeded();
7522            } else {
7523                notifyViewAccessibilityStateChangedIfNeeded(
7524                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7525            }
7526        }
7527    }
7528
7529    /**
7530     * Computes whether this view should be exposed for accessibility. In
7531     * general, views that are interactive or provide information are exposed
7532     * while views that serve only as containers are hidden.
7533     * <p>
7534     * If an ancestor of this view has importance
7535     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method
7536     * returns <code>false</code>.
7537     * <p>
7538     * Otherwise, the value is computed according to the view's
7539     * {@link #getImportantForAccessibility()} value:
7540     * <ol>
7541     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or
7542     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false
7543     * </code>
7544     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code>
7545     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if
7546     * view satisfies any of the following:
7547     * <ul>
7548     * <li>Is actionable, e.g. {@link #isClickable()},
7549     * {@link #isLongClickable()}, or {@link #isFocusable()}
7550     * <li>Has an {@link AccessibilityDelegate}
7551     * <li>Has an interaction listener, e.g. {@link OnTouchListener},
7552     * {@link OnKeyListener}, etc.
7553     * <li>Is an accessibility live region, e.g.
7554     * {@link #getAccessibilityLiveRegion()} is not
7555     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}.
7556     * </ul>
7557     * </ol>
7558     *
7559     * @return Whether the view is exposed for accessibility.
7560     * @see #setImportantForAccessibility(int)
7561     * @see #getImportantForAccessibility()
7562     */
7563    public boolean isImportantForAccessibility() {
7564        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
7565                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
7566        if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO
7567                || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
7568            return false;
7569        }
7570
7571        // Check parent mode to ensure we're not hidden.
7572        ViewParent parent = mParent;
7573        while (parent instanceof View) {
7574            if (((View) parent).getImportantForAccessibility()
7575                    == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
7576                return false;
7577            }
7578            parent = parent.getParent();
7579        }
7580
7581        return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility()
7582                || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null
7583                || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE;
7584    }
7585
7586    /**
7587     * Gets the parent for accessibility purposes. Note that the parent for
7588     * accessibility is not necessary the immediate parent. It is the first
7589     * predecessor that is important for accessibility.
7590     *
7591     * @return The parent for accessibility purposes.
7592     */
7593    public ViewParent getParentForAccessibility() {
7594        if (mParent instanceof View) {
7595            View parentView = (View) mParent;
7596            if (parentView.includeForAccessibility()) {
7597                return mParent;
7598            } else {
7599                return mParent.getParentForAccessibility();
7600            }
7601        }
7602        return null;
7603    }
7604
7605    /**
7606     * Adds the children of a given View for accessibility. Since some Views are
7607     * not important for accessibility the children for accessibility are not
7608     * necessarily direct children of the view, rather they are the first level of
7609     * descendants important for accessibility.
7610     *
7611     * @param children The list of children for accessibility.
7612     */
7613    public void addChildrenForAccessibility(ArrayList<View> children) {
7614
7615    }
7616
7617    /**
7618     * Whether to regard this view for accessibility. A view is regarded for
7619     * accessibility if it is important for accessibility or the querying
7620     * accessibility service has explicitly requested that view not
7621     * important for accessibility are regarded.
7622     *
7623     * @return Whether to regard the view for accessibility.
7624     *
7625     * @hide
7626     */
7627    public boolean includeForAccessibility() {
7628        if (mAttachInfo != null) {
7629            return (mAttachInfo.mAccessibilityFetchFlags
7630                    & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0
7631                    || isImportantForAccessibility();
7632        }
7633        return false;
7634    }
7635
7636    /**
7637     * Returns whether the View is considered actionable from
7638     * accessibility perspective. Such view are important for
7639     * accessibility.
7640     *
7641     * @return True if the view is actionable for accessibility.
7642     *
7643     * @hide
7644     */
7645    public boolean isActionableForAccessibility() {
7646        return (isClickable() || isLongClickable() || isFocusable());
7647    }
7648
7649    /**
7650     * Returns whether the View has registered callbacks which makes it
7651     * important for accessibility.
7652     *
7653     * @return True if the view is actionable for accessibility.
7654     */
7655    private boolean hasListenersForAccessibility() {
7656        ListenerInfo info = getListenerInfo();
7657        return mTouchDelegate != null || info.mOnKeyListener != null
7658                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
7659                || info.mOnHoverListener != null || info.mOnDragListener != null;
7660    }
7661
7662    /**
7663     * Notifies that the accessibility state of this view changed. The change
7664     * is local to this view and does not represent structural changes such
7665     * as children and parent. For example, the view became focusable. The
7666     * notification is at at most once every
7667     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
7668     * to avoid unnecessary load to the system. Also once a view has a pending
7669     * notification this method is a NOP until the notification has been sent.
7670     *
7671     * @hide
7672     */
7673    public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) {
7674        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
7675            return;
7676        }
7677        if (mSendViewStateChangedAccessibilityEvent == null) {
7678            mSendViewStateChangedAccessibilityEvent =
7679                    new SendViewStateChangedAccessibilityEvent();
7680        }
7681        mSendViewStateChangedAccessibilityEvent.runOrPost(changeType);
7682    }
7683
7684    /**
7685     * Notifies that the accessibility state of this view changed. The change
7686     * is *not* local to this view and does represent structural changes such
7687     * as children and parent. For example, the view size changed. The
7688     * notification is at at most once every
7689     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
7690     * to avoid unnecessary load to the system. Also once a view has a pending
7691     * notifucation this method is a NOP until the notification has been sent.
7692     *
7693     * @hide
7694     */
7695    public void notifySubtreeAccessibilityStateChangedIfNeeded() {
7696        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
7697            return;
7698        }
7699        if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) {
7700            mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
7701            if (mParent != null) {
7702                try {
7703                    mParent.notifySubtreeAccessibilityStateChanged(
7704                            this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
7705                } catch (AbstractMethodError e) {
7706                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
7707                            " does not fully implement ViewParent", e);
7708                }
7709            }
7710        }
7711    }
7712
7713    /**
7714     * Reset the flag indicating the accessibility state of the subtree rooted
7715     * at this view changed.
7716     */
7717    void resetSubtreeAccessibilityStateChanged() {
7718        mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
7719    }
7720
7721    /**
7722     * Performs the specified accessibility action on the view. For
7723     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
7724     * <p>
7725     * If an {@link AccessibilityDelegate} has been specified via calling
7726     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
7727     * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
7728     * is responsible for handling this call.
7729     * </p>
7730     *
7731     * @param action The action to perform.
7732     * @param arguments Optional action arguments.
7733     * @return Whether the action was performed.
7734     */
7735    public boolean performAccessibilityAction(int action, Bundle arguments) {
7736      if (mAccessibilityDelegate != null) {
7737          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
7738      } else {
7739          return performAccessibilityActionInternal(action, arguments);
7740      }
7741    }
7742
7743   /**
7744    * @see #performAccessibilityAction(int, Bundle)
7745    *
7746    * Note: Called from the default {@link AccessibilityDelegate}.
7747    */
7748    boolean performAccessibilityActionInternal(int action, Bundle arguments) {
7749        switch (action) {
7750            case AccessibilityNodeInfo.ACTION_CLICK: {
7751                if (isClickable()) {
7752                    performClick();
7753                    return true;
7754                }
7755            } break;
7756            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
7757                if (isLongClickable()) {
7758                    performLongClick();
7759                    return true;
7760                }
7761            } break;
7762            case AccessibilityNodeInfo.ACTION_FOCUS: {
7763                if (!hasFocus()) {
7764                    // Get out of touch mode since accessibility
7765                    // wants to move focus around.
7766                    getViewRootImpl().ensureTouchMode(false);
7767                    return requestFocus();
7768                }
7769            } break;
7770            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
7771                if (hasFocus()) {
7772                    clearFocus();
7773                    return !isFocused();
7774                }
7775            } break;
7776            case AccessibilityNodeInfo.ACTION_SELECT: {
7777                if (!isSelected()) {
7778                    setSelected(true);
7779                    return isSelected();
7780                }
7781            } break;
7782            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
7783                if (isSelected()) {
7784                    setSelected(false);
7785                    return !isSelected();
7786                }
7787            } break;
7788            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
7789                if (!isAccessibilityFocused()) {
7790                    return requestAccessibilityFocus();
7791                }
7792            } break;
7793            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
7794                if (isAccessibilityFocused()) {
7795                    clearAccessibilityFocus();
7796                    return true;
7797                }
7798            } break;
7799            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
7800                if (arguments != null) {
7801                    final int granularity = arguments.getInt(
7802                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
7803                    final boolean extendSelection = arguments.getBoolean(
7804                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
7805                    return traverseAtGranularity(granularity, true, extendSelection);
7806                }
7807            } break;
7808            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
7809                if (arguments != null) {
7810                    final int granularity = arguments.getInt(
7811                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
7812                    final boolean extendSelection = arguments.getBoolean(
7813                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
7814                    return traverseAtGranularity(granularity, false, extendSelection);
7815                }
7816            } break;
7817            case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
7818                CharSequence text = getIterableTextForAccessibility();
7819                if (text == null) {
7820                    return false;
7821                }
7822                final int start = (arguments != null) ? arguments.getInt(
7823                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1;
7824                final int end = (arguments != null) ? arguments.getInt(
7825                AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1;
7826                // Only cursor position can be specified (selection length == 0)
7827                if ((getAccessibilitySelectionStart() != start
7828                        || getAccessibilitySelectionEnd() != end)
7829                        && (start == end)) {
7830                    setAccessibilitySelection(start, end);
7831                    notifyViewAccessibilityStateChangedIfNeeded(
7832                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7833                    return true;
7834                }
7835            } break;
7836        }
7837        return false;
7838    }
7839
7840    private boolean traverseAtGranularity(int granularity, boolean forward,
7841            boolean extendSelection) {
7842        CharSequence text = getIterableTextForAccessibility();
7843        if (text == null || text.length() == 0) {
7844            return false;
7845        }
7846        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
7847        if (iterator == null) {
7848            return false;
7849        }
7850        int current = getAccessibilitySelectionEnd();
7851        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7852            current = forward ? 0 : text.length();
7853        }
7854        final int[] range = forward ? iterator.following(current) : iterator.preceding(current);
7855        if (range == null) {
7856            return false;
7857        }
7858        final int segmentStart = range[0];
7859        final int segmentEnd = range[1];
7860        int selectionStart;
7861        int selectionEnd;
7862        if (extendSelection && isAccessibilitySelectionExtendable()) {
7863            selectionStart = getAccessibilitySelectionStart();
7864            if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7865                selectionStart = forward ? segmentStart : segmentEnd;
7866            }
7867            selectionEnd = forward ? segmentEnd : segmentStart;
7868        } else {
7869            selectionStart = selectionEnd= forward ? segmentEnd : segmentStart;
7870        }
7871        setAccessibilitySelection(selectionStart, selectionEnd);
7872        final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY
7873                : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY;
7874        sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd);
7875        return true;
7876    }
7877
7878    /**
7879     * Gets the text reported for accessibility purposes.
7880     *
7881     * @return The accessibility text.
7882     *
7883     * @hide
7884     */
7885    public CharSequence getIterableTextForAccessibility() {
7886        return getContentDescription();
7887    }
7888
7889    /**
7890     * Gets whether accessibility selection can be extended.
7891     *
7892     * @return If selection is extensible.
7893     *
7894     * @hide
7895     */
7896    public boolean isAccessibilitySelectionExtendable() {
7897        return false;
7898    }
7899
7900    /**
7901     * @hide
7902     */
7903    public int getAccessibilitySelectionStart() {
7904        return mAccessibilityCursorPosition;
7905    }
7906
7907    /**
7908     * @hide
7909     */
7910    public int getAccessibilitySelectionEnd() {
7911        return getAccessibilitySelectionStart();
7912    }
7913
7914    /**
7915     * @hide
7916     */
7917    public void setAccessibilitySelection(int start, int end) {
7918        if (start ==  end && end == mAccessibilityCursorPosition) {
7919            return;
7920        }
7921        if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) {
7922            mAccessibilityCursorPosition = start;
7923        } else {
7924            mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
7925        }
7926        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
7927    }
7928
7929    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
7930            int fromIndex, int toIndex) {
7931        if (mParent == null) {
7932            return;
7933        }
7934        AccessibilityEvent event = AccessibilityEvent.obtain(
7935                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
7936        onInitializeAccessibilityEvent(event);
7937        onPopulateAccessibilityEvent(event);
7938        event.setFromIndex(fromIndex);
7939        event.setToIndex(toIndex);
7940        event.setAction(action);
7941        event.setMovementGranularity(granularity);
7942        mParent.requestSendAccessibilityEvent(this, event);
7943    }
7944
7945    /**
7946     * @hide
7947     */
7948    public TextSegmentIterator getIteratorForGranularity(int granularity) {
7949        switch (granularity) {
7950            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
7951                CharSequence text = getIterableTextForAccessibility();
7952                if (text != null && text.length() > 0) {
7953                    CharacterTextSegmentIterator iterator =
7954                        CharacterTextSegmentIterator.getInstance(
7955                                mContext.getResources().getConfiguration().locale);
7956                    iterator.initialize(text.toString());
7957                    return iterator;
7958                }
7959            } break;
7960            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
7961                CharSequence text = getIterableTextForAccessibility();
7962                if (text != null && text.length() > 0) {
7963                    WordTextSegmentIterator iterator =
7964                        WordTextSegmentIterator.getInstance(
7965                                mContext.getResources().getConfiguration().locale);
7966                    iterator.initialize(text.toString());
7967                    return iterator;
7968                }
7969            } break;
7970            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
7971                CharSequence text = getIterableTextForAccessibility();
7972                if (text != null && text.length() > 0) {
7973                    ParagraphTextSegmentIterator iterator =
7974                        ParagraphTextSegmentIterator.getInstance();
7975                    iterator.initialize(text.toString());
7976                    return iterator;
7977                }
7978            } break;
7979        }
7980        return null;
7981    }
7982
7983    /**
7984     * @hide
7985     */
7986    public void dispatchStartTemporaryDetach() {
7987        onStartTemporaryDetach();
7988    }
7989
7990    /**
7991     * This is called when a container is going to temporarily detach a child, with
7992     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
7993     * It will either be followed by {@link #onFinishTemporaryDetach()} or
7994     * {@link #onDetachedFromWindow()} when the container is done.
7995     */
7996    public void onStartTemporaryDetach() {
7997        removeUnsetPressCallback();
7998        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
7999    }
8000
8001    /**
8002     * @hide
8003     */
8004    public void dispatchFinishTemporaryDetach() {
8005        onFinishTemporaryDetach();
8006    }
8007
8008    /**
8009     * Called after {@link #onStartTemporaryDetach} when the container is done
8010     * changing the view.
8011     */
8012    public void onFinishTemporaryDetach() {
8013    }
8014
8015    /**
8016     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
8017     * for this view's window.  Returns null if the view is not currently attached
8018     * to the window.  Normally you will not need to use this directly, but
8019     * just use the standard high-level event callbacks like
8020     * {@link #onKeyDown(int, KeyEvent)}.
8021     */
8022    public KeyEvent.DispatcherState getKeyDispatcherState() {
8023        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
8024    }
8025
8026    /**
8027     * Dispatch a key event before it is processed by any input method
8028     * associated with the view hierarchy.  This can be used to intercept
8029     * key events in special situations before the IME consumes them; a
8030     * typical example would be handling the BACK key to update the application's
8031     * UI instead of allowing the IME to see it and close itself.
8032     *
8033     * @param event The key event to be dispatched.
8034     * @return True if the event was handled, false otherwise.
8035     */
8036    public boolean dispatchKeyEventPreIme(KeyEvent event) {
8037        return onKeyPreIme(event.getKeyCode(), event);
8038    }
8039
8040    /**
8041     * Dispatch a key event to the next view on the focus path. This path runs
8042     * from the top of the view tree down to the currently focused view. If this
8043     * view has focus, it will dispatch to itself. Otherwise it will dispatch
8044     * the next node down the focus path. This method also fires any key
8045     * listeners.
8046     *
8047     * @param event The key event to be dispatched.
8048     * @return True if the event was handled, false otherwise.
8049     */
8050    public boolean dispatchKeyEvent(KeyEvent event) {
8051        if (mInputEventConsistencyVerifier != null) {
8052            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
8053        }
8054
8055        // Give any attached key listener a first crack at the event.
8056        //noinspection SimplifiableIfStatement
8057        ListenerInfo li = mListenerInfo;
8058        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
8059                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
8060            return true;
8061        }
8062
8063        if (event.dispatch(this, mAttachInfo != null
8064                ? mAttachInfo.mKeyDispatchState : null, this)) {
8065            return true;
8066        }
8067
8068        if (mInputEventConsistencyVerifier != null) {
8069            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8070        }
8071        return false;
8072    }
8073
8074    /**
8075     * Dispatches a key shortcut event.
8076     *
8077     * @param event The key event to be dispatched.
8078     * @return True if the event was handled by the view, false otherwise.
8079     */
8080    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
8081        return onKeyShortcut(event.getKeyCode(), event);
8082    }
8083
8084    /**
8085     * Pass the touch screen motion event down to the target view, or this
8086     * view if it is the target.
8087     *
8088     * @param event The motion event to be dispatched.
8089     * @return True if the event was handled by the view, false otherwise.
8090     */
8091    public boolean dispatchTouchEvent(MotionEvent event) {
8092        if (mInputEventConsistencyVerifier != null) {
8093            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
8094        }
8095
8096        if (onFilterTouchEventForSecurity(event)) {
8097            //noinspection SimplifiableIfStatement
8098            ListenerInfo li = mListenerInfo;
8099            if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
8100                    && li.mOnTouchListener.onTouch(this, event)) {
8101                return true;
8102            }
8103
8104            if (onTouchEvent(event)) {
8105                return true;
8106            }
8107        }
8108
8109        if (mInputEventConsistencyVerifier != null) {
8110            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8111        }
8112        return false;
8113    }
8114
8115    /**
8116     * Filter the touch event to apply security policies.
8117     *
8118     * @param event The motion event to be filtered.
8119     * @return True if the event should be dispatched, false if the event should be dropped.
8120     *
8121     * @see #getFilterTouchesWhenObscured
8122     */
8123    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
8124        //noinspection RedundantIfStatement
8125        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
8126                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
8127            // Window is obscured, drop this touch.
8128            return false;
8129        }
8130        return true;
8131    }
8132
8133    /**
8134     * Pass a trackball motion event down to the focused view.
8135     *
8136     * @param event The motion event to be dispatched.
8137     * @return True if the event was handled by the view, false otherwise.
8138     */
8139    public boolean dispatchTrackballEvent(MotionEvent event) {
8140        if (mInputEventConsistencyVerifier != null) {
8141            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
8142        }
8143
8144        return onTrackballEvent(event);
8145    }
8146
8147    /**
8148     * Dispatch a generic motion event.
8149     * <p>
8150     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
8151     * are delivered to the view under the pointer.  All other generic motion events are
8152     * delivered to the focused view.  Hover events are handled specially and are delivered
8153     * to {@link #onHoverEvent(MotionEvent)}.
8154     * </p>
8155     *
8156     * @param event The motion event to be dispatched.
8157     * @return True if the event was handled by the view, false otherwise.
8158     */
8159    public boolean dispatchGenericMotionEvent(MotionEvent event) {
8160        if (mInputEventConsistencyVerifier != null) {
8161            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
8162        }
8163
8164        final int source = event.getSource();
8165        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
8166            final int action = event.getAction();
8167            if (action == MotionEvent.ACTION_HOVER_ENTER
8168                    || action == MotionEvent.ACTION_HOVER_MOVE
8169                    || action == MotionEvent.ACTION_HOVER_EXIT) {
8170                if (dispatchHoverEvent(event)) {
8171                    return true;
8172                }
8173            } else if (dispatchGenericPointerEvent(event)) {
8174                return true;
8175            }
8176        } else if (dispatchGenericFocusedEvent(event)) {
8177            return true;
8178        }
8179
8180        if (dispatchGenericMotionEventInternal(event)) {
8181            return true;
8182        }
8183
8184        if (mInputEventConsistencyVerifier != null) {
8185            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8186        }
8187        return false;
8188    }
8189
8190    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
8191        //noinspection SimplifiableIfStatement
8192        ListenerInfo li = mListenerInfo;
8193        if (li != null && li.mOnGenericMotionListener != null
8194                && (mViewFlags & ENABLED_MASK) == ENABLED
8195                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
8196            return true;
8197        }
8198
8199        if (onGenericMotionEvent(event)) {
8200            return true;
8201        }
8202
8203        if (mInputEventConsistencyVerifier != null) {
8204            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8205        }
8206        return false;
8207    }
8208
8209    /**
8210     * Dispatch a hover event.
8211     * <p>
8212     * Do not call this method directly.
8213     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8214     * </p>
8215     *
8216     * @param event The motion event to be dispatched.
8217     * @return True if the event was handled by the view, false otherwise.
8218     */
8219    protected boolean dispatchHoverEvent(MotionEvent event) {
8220        ListenerInfo li = mListenerInfo;
8221        //noinspection SimplifiableIfStatement
8222        if (li != null && li.mOnHoverListener != null
8223                && (mViewFlags & ENABLED_MASK) == ENABLED
8224                && li.mOnHoverListener.onHover(this, event)) {
8225            return true;
8226        }
8227
8228        return onHoverEvent(event);
8229    }
8230
8231    /**
8232     * Returns true if the view has a child to which it has recently sent
8233     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
8234     * it does not have a hovered child, then it must be the innermost hovered view.
8235     * @hide
8236     */
8237    protected boolean hasHoveredChild() {
8238        return false;
8239    }
8240
8241    /**
8242     * Dispatch a generic motion event to the view under the first pointer.
8243     * <p>
8244     * Do not call this method directly.
8245     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8246     * </p>
8247     *
8248     * @param event The motion event to be dispatched.
8249     * @return True if the event was handled by the view, false otherwise.
8250     */
8251    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
8252        return false;
8253    }
8254
8255    /**
8256     * Dispatch a generic motion event to the currently focused view.
8257     * <p>
8258     * Do not call this method directly.
8259     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8260     * </p>
8261     *
8262     * @param event The motion event to be dispatched.
8263     * @return True if the event was handled by the view, false otherwise.
8264     */
8265    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
8266        return false;
8267    }
8268
8269    /**
8270     * Dispatch a pointer event.
8271     * <p>
8272     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
8273     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
8274     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
8275     * and should not be expected to handle other pointing device features.
8276     * </p>
8277     *
8278     * @param event The motion event to be dispatched.
8279     * @return True if the event was handled by the view, false otherwise.
8280     * @hide
8281     */
8282    public final boolean dispatchPointerEvent(MotionEvent event) {
8283        if (event.isTouchEvent()) {
8284            return dispatchTouchEvent(event);
8285        } else {
8286            return dispatchGenericMotionEvent(event);
8287        }
8288    }
8289
8290    /**
8291     * Called when the window containing this view gains or loses window focus.
8292     * ViewGroups should override to route to their children.
8293     *
8294     * @param hasFocus True if the window containing this view now has focus,
8295     *        false otherwise.
8296     */
8297    public void dispatchWindowFocusChanged(boolean hasFocus) {
8298        onWindowFocusChanged(hasFocus);
8299    }
8300
8301    /**
8302     * Called when the window containing this view gains or loses focus.  Note
8303     * that this is separate from view focus: to receive key events, both
8304     * your view and its window must have focus.  If a window is displayed
8305     * on top of yours that takes input focus, then your own window will lose
8306     * focus but the view focus will remain unchanged.
8307     *
8308     * @param hasWindowFocus True if the window containing this view now has
8309     *        focus, false otherwise.
8310     */
8311    public void onWindowFocusChanged(boolean hasWindowFocus) {
8312        InputMethodManager imm = InputMethodManager.peekInstance();
8313        if (!hasWindowFocus) {
8314            if (isPressed()) {
8315                setPressed(false);
8316            }
8317            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
8318                imm.focusOut(this);
8319            }
8320            removeLongPressCallback();
8321            removeTapCallback();
8322            onFocusLost();
8323        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
8324            imm.focusIn(this);
8325        }
8326        refreshDrawableState();
8327    }
8328
8329    /**
8330     * Returns true if this view is in a window that currently has window focus.
8331     * Note that this is not the same as the view itself having focus.
8332     *
8333     * @return True if this view is in a window that currently has window focus.
8334     */
8335    public boolean hasWindowFocus() {
8336        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
8337    }
8338
8339    /**
8340     * Dispatch a view visibility change down the view hierarchy.
8341     * ViewGroups should override to route to their children.
8342     * @param changedView The view whose visibility changed. Could be 'this' or
8343     * an ancestor view.
8344     * @param visibility The new visibility of changedView: {@link #VISIBLE},
8345     * {@link #INVISIBLE} or {@link #GONE}.
8346     */
8347    protected void dispatchVisibilityChanged(@NonNull View changedView,
8348            @Visibility int visibility) {
8349        onVisibilityChanged(changedView, visibility);
8350    }
8351
8352    /**
8353     * Called when the visibility of the view or an ancestor of the view is changed.
8354     * @param changedView The view whose visibility changed. Could be 'this' or
8355     * an ancestor view.
8356     * @param visibility The new visibility of changedView: {@link #VISIBLE},
8357     * {@link #INVISIBLE} or {@link #GONE}.
8358     */
8359    protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) {
8360        if (visibility == VISIBLE) {
8361            if (mAttachInfo != null) {
8362                initialAwakenScrollBars();
8363            } else {
8364                mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
8365            }
8366        }
8367    }
8368
8369    /**
8370     * Dispatch a hint about whether this view is displayed. For instance, when
8371     * a View moves out of the screen, it might receives a display hint indicating
8372     * the view is not displayed. Applications should not <em>rely</em> on this hint
8373     * as there is no guarantee that they will receive one.
8374     *
8375     * @param hint A hint about whether or not this view is displayed:
8376     * {@link #VISIBLE} or {@link #INVISIBLE}.
8377     */
8378    public void dispatchDisplayHint(@Visibility int hint) {
8379        onDisplayHint(hint);
8380    }
8381
8382    /**
8383     * Gives this view a hint about whether is displayed or not. For instance, when
8384     * a View moves out of the screen, it might receives a display hint indicating
8385     * the view is not displayed. Applications should not <em>rely</em> on this hint
8386     * as there is no guarantee that they will receive one.
8387     *
8388     * @param hint A hint about whether or not this view is displayed:
8389     * {@link #VISIBLE} or {@link #INVISIBLE}.
8390     */
8391    protected void onDisplayHint(@Visibility int hint) {
8392    }
8393
8394    /**
8395     * Dispatch a window visibility change down the view hierarchy.
8396     * ViewGroups should override to route to their children.
8397     *
8398     * @param visibility The new visibility of the window.
8399     *
8400     * @see #onWindowVisibilityChanged(int)
8401     */
8402    public void dispatchWindowVisibilityChanged(@Visibility int visibility) {
8403        onWindowVisibilityChanged(visibility);
8404    }
8405
8406    /**
8407     * Called when the window containing has change its visibility
8408     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
8409     * that this tells you whether or not your window is being made visible
8410     * to the window manager; this does <em>not</em> tell you whether or not
8411     * your window is obscured by other windows on the screen, even if it
8412     * is itself visible.
8413     *
8414     * @param visibility The new visibility of the window.
8415     */
8416    protected void onWindowVisibilityChanged(@Visibility int visibility) {
8417        if (visibility == VISIBLE) {
8418            initialAwakenScrollBars();
8419        }
8420    }
8421
8422    /**
8423     * Returns the current visibility of the window this view is attached to
8424     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
8425     *
8426     * @return Returns the current visibility of the view's window.
8427     */
8428    @Visibility
8429    public int getWindowVisibility() {
8430        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
8431    }
8432
8433    /**
8434     * Retrieve the overall visible display size in which the window this view is
8435     * attached to has been positioned in.  This takes into account screen
8436     * decorations above the window, for both cases where the window itself
8437     * is being position inside of them or the window is being placed under
8438     * then and covered insets are used for the window to position its content
8439     * inside.  In effect, this tells you the available area where content can
8440     * be placed and remain visible to users.
8441     *
8442     * <p>This function requires an IPC back to the window manager to retrieve
8443     * the requested information, so should not be used in performance critical
8444     * code like drawing.
8445     *
8446     * @param outRect Filled in with the visible display frame.  If the view
8447     * is not attached to a window, this is simply the raw display size.
8448     */
8449    public void getWindowVisibleDisplayFrame(Rect outRect) {
8450        if (mAttachInfo != null) {
8451            try {
8452                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
8453            } catch (RemoteException e) {
8454                return;
8455            }
8456            // XXX This is really broken, and probably all needs to be done
8457            // in the window manager, and we need to know more about whether
8458            // we want the area behind or in front of the IME.
8459            final Rect insets = mAttachInfo.mVisibleInsets;
8460            outRect.left += insets.left;
8461            outRect.top += insets.top;
8462            outRect.right -= insets.right;
8463            outRect.bottom -= insets.bottom;
8464            return;
8465        }
8466        // The view is not attached to a display so we don't have a context.
8467        // Make a best guess about the display size.
8468        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
8469        d.getRectSize(outRect);
8470    }
8471
8472    /**
8473     * Dispatch a notification about a resource configuration change down
8474     * the view hierarchy.
8475     * ViewGroups should override to route to their children.
8476     *
8477     * @param newConfig The new resource configuration.
8478     *
8479     * @see #onConfigurationChanged(android.content.res.Configuration)
8480     */
8481    public void dispatchConfigurationChanged(Configuration newConfig) {
8482        onConfigurationChanged(newConfig);
8483    }
8484
8485    /**
8486     * Called when the current configuration of the resources being used
8487     * by the application have changed.  You can use this to decide when
8488     * to reload resources that can changed based on orientation and other
8489     * configuration characterstics.  You only need to use this if you are
8490     * not relying on the normal {@link android.app.Activity} mechanism of
8491     * recreating the activity instance upon a configuration change.
8492     *
8493     * @param newConfig The new resource configuration.
8494     */
8495    protected void onConfigurationChanged(Configuration newConfig) {
8496    }
8497
8498    /**
8499     * Private function to aggregate all per-view attributes in to the view
8500     * root.
8501     */
8502    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
8503        performCollectViewAttributes(attachInfo, visibility);
8504    }
8505
8506    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
8507        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
8508            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
8509                attachInfo.mKeepScreenOn = true;
8510            }
8511            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
8512            ListenerInfo li = mListenerInfo;
8513            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
8514                attachInfo.mHasSystemUiListeners = true;
8515            }
8516        }
8517    }
8518
8519    void needGlobalAttributesUpdate(boolean force) {
8520        final AttachInfo ai = mAttachInfo;
8521        if (ai != null && !ai.mRecomputeGlobalAttributes) {
8522            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
8523                    || ai.mHasSystemUiListeners) {
8524                ai.mRecomputeGlobalAttributes = true;
8525            }
8526        }
8527    }
8528
8529    /**
8530     * Returns whether the device is currently in touch mode.  Touch mode is entered
8531     * once the user begins interacting with the device by touch, and affects various
8532     * things like whether focus is always visible to the user.
8533     *
8534     * @return Whether the device is in touch mode.
8535     */
8536    @ViewDebug.ExportedProperty
8537    public boolean isInTouchMode() {
8538        if (mAttachInfo != null) {
8539            return mAttachInfo.mInTouchMode;
8540        } else {
8541            return ViewRootImpl.isInTouchMode();
8542        }
8543    }
8544
8545    /**
8546     * Returns the context the view is running in, through which it can
8547     * access the current theme, resources, etc.
8548     *
8549     * @return The view's Context.
8550     */
8551    @ViewDebug.CapturedViewProperty
8552    public final Context getContext() {
8553        return mContext;
8554    }
8555
8556    /**
8557     * Handle a key event before it is processed by any input method
8558     * associated with the view hierarchy.  This can be used to intercept
8559     * key events in special situations before the IME consumes them; a
8560     * typical example would be handling the BACK key to update the application's
8561     * UI instead of allowing the IME to see it and close itself.
8562     *
8563     * @param keyCode The value in event.getKeyCode().
8564     * @param event Description of the key event.
8565     * @return If you handled the event, return true. If you want to allow the
8566     *         event to be handled by the next receiver, return false.
8567     */
8568    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
8569        return false;
8570    }
8571
8572    /**
8573     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
8574     * KeyEvent.Callback.onKeyDown()}: perform press of the view
8575     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
8576     * is released, if the view is enabled and clickable.
8577     *
8578     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8579     * although some may elect to do so in some situations. Do not rely on this to
8580     * catch software key presses.
8581     *
8582     * @param keyCode A key code that represents the button pressed, from
8583     *                {@link android.view.KeyEvent}.
8584     * @param event   The KeyEvent object that defines the button action.
8585     */
8586    public boolean onKeyDown(int keyCode, KeyEvent event) {
8587        boolean result = false;
8588
8589        if (KeyEvent.isConfirmKey(keyCode)) {
8590            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
8591                return true;
8592            }
8593            // Long clickable items don't necessarily have to be clickable
8594            if (((mViewFlags & CLICKABLE) == CLICKABLE ||
8595                    (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
8596                    (event.getRepeatCount() == 0)) {
8597                setPressed(true);
8598                checkForLongClick(0);
8599                return true;
8600            }
8601        }
8602        return result;
8603    }
8604
8605    /**
8606     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
8607     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
8608     * the event).
8609     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8610     * although some may elect to do so in some situations. Do not rely on this to
8611     * catch software key presses.
8612     */
8613    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
8614        return false;
8615    }
8616
8617    /**
8618     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
8619     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
8620     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
8621     * {@link KeyEvent#KEYCODE_ENTER} is released.
8622     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8623     * although some may elect to do so in some situations. Do not rely on this to
8624     * catch software key presses.
8625     *
8626     * @param keyCode A key code that represents the button pressed, from
8627     *                {@link android.view.KeyEvent}.
8628     * @param event   The KeyEvent object that defines the button action.
8629     */
8630    public boolean onKeyUp(int keyCode, KeyEvent event) {
8631        if (KeyEvent.isConfirmKey(keyCode)) {
8632            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
8633                return true;
8634            }
8635            if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
8636                setPressed(false);
8637
8638                if (!mHasPerformedLongPress) {
8639                    // This is a tap, so remove the longpress check
8640                    removeLongPressCallback();
8641                    return performClick();
8642                }
8643            }
8644        }
8645        return false;
8646    }
8647
8648    /**
8649     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
8650     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
8651     * the event).
8652     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8653     * although some may elect to do so in some situations. Do not rely on this to
8654     * catch software key presses.
8655     *
8656     * @param keyCode     A key code that represents the button pressed, from
8657     *                    {@link android.view.KeyEvent}.
8658     * @param repeatCount The number of times the action was made.
8659     * @param event       The KeyEvent object that defines the button action.
8660     */
8661    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
8662        return false;
8663    }
8664
8665    /**
8666     * Called on the focused view when a key shortcut event is not handled.
8667     * Override this method to implement local key shortcuts for the View.
8668     * Key shortcuts can also be implemented by setting the
8669     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
8670     *
8671     * @param keyCode The value in event.getKeyCode().
8672     * @param event Description of the key event.
8673     * @return If you handled the event, return true. If you want to allow the
8674     *         event to be handled by the next receiver, return false.
8675     */
8676    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
8677        return false;
8678    }
8679
8680    /**
8681     * Check whether the called view is a text editor, in which case it
8682     * would make sense to automatically display a soft input window for
8683     * it.  Subclasses should override this if they implement
8684     * {@link #onCreateInputConnection(EditorInfo)} to return true if
8685     * a call on that method would return a non-null InputConnection, and
8686     * they are really a first-class editor that the user would normally
8687     * start typing on when the go into a window containing your view.
8688     *
8689     * <p>The default implementation always returns false.  This does
8690     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
8691     * will not be called or the user can not otherwise perform edits on your
8692     * view; it is just a hint to the system that this is not the primary
8693     * purpose of this view.
8694     *
8695     * @return Returns true if this view is a text editor, else false.
8696     */
8697    public boolean onCheckIsTextEditor() {
8698        return false;
8699    }
8700
8701    /**
8702     * Create a new InputConnection for an InputMethod to interact
8703     * with the view.  The default implementation returns null, since it doesn't
8704     * support input methods.  You can override this to implement such support.
8705     * This is only needed for views that take focus and text input.
8706     *
8707     * <p>When implementing this, you probably also want to implement
8708     * {@link #onCheckIsTextEditor()} to indicate you will return a
8709     * non-null InputConnection.
8710     *
8711     * @param outAttrs Fill in with attribute information about the connection.
8712     */
8713    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
8714        return null;
8715    }
8716
8717    /**
8718     * Called by the {@link android.view.inputmethod.InputMethodManager}
8719     * when a view who is not the current
8720     * input connection target is trying to make a call on the manager.  The
8721     * default implementation returns false; you can override this to return
8722     * true for certain views if you are performing InputConnection proxying
8723     * to them.
8724     * @param view The View that is making the InputMethodManager call.
8725     * @return Return true to allow the call, false to reject.
8726     */
8727    public boolean checkInputConnectionProxy(View view) {
8728        return false;
8729    }
8730
8731    /**
8732     * Show the context menu for this view. It is not safe to hold on to the
8733     * menu after returning from this method.
8734     *
8735     * You should normally not overload this method. Overload
8736     * {@link #onCreateContextMenu(ContextMenu)} or define an
8737     * {@link OnCreateContextMenuListener} to add items to the context menu.
8738     *
8739     * @param menu The context menu to populate
8740     */
8741    public void createContextMenu(ContextMenu menu) {
8742        ContextMenuInfo menuInfo = getContextMenuInfo();
8743
8744        // Sets the current menu info so all items added to menu will have
8745        // my extra info set.
8746        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
8747
8748        onCreateContextMenu(menu);
8749        ListenerInfo li = mListenerInfo;
8750        if (li != null && li.mOnCreateContextMenuListener != null) {
8751            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
8752        }
8753
8754        // Clear the extra information so subsequent items that aren't mine don't
8755        // have my extra info.
8756        ((MenuBuilder)menu).setCurrentMenuInfo(null);
8757
8758        if (mParent != null) {
8759            mParent.createContextMenu(menu);
8760        }
8761    }
8762
8763    /**
8764     * Views should implement this if they have extra information to associate
8765     * with the context menu. The return result is supplied as a parameter to
8766     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
8767     * callback.
8768     *
8769     * @return Extra information about the item for which the context menu
8770     *         should be shown. This information will vary across different
8771     *         subclasses of View.
8772     */
8773    protected ContextMenuInfo getContextMenuInfo() {
8774        return null;
8775    }
8776
8777    /**
8778     * Views should implement this if the view itself is going to add items to
8779     * the context menu.
8780     *
8781     * @param menu the context menu to populate
8782     */
8783    protected void onCreateContextMenu(ContextMenu menu) {
8784    }
8785
8786    /**
8787     * Implement this method to handle trackball motion events.  The
8788     * <em>relative</em> movement of the trackball since the last event
8789     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
8790     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
8791     * that a movement of 1 corresponds to the user pressing one DPAD key (so
8792     * they will often be fractional values, representing the more fine-grained
8793     * movement information available from a trackball).
8794     *
8795     * @param event The motion event.
8796     * @return True if the event was handled, false otherwise.
8797     */
8798    public boolean onTrackballEvent(MotionEvent event) {
8799        return false;
8800    }
8801
8802    /**
8803     * Implement this method to handle generic motion events.
8804     * <p>
8805     * Generic motion events describe joystick movements, mouse hovers, track pad
8806     * touches, scroll wheel movements and other input events.  The
8807     * {@link MotionEvent#getSource() source} of the motion event specifies
8808     * the class of input that was received.  Implementations of this method
8809     * must examine the bits in the source before processing the event.
8810     * The following code example shows how this is done.
8811     * </p><p>
8812     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
8813     * are delivered to the view under the pointer.  All other generic motion events are
8814     * delivered to the focused view.
8815     * </p>
8816     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
8817     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {
8818     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
8819     *             // process the joystick movement...
8820     *             return true;
8821     *         }
8822     *     }
8823     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
8824     *         switch (event.getAction()) {
8825     *             case MotionEvent.ACTION_HOVER_MOVE:
8826     *                 // process the mouse hover movement...
8827     *                 return true;
8828     *             case MotionEvent.ACTION_SCROLL:
8829     *                 // process the scroll wheel movement...
8830     *                 return true;
8831     *         }
8832     *     }
8833     *     return super.onGenericMotionEvent(event);
8834     * }</pre>
8835     *
8836     * @param event The generic motion event being processed.
8837     * @return True if the event was handled, false otherwise.
8838     */
8839    public boolean onGenericMotionEvent(MotionEvent event) {
8840        return false;
8841    }
8842
8843    /**
8844     * Implement this method to handle hover events.
8845     * <p>
8846     * This method is called whenever a pointer is hovering into, over, or out of the
8847     * bounds of a view and the view is not currently being touched.
8848     * Hover events are represented as pointer events with action
8849     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
8850     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
8851     * </p>
8852     * <ul>
8853     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
8854     * when the pointer enters the bounds of the view.</li>
8855     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
8856     * when the pointer has already entered the bounds of the view and has moved.</li>
8857     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
8858     * when the pointer has exited the bounds of the view or when the pointer is
8859     * about to go down due to a button click, tap, or similar user action that
8860     * causes the view to be touched.</li>
8861     * </ul>
8862     * <p>
8863     * The view should implement this method to return true to indicate that it is
8864     * handling the hover event, such as by changing its drawable state.
8865     * </p><p>
8866     * The default implementation calls {@link #setHovered} to update the hovered state
8867     * of the view when a hover enter or hover exit event is received, if the view
8868     * is enabled and is clickable.  The default implementation also sends hover
8869     * accessibility events.
8870     * </p>
8871     *
8872     * @param event The motion event that describes the hover.
8873     * @return True if the view handled the hover event.
8874     *
8875     * @see #isHovered
8876     * @see #setHovered
8877     * @see #onHoverChanged
8878     */
8879    public boolean onHoverEvent(MotionEvent event) {
8880        // The root view may receive hover (or touch) events that are outside the bounds of
8881        // the window.  This code ensures that we only send accessibility events for
8882        // hovers that are actually within the bounds of the root view.
8883        final int action = event.getActionMasked();
8884        if (!mSendingHoverAccessibilityEvents) {
8885            if ((action == MotionEvent.ACTION_HOVER_ENTER
8886                    || action == MotionEvent.ACTION_HOVER_MOVE)
8887                    && !hasHoveredChild()
8888                    && pointInView(event.getX(), event.getY())) {
8889                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
8890                mSendingHoverAccessibilityEvents = true;
8891            }
8892        } else {
8893            if (action == MotionEvent.ACTION_HOVER_EXIT
8894                    || (action == MotionEvent.ACTION_MOVE
8895                            && !pointInView(event.getX(), event.getY()))) {
8896                mSendingHoverAccessibilityEvents = false;
8897                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
8898                // If the window does not have input focus we take away accessibility
8899                // focus as soon as the user stop hovering over the view.
8900                if (mAttachInfo != null && !mAttachInfo.mHasWindowFocus) {
8901                    getViewRootImpl().setAccessibilityFocus(null, null);
8902                }
8903            }
8904        }
8905
8906        if (isHoverable()) {
8907            switch (action) {
8908                case MotionEvent.ACTION_HOVER_ENTER:
8909                    setHovered(true);
8910                    break;
8911                case MotionEvent.ACTION_HOVER_EXIT:
8912                    setHovered(false);
8913                    break;
8914            }
8915
8916            // Dispatch the event to onGenericMotionEvent before returning true.
8917            // This is to provide compatibility with existing applications that
8918            // handled HOVER_MOVE events in onGenericMotionEvent and that would
8919            // break because of the new default handling for hoverable views
8920            // in onHoverEvent.
8921            // Note that onGenericMotionEvent will be called by default when
8922            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
8923            dispatchGenericMotionEventInternal(event);
8924            // The event was already handled by calling setHovered(), so always
8925            // return true.
8926            return true;
8927        }
8928
8929        return false;
8930    }
8931
8932    /**
8933     * Returns true if the view should handle {@link #onHoverEvent}
8934     * by calling {@link #setHovered} to change its hovered state.
8935     *
8936     * @return True if the view is hoverable.
8937     */
8938    private boolean isHoverable() {
8939        final int viewFlags = mViewFlags;
8940        if ((viewFlags & ENABLED_MASK) == DISABLED) {
8941            return false;
8942        }
8943
8944        return (viewFlags & CLICKABLE) == CLICKABLE
8945                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
8946    }
8947
8948    /**
8949     * Returns true if the view is currently hovered.
8950     *
8951     * @return True if the view is currently hovered.
8952     *
8953     * @see #setHovered
8954     * @see #onHoverChanged
8955     */
8956    @ViewDebug.ExportedProperty
8957    public boolean isHovered() {
8958        return (mPrivateFlags & PFLAG_HOVERED) != 0;
8959    }
8960
8961    /**
8962     * Sets whether the view is currently hovered.
8963     * <p>
8964     * Calling this method also changes the drawable state of the view.  This
8965     * enables the view to react to hover by using different drawable resources
8966     * to change its appearance.
8967     * </p><p>
8968     * The {@link #onHoverChanged} method is called when the hovered state changes.
8969     * </p>
8970     *
8971     * @param hovered True if the view is hovered.
8972     *
8973     * @see #isHovered
8974     * @see #onHoverChanged
8975     */
8976    public void setHovered(boolean hovered) {
8977        if (hovered) {
8978            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
8979                mPrivateFlags |= PFLAG_HOVERED;
8980                refreshDrawableState();
8981                onHoverChanged(true);
8982            }
8983        } else {
8984            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
8985                mPrivateFlags &= ~PFLAG_HOVERED;
8986                refreshDrawableState();
8987                onHoverChanged(false);
8988            }
8989        }
8990    }
8991
8992    /**
8993     * Implement this method to handle hover state changes.
8994     * <p>
8995     * This method is called whenever the hover state changes as a result of a
8996     * call to {@link #setHovered}.
8997     * </p>
8998     *
8999     * @param hovered The current hover state, as returned by {@link #isHovered}.
9000     *
9001     * @see #isHovered
9002     * @see #setHovered
9003     */
9004    public void onHoverChanged(boolean hovered) {
9005    }
9006
9007    /**
9008     * Implement this method to handle touch screen motion events.
9009     * <p>
9010     * If this method is used to detect click actions, it is recommended that
9011     * the actions be performed by implementing and calling
9012     * {@link #performClick()}. This will ensure consistent system behavior,
9013     * including:
9014     * <ul>
9015     * <li>obeying click sound preferences
9016     * <li>dispatching OnClickListener calls
9017     * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when
9018     * accessibility features are enabled
9019     * </ul>
9020     *
9021     * @param event The motion event.
9022     * @return True if the event was handled, false otherwise.
9023     */
9024    public boolean onTouchEvent(MotionEvent event) {
9025        final int viewFlags = mViewFlags;
9026
9027        if ((viewFlags & ENABLED_MASK) == DISABLED) {
9028            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
9029                setPressed(false);
9030            }
9031            // A disabled view that is clickable still consumes the touch
9032            // events, it just doesn't respond to them.
9033            return (((viewFlags & CLICKABLE) == CLICKABLE ||
9034                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
9035        }
9036
9037        if (mTouchDelegate != null) {
9038            if (mTouchDelegate.onTouchEvent(event)) {
9039                return true;
9040            }
9041        }
9042
9043        if (((viewFlags & CLICKABLE) == CLICKABLE ||
9044                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
9045            switch (event.getAction()) {
9046                case MotionEvent.ACTION_UP:
9047                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
9048                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
9049                        // take focus if we don't have it already and we should in
9050                        // touch mode.
9051                        boolean focusTaken = false;
9052                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
9053                            focusTaken = requestFocus();
9054                        }
9055
9056                        if (prepressed) {
9057                            // The button is being released before we actually
9058                            // showed it as pressed.  Make it show the pressed
9059                            // state now (before scheduling the click) to ensure
9060                            // the user sees it.
9061                            setPressed(true);
9062                       }
9063
9064                        if (!mHasPerformedLongPress) {
9065                            // This is a tap, so remove the longpress check
9066                            removeLongPressCallback();
9067
9068                            // Only perform take click actions if we were in the pressed state
9069                            if (!focusTaken) {
9070                                // Use a Runnable and post this rather than calling
9071                                // performClick directly. This lets other visual state
9072                                // of the view update before click actions start.
9073                                if (mPerformClick == null) {
9074                                    mPerformClick = new PerformClick();
9075                                }
9076                                if (!post(mPerformClick)) {
9077                                    performClick();
9078                                }
9079                            }
9080                        }
9081
9082                        if (mUnsetPressedState == null) {
9083                            mUnsetPressedState = new UnsetPressedState();
9084                        }
9085
9086                        if (prepressed) {
9087                            postDelayed(mUnsetPressedState,
9088                                    ViewConfiguration.getPressedStateDuration());
9089                        } else if (!post(mUnsetPressedState)) {
9090                            // If the post failed, unpress right now
9091                            mUnsetPressedState.run();
9092                        }
9093                        removeTapCallback();
9094                    }
9095                    break;
9096
9097                case MotionEvent.ACTION_DOWN:
9098                    mHasPerformedLongPress = false;
9099
9100                    if (performButtonActionOnTouchDown(event)) {
9101                        break;
9102                    }
9103
9104                    // Walk up the hierarchy to determine if we're inside a scrolling container.
9105                    boolean isInScrollingContainer = isInScrollingContainer();
9106
9107                    // For views inside a scrolling container, delay the pressed feedback for
9108                    // a short period in case this is a scroll.
9109                    if (isInScrollingContainer) {
9110                        mPrivateFlags |= PFLAG_PREPRESSED;
9111                        if (mPendingCheckForTap == null) {
9112                            mPendingCheckForTap = new CheckForTap();
9113                        }
9114                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
9115                    } else {
9116                        // Not inside a scrolling container, so show the feedback right away
9117                        setPressed(true);
9118                        checkForLongClick(0);
9119                    }
9120                    break;
9121
9122                case MotionEvent.ACTION_CANCEL:
9123                    setPressed(false);
9124                    removeTapCallback();
9125                    removeLongPressCallback();
9126                    break;
9127
9128                case MotionEvent.ACTION_MOVE:
9129                    final int x = (int) event.getX();
9130                    final int y = (int) event.getY();
9131
9132                    // Be lenient about moving outside of buttons
9133                    if (!pointInView(x, y, mTouchSlop)) {
9134                        // Outside button
9135                        removeTapCallback();
9136                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
9137                            // Remove any future long press/tap checks
9138                            removeLongPressCallback();
9139
9140                            setPressed(false);
9141                        }
9142                    }
9143                    break;
9144            }
9145
9146            if (mBackground != null && mBackground.supportsHotspots()) {
9147                manageTouchHotspot(event);
9148            }
9149
9150            return true;
9151        }
9152
9153        return false;
9154    }
9155
9156    private void manageTouchHotspot(MotionEvent event) {
9157        switch (event.getAction()) {
9158            case MotionEvent.ACTION_DOWN:
9159            case MotionEvent.ACTION_POINTER_DOWN: {
9160                final int index = event.getActionIndex();
9161                setPointerHotspot(event, index);
9162            } break;
9163            case MotionEvent.ACTION_MOVE: {
9164                final int count = event.getPointerCount();
9165                for (int index = 0; index < count; index++) {
9166                    setPointerHotspot(event, index);
9167                }
9168            } break;
9169            case MotionEvent.ACTION_POINTER_UP: {
9170                final int actionIndex = event.getActionIndex();
9171                final int pointerId = event.getPointerId(actionIndex);
9172                mBackground.removeHotspot(pointerId);
9173            } break;
9174            case MotionEvent.ACTION_UP:
9175            case MotionEvent.ACTION_CANCEL:
9176                mBackground.clearHotspots();
9177                break;
9178        }
9179    }
9180
9181    private void setPointerHotspot(MotionEvent event, int index) {
9182        final int id = event.getPointerId(index);
9183        final float x = event.getX(index);
9184        final float y = event.getY(index);
9185        mBackground.setHotspot(id, x, y);
9186    }
9187
9188    /**
9189     * @hide
9190     */
9191    public boolean isInScrollingContainer() {
9192        ViewParent p = getParent();
9193        while (p != null && p instanceof ViewGroup) {
9194            if (((ViewGroup) p).shouldDelayChildPressedState()) {
9195                return true;
9196            }
9197            p = p.getParent();
9198        }
9199        return false;
9200    }
9201
9202    /**
9203     * Remove the longpress detection timer.
9204     */
9205    private void removeLongPressCallback() {
9206        if (mPendingCheckForLongPress != null) {
9207          removeCallbacks(mPendingCheckForLongPress);
9208        }
9209    }
9210
9211    /**
9212     * Remove the pending click action
9213     */
9214    private void removePerformClickCallback() {
9215        if (mPerformClick != null) {
9216            removeCallbacks(mPerformClick);
9217        }
9218    }
9219
9220    /**
9221     * Remove the prepress detection timer.
9222     */
9223    private void removeUnsetPressCallback() {
9224        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
9225            setPressed(false);
9226            removeCallbacks(mUnsetPressedState);
9227        }
9228    }
9229
9230    /**
9231     * Remove the tap detection timer.
9232     */
9233    private void removeTapCallback() {
9234        if (mPendingCheckForTap != null) {
9235            mPrivateFlags &= ~PFLAG_PREPRESSED;
9236            removeCallbacks(mPendingCheckForTap);
9237        }
9238    }
9239
9240    /**
9241     * Cancels a pending long press.  Your subclass can use this if you
9242     * want the context menu to come up if the user presses and holds
9243     * at the same place, but you don't want it to come up if they press
9244     * and then move around enough to cause scrolling.
9245     */
9246    public void cancelLongPress() {
9247        removeLongPressCallback();
9248
9249        /*
9250         * The prepressed state handled by the tap callback is a display
9251         * construct, but the tap callback will post a long press callback
9252         * less its own timeout. Remove it here.
9253         */
9254        removeTapCallback();
9255    }
9256
9257    /**
9258     * Remove the pending callback for sending a
9259     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
9260     */
9261    private void removeSendViewScrolledAccessibilityEventCallback() {
9262        if (mSendViewScrolledAccessibilityEvent != null) {
9263            removeCallbacks(mSendViewScrolledAccessibilityEvent);
9264            mSendViewScrolledAccessibilityEvent.mIsPending = false;
9265        }
9266    }
9267
9268    /**
9269     * Sets the TouchDelegate for this View.
9270     */
9271    public void setTouchDelegate(TouchDelegate delegate) {
9272        mTouchDelegate = delegate;
9273    }
9274
9275    /**
9276     * Gets the TouchDelegate for this View.
9277     */
9278    public TouchDelegate getTouchDelegate() {
9279        return mTouchDelegate;
9280    }
9281
9282    /**
9283     * Set flags controlling behavior of this view.
9284     *
9285     * @param flags Constant indicating the value which should be set
9286     * @param mask Constant indicating the bit range that should be changed
9287     */
9288    void setFlags(int flags, int mask) {
9289        final boolean accessibilityEnabled =
9290                AccessibilityManager.getInstance(mContext).isEnabled();
9291        final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility();
9292
9293        int old = mViewFlags;
9294        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
9295
9296        int changed = mViewFlags ^ old;
9297        if (changed == 0) {
9298            return;
9299        }
9300        int privateFlags = mPrivateFlags;
9301
9302        /* Check if the FOCUSABLE bit has changed */
9303        if (((changed & FOCUSABLE_MASK) != 0) &&
9304                ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) {
9305            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
9306                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
9307                /* Give up focus if we are no longer focusable */
9308                clearFocus();
9309            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
9310                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
9311                /*
9312                 * Tell the view system that we are now available to take focus
9313                 * if no one else already has it.
9314                 */
9315                if (mParent != null) mParent.focusableViewAvailable(this);
9316            }
9317        }
9318
9319        final int newVisibility = flags & VISIBILITY_MASK;
9320        if (newVisibility == VISIBLE) {
9321            if ((changed & VISIBILITY_MASK) != 0) {
9322                /*
9323                 * If this view is becoming visible, invalidate it in case it changed while
9324                 * it was not visible. Marking it drawn ensures that the invalidation will
9325                 * go through.
9326                 */
9327                mPrivateFlags |= PFLAG_DRAWN;
9328                invalidate(true);
9329
9330                needGlobalAttributesUpdate(true);
9331
9332                // a view becoming visible is worth notifying the parent
9333                // about in case nothing has focus.  even if this specific view
9334                // isn't focusable, it may contain something that is, so let
9335                // the root view try to give this focus if nothing else does.
9336                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
9337                    mParent.focusableViewAvailable(this);
9338                }
9339            }
9340        }
9341
9342        /* Check if the GONE bit has changed */
9343        if ((changed & GONE) != 0) {
9344            needGlobalAttributesUpdate(false);
9345            requestLayout();
9346
9347            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
9348                if (hasFocus()) clearFocus();
9349                clearAccessibilityFocus();
9350                destroyDrawingCache();
9351                if (mParent instanceof View) {
9352                    // GONE views noop invalidation, so invalidate the parent
9353                    ((View) mParent).invalidate(true);
9354                }
9355                // Mark the view drawn to ensure that it gets invalidated properly the next
9356                // time it is visible and gets invalidated
9357                mPrivateFlags |= PFLAG_DRAWN;
9358            }
9359            if (mAttachInfo != null) {
9360                mAttachInfo.mViewVisibilityChanged = true;
9361            }
9362        }
9363
9364        /* Check if the VISIBLE bit has changed */
9365        if ((changed & INVISIBLE) != 0) {
9366            needGlobalAttributesUpdate(false);
9367            /*
9368             * If this view is becoming invisible, set the DRAWN flag so that
9369             * the next invalidate() will not be skipped.
9370             */
9371            mPrivateFlags |= PFLAG_DRAWN;
9372
9373            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) {
9374                // root view becoming invisible shouldn't clear focus and accessibility focus
9375                if (getRootView() != this) {
9376                    if (hasFocus()) clearFocus();
9377                    clearAccessibilityFocus();
9378                }
9379            }
9380            if (mAttachInfo != null) {
9381                mAttachInfo.mViewVisibilityChanged = true;
9382            }
9383        }
9384
9385        if ((changed & VISIBILITY_MASK) != 0) {
9386            // If the view is invisible, cleanup its display list to free up resources
9387            if (newVisibility != VISIBLE && mAttachInfo != null) {
9388                cleanupDraw();
9389            }
9390
9391            if (mParent instanceof ViewGroup) {
9392                ((ViewGroup) mParent).onChildVisibilityChanged(this,
9393                        (changed & VISIBILITY_MASK), newVisibility);
9394                ((View) mParent).invalidate(true);
9395            } else if (mParent != null) {
9396                mParent.invalidateChild(this, null);
9397            }
9398            dispatchVisibilityChanged(this, newVisibility);
9399        }
9400
9401        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
9402            destroyDrawingCache();
9403        }
9404
9405        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
9406            destroyDrawingCache();
9407            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
9408            invalidateParentCaches();
9409        }
9410
9411        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
9412            destroyDrawingCache();
9413            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
9414        }
9415
9416        if ((changed & DRAW_MASK) != 0) {
9417            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
9418                if (mBackground != null) {
9419                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
9420                    mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
9421                } else {
9422                    mPrivateFlags |= PFLAG_SKIP_DRAW;
9423                }
9424            } else {
9425                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
9426            }
9427            requestLayout();
9428            invalidate(true);
9429        }
9430
9431        if ((changed & KEEP_SCREEN_ON) != 0) {
9432            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
9433                mParent.recomputeViewAttributes(this);
9434            }
9435        }
9436
9437        if (accessibilityEnabled) {
9438            if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0
9439                    || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0) {
9440                if (oldIncludeForAccessibility != includeForAccessibility()) {
9441                    notifySubtreeAccessibilityStateChangedIfNeeded();
9442                } else {
9443                    notifyViewAccessibilityStateChangedIfNeeded(
9444                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9445                }
9446            } else if ((changed & ENABLED_MASK) != 0) {
9447                notifyViewAccessibilityStateChangedIfNeeded(
9448                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9449            }
9450        }
9451    }
9452
9453    /**
9454     * Change the view's z order in the tree, so it's on top of other sibling
9455     * views. This ordering change may affect layout, if the parent container
9456     * uses an order-dependent layout scheme (e.g., LinearLayout). Prior
9457     * to {@link android.os.Build.VERSION_CODES#KITKAT} this
9458     * method should be followed by calls to {@link #requestLayout()} and
9459     * {@link View#invalidate()} on the view's parent to force the parent to redraw
9460     * with the new child ordering.
9461     *
9462     * @see ViewGroup#bringChildToFront(View)
9463     */
9464    public void bringToFront() {
9465        if (mParent != null) {
9466            mParent.bringChildToFront(this);
9467        }
9468    }
9469
9470    /**
9471     * This is called in response to an internal scroll in this view (i.e., the
9472     * view scrolled its own contents). This is typically as a result of
9473     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
9474     * called.
9475     *
9476     * @param l Current horizontal scroll origin.
9477     * @param t Current vertical scroll origin.
9478     * @param oldl Previous horizontal scroll origin.
9479     * @param oldt Previous vertical scroll origin.
9480     */
9481    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
9482        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
9483            postSendViewScrolledAccessibilityEventCallback();
9484        }
9485
9486        mBackgroundSizeChanged = true;
9487
9488        final AttachInfo ai = mAttachInfo;
9489        if (ai != null) {
9490            ai.mViewScrollChanged = true;
9491        }
9492    }
9493
9494    /**
9495     * Interface definition for a callback to be invoked when the layout bounds of a view
9496     * changes due to layout processing.
9497     */
9498    public interface OnLayoutChangeListener {
9499        /**
9500         * Called when the layout bounds of a view changes due to layout processing.
9501         *
9502         * @param v The view whose bounds have changed.
9503         * @param left The new value of the view's left property.
9504         * @param top The new value of the view's top property.
9505         * @param right The new value of the view's right property.
9506         * @param bottom The new value of the view's bottom property.
9507         * @param oldLeft The previous value of the view's left property.
9508         * @param oldTop The previous value of the view's top property.
9509         * @param oldRight The previous value of the view's right property.
9510         * @param oldBottom The previous value of the view's bottom property.
9511         */
9512        void onLayoutChange(View v, int left, int top, int right, int bottom,
9513            int oldLeft, int oldTop, int oldRight, int oldBottom);
9514    }
9515
9516    /**
9517     * This is called during layout when the size of this view has changed. If
9518     * you were just added to the view hierarchy, you're called with the old
9519     * values of 0.
9520     *
9521     * @param w Current width of this view.
9522     * @param h Current height of this view.
9523     * @param oldw Old width of this view.
9524     * @param oldh Old height of this view.
9525     */
9526    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
9527    }
9528
9529    /**
9530     * Called by draw to draw the child views. This may be overridden
9531     * by derived classes to gain control just before its children are drawn
9532     * (but after its own view has been drawn).
9533     * @param canvas the canvas on which to draw the view
9534     */
9535    protected void dispatchDraw(Canvas canvas) {
9536
9537    }
9538
9539    /**
9540     * Gets the parent of this view. Note that the parent is a
9541     * ViewParent and not necessarily a View.
9542     *
9543     * @return Parent of this view.
9544     */
9545    public final ViewParent getParent() {
9546        return mParent;
9547    }
9548
9549    /**
9550     * Set the horizontal scrolled position of your view. This will cause a call to
9551     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9552     * invalidated.
9553     * @param value the x position to scroll to
9554     */
9555    public void setScrollX(int value) {
9556        scrollTo(value, mScrollY);
9557    }
9558
9559    /**
9560     * Set the vertical scrolled position of your view. This will cause a call to
9561     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9562     * invalidated.
9563     * @param value the y position to scroll to
9564     */
9565    public void setScrollY(int value) {
9566        scrollTo(mScrollX, value);
9567    }
9568
9569    /**
9570     * Return the scrolled left position of this view. This is the left edge of
9571     * the displayed part of your view. You do not need to draw any pixels
9572     * farther left, since those are outside of the frame of your view on
9573     * screen.
9574     *
9575     * @return The left edge of the displayed part of your view, in pixels.
9576     */
9577    public final int getScrollX() {
9578        return mScrollX;
9579    }
9580
9581    /**
9582     * Return the scrolled top position of this view. This is the top edge of
9583     * the displayed part of your view. You do not need to draw any pixels above
9584     * it, since those are outside of the frame of your view on screen.
9585     *
9586     * @return The top edge of the displayed part of your view, in pixels.
9587     */
9588    public final int getScrollY() {
9589        return mScrollY;
9590    }
9591
9592    /**
9593     * Return the width of the your view.
9594     *
9595     * @return The width of your view, in pixels.
9596     */
9597    @ViewDebug.ExportedProperty(category = "layout")
9598    public final int getWidth() {
9599        return mRight - mLeft;
9600    }
9601
9602    /**
9603     * Return the height of your view.
9604     *
9605     * @return The height of your view, in pixels.
9606     */
9607    @ViewDebug.ExportedProperty(category = "layout")
9608    public final int getHeight() {
9609        return mBottom - mTop;
9610    }
9611
9612    /**
9613     * Return the visible drawing bounds of your view. Fills in the output
9614     * rectangle with the values from getScrollX(), getScrollY(),
9615     * getWidth(), and getHeight(). These bounds do not account for any
9616     * transformation properties currently set on the view, such as
9617     * {@link #setScaleX(float)} or {@link #setRotation(float)}.
9618     *
9619     * @param outRect The (scrolled) drawing bounds of the view.
9620     */
9621    public void getDrawingRect(Rect outRect) {
9622        outRect.left = mScrollX;
9623        outRect.top = mScrollY;
9624        outRect.right = mScrollX + (mRight - mLeft);
9625        outRect.bottom = mScrollY + (mBottom - mTop);
9626    }
9627
9628    /**
9629     * Like {@link #getMeasuredWidthAndState()}, but only returns the
9630     * raw width component (that is the result is masked by
9631     * {@link #MEASURED_SIZE_MASK}).
9632     *
9633     * @return The raw measured width of this view.
9634     */
9635    public final int getMeasuredWidth() {
9636        return mMeasuredWidth & MEASURED_SIZE_MASK;
9637    }
9638
9639    /**
9640     * Return the full width measurement information for this view as computed
9641     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
9642     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
9643     * This should be used during measurement and layout calculations only. Use
9644     * {@link #getWidth()} to see how wide a view is after layout.
9645     *
9646     * @return The measured width of this view as a bit mask.
9647     */
9648    public final int getMeasuredWidthAndState() {
9649        return mMeasuredWidth;
9650    }
9651
9652    /**
9653     * Like {@link #getMeasuredHeightAndState()}, but only returns the
9654     * raw width component (that is the result is masked by
9655     * {@link #MEASURED_SIZE_MASK}).
9656     *
9657     * @return The raw measured height of this view.
9658     */
9659    public final int getMeasuredHeight() {
9660        return mMeasuredHeight & MEASURED_SIZE_MASK;
9661    }
9662
9663    /**
9664     * Return the full height measurement information for this view as computed
9665     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
9666     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
9667     * This should be used during measurement and layout calculations only. Use
9668     * {@link #getHeight()} to see how wide a view is after layout.
9669     *
9670     * @return The measured width of this view as a bit mask.
9671     */
9672    public final int getMeasuredHeightAndState() {
9673        return mMeasuredHeight;
9674    }
9675
9676    /**
9677     * Return only the state bits of {@link #getMeasuredWidthAndState()}
9678     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
9679     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
9680     * and the height component is at the shifted bits
9681     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
9682     */
9683    public final int getMeasuredState() {
9684        return (mMeasuredWidth&MEASURED_STATE_MASK)
9685                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
9686                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
9687    }
9688
9689    /**
9690     * The transform matrix of this view, which is calculated based on the current
9691     * roation, scale, and pivot properties.
9692     *
9693     * @see #getRotation()
9694     * @see #getScaleX()
9695     * @see #getScaleY()
9696     * @see #getPivotX()
9697     * @see #getPivotY()
9698     * @return The current transform matrix for the view
9699     */
9700    public Matrix getMatrix() {
9701        if (mTransformationInfo != null) {
9702            updateMatrix();
9703            return mTransformationInfo.mMatrix;
9704        }
9705        return Matrix.IDENTITY_MATRIX;
9706    }
9707
9708    /**
9709     * Utility function to determine if the value is far enough away from zero to be
9710     * considered non-zero.
9711     * @param value A floating point value to check for zero-ness
9712     * @return whether the passed-in value is far enough away from zero to be considered non-zero
9713     */
9714    private static boolean nonzero(float value) {
9715        return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
9716    }
9717
9718    /**
9719     * Returns true if the transform matrix is the identity matrix.
9720     * Recomputes the matrix if necessary.
9721     *
9722     * @return True if the transform matrix is the identity matrix, false otherwise.
9723     */
9724    final boolean hasIdentityMatrix() {
9725        if (mTransformationInfo != null) {
9726            updateMatrix();
9727            return mTransformationInfo.mMatrixIsIdentity;
9728        }
9729        return true;
9730    }
9731
9732    void ensureTransformationInfo() {
9733        if (mTransformationInfo == null) {
9734            mTransformationInfo = new TransformationInfo();
9735        }
9736    }
9737
9738    /**
9739     * Recomputes the transform matrix if necessary.
9740     */
9741    private void updateMatrix() {
9742        final TransformationInfo info = mTransformationInfo;
9743        if (info == null) {
9744            return;
9745        }
9746        if (info.mMatrixDirty) {
9747            // transform-related properties have changed since the last time someone
9748            // asked for the matrix; recalculate it with the current values
9749
9750            // Figure out if we need to update the pivot point
9751            if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9752                if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) {
9753                    info.mPrevWidth = mRight - mLeft;
9754                    info.mPrevHeight = mBottom - mTop;
9755                    info.mPivotX = info.mPrevWidth / 2f;
9756                    info.mPivotY = info.mPrevHeight / 2f;
9757                }
9758            }
9759            info.mMatrix.reset();
9760            if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) {
9761                info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY);
9762                info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY);
9763                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
9764            } else {
9765                if (info.mCamera == null) {
9766                    info.mCamera = new Camera();
9767                    info.matrix3D = new Matrix();
9768                }
9769                info.mCamera.save();
9770                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
9771                info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation);
9772                info.mCamera.getMatrix(info.matrix3D);
9773                info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY);
9774                info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX,
9775                        info.mPivotY + info.mTranslationY);
9776                info.mMatrix.postConcat(info.matrix3D);
9777                info.mCamera.restore();
9778            }
9779            info.mMatrixDirty = false;
9780            info.mMatrixIsIdentity = info.mMatrix.isIdentity();
9781            info.mInverseMatrixDirty = true;
9782        }
9783    }
9784
9785   /**
9786     * Utility method to retrieve the inverse of the current mMatrix property.
9787     * We cache the matrix to avoid recalculating it when transform properties
9788     * have not changed.
9789     *
9790     * @return The inverse of the current matrix of this view.
9791     */
9792    final Matrix getInverseMatrix() {
9793        final TransformationInfo info = mTransformationInfo;
9794        if (info != null) {
9795            updateMatrix();
9796            if (info.mInverseMatrixDirty) {
9797                if (info.mInverseMatrix == null) {
9798                    info.mInverseMatrix = new Matrix();
9799                }
9800                info.mMatrix.invert(info.mInverseMatrix);
9801                info.mInverseMatrixDirty = false;
9802            }
9803            return info.mInverseMatrix;
9804        }
9805        return Matrix.IDENTITY_MATRIX;
9806    }
9807
9808    /**
9809     * Gets the distance along the Z axis from the camera to this view.
9810     *
9811     * @see #setCameraDistance(float)
9812     *
9813     * @return The distance along the Z axis.
9814     */
9815    public float getCameraDistance() {
9816        ensureTransformationInfo();
9817        final float dpi = mResources.getDisplayMetrics().densityDpi;
9818        final TransformationInfo info = mTransformationInfo;
9819        if (info.mCamera == null) {
9820            info.mCamera = new Camera();
9821            info.matrix3D = new Matrix();
9822        }
9823        return -(info.mCamera.getLocationZ() * dpi);
9824    }
9825
9826    /**
9827     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
9828     * views are drawn) from the camera to this view. The camera's distance
9829     * affects 3D transformations, for instance rotations around the X and Y
9830     * axis. If the rotationX or rotationY properties are changed and this view is
9831     * large (more than half the size of the screen), it is recommended to always
9832     * use a camera distance that's greater than the height (X axis rotation) or
9833     * the width (Y axis rotation) of this view.</p>
9834     *
9835     * <p>The distance of the camera from the view plane can have an affect on the
9836     * perspective distortion of the view when it is rotated around the x or y axis.
9837     * For example, a large distance will result in a large viewing angle, and there
9838     * will not be much perspective distortion of the view as it rotates. A short
9839     * distance may cause much more perspective distortion upon rotation, and can
9840     * also result in some drawing artifacts if the rotated view ends up partially
9841     * behind the camera (which is why the recommendation is to use a distance at
9842     * least as far as the size of the view, if the view is to be rotated.)</p>
9843     *
9844     * <p>The distance is expressed in "depth pixels." The default distance depends
9845     * on the screen density. For instance, on a medium density display, the
9846     * default distance is 1280. On a high density display, the default distance
9847     * is 1920.</p>
9848     *
9849     * <p>If you want to specify a distance that leads to visually consistent
9850     * results across various densities, use the following formula:</p>
9851     * <pre>
9852     * float scale = context.getResources().getDisplayMetrics().density;
9853     * view.setCameraDistance(distance * scale);
9854     * </pre>
9855     *
9856     * <p>The density scale factor of a high density display is 1.5,
9857     * and 1920 = 1280 * 1.5.</p>
9858     *
9859     * @param distance The distance in "depth pixels", if negative the opposite
9860     *        value is used
9861     *
9862     * @see #setRotationX(float)
9863     * @see #setRotationY(float)
9864     */
9865    public void setCameraDistance(float distance) {
9866        invalidateViewProperty(true, false);
9867
9868        ensureTransformationInfo();
9869        final float dpi = mResources.getDisplayMetrics().densityDpi;
9870        final TransformationInfo info = mTransformationInfo;
9871        if (info.mCamera == null) {
9872            info.mCamera = new Camera();
9873            info.matrix3D = new Matrix();
9874        }
9875
9876        info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi);
9877        info.mMatrixDirty = true;
9878
9879        invalidateViewProperty(false, false);
9880        if (mDisplayList != null) {
9881            mDisplayList.setCameraDistance(-Math.abs(distance) / dpi);
9882        }
9883        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9884            // View was rejected last time it was drawn by its parent; this may have changed
9885            invalidateParentIfNeeded();
9886        }
9887    }
9888
9889    /**
9890     * The degrees that the view is rotated around the pivot point.
9891     *
9892     * @see #setRotation(float)
9893     * @see #getPivotX()
9894     * @see #getPivotY()
9895     *
9896     * @return The degrees of rotation.
9897     */
9898    @ViewDebug.ExportedProperty(category = "drawing")
9899    public float getRotation() {
9900        return mTransformationInfo != null ? mTransformationInfo.mRotation : 0;
9901    }
9902
9903    /**
9904     * Sets the degrees that the view is rotated around the pivot point. Increasing values
9905     * result in clockwise rotation.
9906     *
9907     * @param rotation The degrees of rotation.
9908     *
9909     * @see #getRotation()
9910     * @see #getPivotX()
9911     * @see #getPivotY()
9912     * @see #setRotationX(float)
9913     * @see #setRotationY(float)
9914     *
9915     * @attr ref android.R.styleable#View_rotation
9916     */
9917    public void setRotation(float rotation) {
9918        ensureTransformationInfo();
9919        final TransformationInfo info = mTransformationInfo;
9920        if (info.mRotation != rotation) {
9921            // Double-invalidation is necessary to capture view's old and new areas
9922            invalidateViewProperty(true, false);
9923            info.mRotation = rotation;
9924            info.mMatrixDirty = true;
9925            invalidateViewProperty(false, true);
9926            if (mDisplayList != null) {
9927                mDisplayList.setRotation(rotation);
9928            }
9929            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9930                // View was rejected last time it was drawn by its parent; this may have changed
9931                invalidateParentIfNeeded();
9932            }
9933        }
9934    }
9935
9936    /**
9937     * The degrees that the view is rotated around the vertical axis through the pivot point.
9938     *
9939     * @see #getPivotX()
9940     * @see #getPivotY()
9941     * @see #setRotationY(float)
9942     *
9943     * @return The degrees of Y rotation.
9944     */
9945    @ViewDebug.ExportedProperty(category = "drawing")
9946    public float getRotationY() {
9947        return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0;
9948    }
9949
9950    /**
9951     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
9952     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
9953     * down the y axis.
9954     *
9955     * When rotating large views, it is recommended to adjust the camera distance
9956     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
9957     *
9958     * @param rotationY The degrees of Y rotation.
9959     *
9960     * @see #getRotationY()
9961     * @see #getPivotX()
9962     * @see #getPivotY()
9963     * @see #setRotation(float)
9964     * @see #setRotationX(float)
9965     * @see #setCameraDistance(float)
9966     *
9967     * @attr ref android.R.styleable#View_rotationY
9968     */
9969    public void setRotationY(float rotationY) {
9970        ensureTransformationInfo();
9971        final TransformationInfo info = mTransformationInfo;
9972        if (info.mRotationY != rotationY) {
9973            invalidateViewProperty(true, false);
9974            info.mRotationY = rotationY;
9975            info.mMatrixDirty = true;
9976            invalidateViewProperty(false, true);
9977            if (mDisplayList != null) {
9978                mDisplayList.setRotationY(rotationY);
9979            }
9980            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9981                // View was rejected last time it was drawn by its parent; this may have changed
9982                invalidateParentIfNeeded();
9983            }
9984        }
9985    }
9986
9987    /**
9988     * The degrees that the view is rotated around the horizontal axis through the pivot point.
9989     *
9990     * @see #getPivotX()
9991     * @see #getPivotY()
9992     * @see #setRotationX(float)
9993     *
9994     * @return The degrees of X rotation.
9995     */
9996    @ViewDebug.ExportedProperty(category = "drawing")
9997    public float getRotationX() {
9998        return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0;
9999    }
10000
10001    /**
10002     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
10003     * Increasing values result in clockwise rotation from the viewpoint of looking down the
10004     * x axis.
10005     *
10006     * When rotating large views, it is recommended to adjust the camera distance
10007     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
10008     *
10009     * @param rotationX The degrees of X rotation.
10010     *
10011     * @see #getRotationX()
10012     * @see #getPivotX()
10013     * @see #getPivotY()
10014     * @see #setRotation(float)
10015     * @see #setRotationY(float)
10016     * @see #setCameraDistance(float)
10017     *
10018     * @attr ref android.R.styleable#View_rotationX
10019     */
10020    public void setRotationX(float rotationX) {
10021        ensureTransformationInfo();
10022        final TransformationInfo info = mTransformationInfo;
10023        if (info.mRotationX != rotationX) {
10024            invalidateViewProperty(true, false);
10025            info.mRotationX = rotationX;
10026            info.mMatrixDirty = true;
10027            invalidateViewProperty(false, true);
10028            if (mDisplayList != null) {
10029                mDisplayList.setRotationX(rotationX);
10030            }
10031            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10032                // View was rejected last time it was drawn by its parent; this may have changed
10033                invalidateParentIfNeeded();
10034            }
10035        }
10036    }
10037
10038    /**
10039     * The amount that the view is scaled in x around the pivot point, as a proportion of
10040     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
10041     *
10042     * <p>By default, this is 1.0f.
10043     *
10044     * @see #getPivotX()
10045     * @see #getPivotY()
10046     * @return The scaling factor.
10047     */
10048    @ViewDebug.ExportedProperty(category = "drawing")
10049    public float getScaleX() {
10050        return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1;
10051    }
10052
10053    /**
10054     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
10055     * the view's unscaled width. A value of 1 means that no scaling is applied.
10056     *
10057     * @param scaleX The scaling factor.
10058     * @see #getPivotX()
10059     * @see #getPivotY()
10060     *
10061     * @attr ref android.R.styleable#View_scaleX
10062     */
10063    public void setScaleX(float scaleX) {
10064        ensureTransformationInfo();
10065        final TransformationInfo info = mTransformationInfo;
10066        if (info.mScaleX != scaleX) {
10067            invalidateViewProperty(true, false);
10068            info.mScaleX = scaleX;
10069            info.mMatrixDirty = true;
10070            invalidateViewProperty(false, true);
10071            if (mDisplayList != null) {
10072                mDisplayList.setScaleX(scaleX);
10073            }
10074            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10075                // View was rejected last time it was drawn by its parent; this may have changed
10076                invalidateParentIfNeeded();
10077            }
10078        }
10079    }
10080
10081    /**
10082     * The amount that the view is scaled in y around the pivot point, as a proportion of
10083     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
10084     *
10085     * <p>By default, this is 1.0f.
10086     *
10087     * @see #getPivotX()
10088     * @see #getPivotY()
10089     * @return The scaling factor.
10090     */
10091    @ViewDebug.ExportedProperty(category = "drawing")
10092    public float getScaleY() {
10093        return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1;
10094    }
10095
10096    /**
10097     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
10098     * the view's unscaled width. A value of 1 means that no scaling is applied.
10099     *
10100     * @param scaleY The scaling factor.
10101     * @see #getPivotX()
10102     * @see #getPivotY()
10103     *
10104     * @attr ref android.R.styleable#View_scaleY
10105     */
10106    public void setScaleY(float scaleY) {
10107        ensureTransformationInfo();
10108        final TransformationInfo info = mTransformationInfo;
10109        if (info.mScaleY != scaleY) {
10110            invalidateViewProperty(true, false);
10111            info.mScaleY = scaleY;
10112            info.mMatrixDirty = true;
10113            invalidateViewProperty(false, true);
10114            if (mDisplayList != null) {
10115                mDisplayList.setScaleY(scaleY);
10116            }
10117            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10118                // View was rejected last time it was drawn by its parent; this may have changed
10119                invalidateParentIfNeeded();
10120            }
10121        }
10122    }
10123
10124    /**
10125     * The x location of the point around which the view is {@link #setRotation(float) rotated}
10126     * and {@link #setScaleX(float) scaled}.
10127     *
10128     * @see #getRotation()
10129     * @see #getScaleX()
10130     * @see #getScaleY()
10131     * @see #getPivotY()
10132     * @return The x location of the pivot point.
10133     *
10134     * @attr ref android.R.styleable#View_transformPivotX
10135     */
10136    @ViewDebug.ExportedProperty(category = "drawing")
10137    public float getPivotX() {
10138        return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0;
10139    }
10140
10141    /**
10142     * Sets the x location of the point around which the view is
10143     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
10144     * By default, the pivot point is centered on the object.
10145     * Setting this property disables this behavior and causes the view to use only the
10146     * explicitly set pivotX and pivotY values.
10147     *
10148     * @param pivotX The x location of the pivot point.
10149     * @see #getRotation()
10150     * @see #getScaleX()
10151     * @see #getScaleY()
10152     * @see #getPivotY()
10153     *
10154     * @attr ref android.R.styleable#View_transformPivotX
10155     */
10156    public void setPivotX(float pivotX) {
10157        ensureTransformationInfo();
10158        final TransformationInfo info = mTransformationInfo;
10159        boolean pivotSet = (mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) ==
10160                PFLAG_PIVOT_EXPLICITLY_SET;
10161        if (info.mPivotX != pivotX || !pivotSet) {
10162            mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET;
10163            invalidateViewProperty(true, false);
10164            info.mPivotX = pivotX;
10165            info.mMatrixDirty = true;
10166            invalidateViewProperty(false, true);
10167            if (mDisplayList != null) {
10168                mDisplayList.setPivotX(pivotX);
10169            }
10170            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10171                // View was rejected last time it was drawn by its parent; this may have changed
10172                invalidateParentIfNeeded();
10173            }
10174        }
10175    }
10176
10177    /**
10178     * The y location of the point around which the view is {@link #setRotation(float) rotated}
10179     * and {@link #setScaleY(float) scaled}.
10180     *
10181     * @see #getRotation()
10182     * @see #getScaleX()
10183     * @see #getScaleY()
10184     * @see #getPivotY()
10185     * @return The y location of the pivot point.
10186     *
10187     * @attr ref android.R.styleable#View_transformPivotY
10188     */
10189    @ViewDebug.ExportedProperty(category = "drawing")
10190    public float getPivotY() {
10191        return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0;
10192    }
10193
10194    /**
10195     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
10196     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
10197     * Setting this property disables this behavior and causes the view to use only the
10198     * explicitly set pivotX and pivotY values.
10199     *
10200     * @param pivotY The y location of the pivot point.
10201     * @see #getRotation()
10202     * @see #getScaleX()
10203     * @see #getScaleY()
10204     * @see #getPivotY()
10205     *
10206     * @attr ref android.R.styleable#View_transformPivotY
10207     */
10208    public void setPivotY(float pivotY) {
10209        ensureTransformationInfo();
10210        final TransformationInfo info = mTransformationInfo;
10211        boolean pivotSet = (mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) ==
10212                PFLAG_PIVOT_EXPLICITLY_SET;
10213        if (info.mPivotY != pivotY || !pivotSet) {
10214            mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET;
10215            invalidateViewProperty(true, false);
10216            info.mPivotY = pivotY;
10217            info.mMatrixDirty = true;
10218            invalidateViewProperty(false, true);
10219            if (mDisplayList != null) {
10220                mDisplayList.setPivotY(pivotY);
10221            }
10222            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10223                // View was rejected last time it was drawn by its parent; this may have changed
10224                invalidateParentIfNeeded();
10225            }
10226        }
10227    }
10228
10229    /**
10230     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
10231     * completely transparent and 1 means the view is completely opaque.
10232     *
10233     * <p>By default this is 1.0f.
10234     * @return The opacity of the view.
10235     */
10236    @ViewDebug.ExportedProperty(category = "drawing")
10237    public float getAlpha() {
10238        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
10239    }
10240
10241    /**
10242     * Returns whether this View has content which overlaps.
10243     *
10244     * <p>This function, intended to be overridden by specific View types, is an optimization when
10245     * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to
10246     * an offscreen buffer and then composited into place, which can be expensive. If the view has
10247     * no overlapping rendering, the view can draw each primitive with the appropriate alpha value
10248     * directly. An example of overlapping rendering is a TextView with a background image, such as
10249     * a Button. An example of non-overlapping rendering is a TextView with no background, or an
10250     * ImageView with only the foreground image. The default implementation returns true; subclasses
10251     * should override if they have cases which can be optimized.</p>
10252     *
10253     * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas}
10254     * necessitates that a View return true if it uses the methods internally without passing the
10255     * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p>
10256     *
10257     * @return true if the content in this view might overlap, false otherwise.
10258     */
10259    public boolean hasOverlappingRendering() {
10260        return true;
10261    }
10262
10263    /**
10264     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
10265     * completely transparent and 1 means the view is completely opaque.</p>
10266     *
10267     * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant
10268     * performance implications, especially for large views. It is best to use the alpha property
10269     * sparingly and transiently, as in the case of fading animations.</p>
10270     *
10271     * <p>For a view with a frequently changing alpha, such as during a fading animation, it is
10272     * strongly recommended for performance reasons to either override
10273     * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a
10274     * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p>
10275     *
10276     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
10277     * responsible for applying the opacity itself.</p>
10278     *
10279     * <p>Note that if the view is backed by a
10280     * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a
10281     * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than
10282     * 1.0 will supercede the alpha of the layer paint.</p>
10283     *
10284     * @param alpha The opacity of the view.
10285     *
10286     * @see #hasOverlappingRendering()
10287     * @see #setLayerType(int, android.graphics.Paint)
10288     *
10289     * @attr ref android.R.styleable#View_alpha
10290     */
10291    public void setAlpha(float alpha) {
10292        ensureTransformationInfo();
10293        if (mTransformationInfo.mAlpha != alpha) {
10294            mTransformationInfo.mAlpha = alpha;
10295            if (onSetAlpha((int) (alpha * 255))) {
10296                mPrivateFlags |= PFLAG_ALPHA_SET;
10297                // subclass is handling alpha - don't optimize rendering cache invalidation
10298                invalidateParentCaches();
10299                invalidate(true);
10300            } else {
10301                mPrivateFlags &= ~PFLAG_ALPHA_SET;
10302                invalidateViewProperty(true, false);
10303                if (mDisplayList != null) {
10304                    mDisplayList.setAlpha(getFinalAlpha());
10305                }
10306            }
10307        }
10308    }
10309
10310    /**
10311     * Faster version of setAlpha() which performs the same steps except there are
10312     * no calls to invalidate(). The caller of this function should perform proper invalidation
10313     * on the parent and this object. The return value indicates whether the subclass handles
10314     * alpha (the return value for onSetAlpha()).
10315     *
10316     * @param alpha The new value for the alpha property
10317     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
10318     *         the new value for the alpha property is different from the old value
10319     */
10320    boolean setAlphaNoInvalidation(float alpha) {
10321        ensureTransformationInfo();
10322        if (mTransformationInfo.mAlpha != alpha) {
10323            mTransformationInfo.mAlpha = alpha;
10324            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
10325            if (subclassHandlesAlpha) {
10326                mPrivateFlags |= PFLAG_ALPHA_SET;
10327                return true;
10328            } else {
10329                mPrivateFlags &= ~PFLAG_ALPHA_SET;
10330                if (mDisplayList != null) {
10331                    mDisplayList.setAlpha(getFinalAlpha());
10332                }
10333            }
10334        }
10335        return false;
10336    }
10337
10338    /**
10339     * This property is hidden and intended only for use by the Fade transition, which
10340     * animates it to produce a visual translucency that does not side-effect (or get
10341     * affected by) the real alpha property. This value is composited with the other
10342     * alpha value (and the AlphaAnimation value, when that is present) to produce
10343     * a final visual translucency result, which is what is passed into the DisplayList.
10344     *
10345     * @hide
10346     */
10347    public void setTransitionAlpha(float alpha) {
10348        ensureTransformationInfo();
10349        if (mTransformationInfo.mTransitionAlpha != alpha) {
10350            mTransformationInfo.mTransitionAlpha = alpha;
10351            mPrivateFlags &= ~PFLAG_ALPHA_SET;
10352            invalidateViewProperty(true, false);
10353            if (mDisplayList != null) {
10354                mDisplayList.setAlpha(getFinalAlpha());
10355            }
10356        }
10357    }
10358
10359    /**
10360     * Calculates the visual alpha of this view, which is a combination of the actual
10361     * alpha value and the transitionAlpha value (if set).
10362     */
10363    private float getFinalAlpha() {
10364        if (mTransformationInfo != null) {
10365            return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha;
10366        }
10367        return 1;
10368    }
10369
10370    /**
10371     * This property is hidden and intended only for use by the Fade transition, which
10372     * animates it to produce a visual translucency that does not side-effect (or get
10373     * affected by) the real alpha property. This value is composited with the other
10374     * alpha value (and the AlphaAnimation value, when that is present) to produce
10375     * a final visual translucency result, which is what is passed into the DisplayList.
10376     *
10377     * @hide
10378     */
10379    public float getTransitionAlpha() {
10380        return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1;
10381    }
10382
10383    /**
10384     * Top position of this view relative to its parent.
10385     *
10386     * @return The top of this view, in pixels.
10387     */
10388    @ViewDebug.CapturedViewProperty
10389    public final int getTop() {
10390        return mTop;
10391    }
10392
10393    /**
10394     * Sets the top position of this view relative to its parent. This method is meant to be called
10395     * by the layout system and should not generally be called otherwise, because the property
10396     * may be changed at any time by the layout.
10397     *
10398     * @param top The top of this view, in pixels.
10399     */
10400    public final void setTop(int top) {
10401        if (top != mTop) {
10402            updateMatrix();
10403            final boolean matrixIsIdentity = mTransformationInfo == null
10404                    || mTransformationInfo.mMatrixIsIdentity;
10405            if (matrixIsIdentity) {
10406                if (mAttachInfo != null) {
10407                    int minTop;
10408                    int yLoc;
10409                    if (top < mTop) {
10410                        minTop = top;
10411                        yLoc = top - mTop;
10412                    } else {
10413                        minTop = mTop;
10414                        yLoc = 0;
10415                    }
10416                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
10417                }
10418            } else {
10419                // Double-invalidation is necessary to capture view's old and new areas
10420                invalidate(true);
10421            }
10422
10423            int width = mRight - mLeft;
10424            int oldHeight = mBottom - mTop;
10425
10426            mTop = top;
10427            if (mDisplayList != null) {
10428                mDisplayList.setTop(mTop);
10429            }
10430
10431            sizeChange(width, mBottom - mTop, width, oldHeight);
10432
10433            if (!matrixIsIdentity) {
10434                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
10435                    // A change in dimension means an auto-centered pivot point changes, too
10436                    mTransformationInfo.mMatrixDirty = true;
10437                }
10438                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10439                invalidate(true);
10440            }
10441            mBackgroundSizeChanged = true;
10442            invalidateParentIfNeeded();
10443            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10444                // View was rejected last time it was drawn by its parent; this may have changed
10445                invalidateParentIfNeeded();
10446            }
10447        }
10448    }
10449
10450    /**
10451     * Bottom position of this view relative to its parent.
10452     *
10453     * @return The bottom of this view, in pixels.
10454     */
10455    @ViewDebug.CapturedViewProperty
10456    public final int getBottom() {
10457        return mBottom;
10458    }
10459
10460    /**
10461     * True if this view has changed since the last time being drawn.
10462     *
10463     * @return The dirty state of this view.
10464     */
10465    public boolean isDirty() {
10466        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
10467    }
10468
10469    /**
10470     * Sets the bottom position of this view relative to its parent. This method is meant to be
10471     * called by the layout system and should not generally be called otherwise, because the
10472     * property may be changed at any time by the layout.
10473     *
10474     * @param bottom The bottom of this view, in pixels.
10475     */
10476    public final void setBottom(int bottom) {
10477        if (bottom != mBottom) {
10478            updateMatrix();
10479            final boolean matrixIsIdentity = mTransformationInfo == null
10480                    || mTransformationInfo.mMatrixIsIdentity;
10481            if (matrixIsIdentity) {
10482                if (mAttachInfo != null) {
10483                    int maxBottom;
10484                    if (bottom < mBottom) {
10485                        maxBottom = mBottom;
10486                    } else {
10487                        maxBottom = bottom;
10488                    }
10489                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
10490                }
10491            } else {
10492                // Double-invalidation is necessary to capture view's old and new areas
10493                invalidate(true);
10494            }
10495
10496            int width = mRight - mLeft;
10497            int oldHeight = mBottom - mTop;
10498
10499            mBottom = bottom;
10500            if (mDisplayList != null) {
10501                mDisplayList.setBottom(mBottom);
10502            }
10503
10504            sizeChange(width, mBottom - mTop, width, oldHeight);
10505
10506            if (!matrixIsIdentity) {
10507                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
10508                    // A change in dimension means an auto-centered pivot point changes, too
10509                    mTransformationInfo.mMatrixDirty = true;
10510                }
10511                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10512                invalidate(true);
10513            }
10514            mBackgroundSizeChanged = true;
10515            invalidateParentIfNeeded();
10516            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10517                // View was rejected last time it was drawn by its parent; this may have changed
10518                invalidateParentIfNeeded();
10519            }
10520        }
10521    }
10522
10523    /**
10524     * Left position of this view relative to its parent.
10525     *
10526     * @return The left edge of this view, in pixels.
10527     */
10528    @ViewDebug.CapturedViewProperty
10529    public final int getLeft() {
10530        return mLeft;
10531    }
10532
10533    /**
10534     * Sets the left position of this view relative to its parent. This method is meant to be called
10535     * by the layout system and should not generally be called otherwise, because the property
10536     * may be changed at any time by the layout.
10537     *
10538     * @param left The bottom of this view, in pixels.
10539     */
10540    public final void setLeft(int left) {
10541        if (left != mLeft) {
10542            updateMatrix();
10543            final boolean matrixIsIdentity = mTransformationInfo == null
10544                    || mTransformationInfo.mMatrixIsIdentity;
10545            if (matrixIsIdentity) {
10546                if (mAttachInfo != null) {
10547                    int minLeft;
10548                    int xLoc;
10549                    if (left < mLeft) {
10550                        minLeft = left;
10551                        xLoc = left - mLeft;
10552                    } else {
10553                        minLeft = mLeft;
10554                        xLoc = 0;
10555                    }
10556                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
10557                }
10558            } else {
10559                // Double-invalidation is necessary to capture view's old and new areas
10560                invalidate(true);
10561            }
10562
10563            int oldWidth = mRight - mLeft;
10564            int height = mBottom - mTop;
10565
10566            mLeft = left;
10567            if (mDisplayList != null) {
10568                mDisplayList.setLeft(left);
10569            }
10570
10571            sizeChange(mRight - mLeft, height, oldWidth, height);
10572
10573            if (!matrixIsIdentity) {
10574                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
10575                    // A change in dimension means an auto-centered pivot point changes, too
10576                    mTransformationInfo.mMatrixDirty = true;
10577                }
10578                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10579                invalidate(true);
10580            }
10581            mBackgroundSizeChanged = true;
10582            invalidateParentIfNeeded();
10583            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10584                // View was rejected last time it was drawn by its parent; this may have changed
10585                invalidateParentIfNeeded();
10586            }
10587        }
10588    }
10589
10590    /**
10591     * Right position of this view relative to its parent.
10592     *
10593     * @return The right edge of this view, in pixels.
10594     */
10595    @ViewDebug.CapturedViewProperty
10596    public final int getRight() {
10597        return mRight;
10598    }
10599
10600    /**
10601     * Sets the right position of this view relative to its parent. This method is meant to be called
10602     * by the layout system and should not generally be called otherwise, because the property
10603     * may be changed at any time by the layout.
10604     *
10605     * @param right The bottom of this view, in pixels.
10606     */
10607    public final void setRight(int right) {
10608        if (right != mRight) {
10609            updateMatrix();
10610            final boolean matrixIsIdentity = mTransformationInfo == null
10611                    || mTransformationInfo.mMatrixIsIdentity;
10612            if (matrixIsIdentity) {
10613                if (mAttachInfo != null) {
10614                    int maxRight;
10615                    if (right < mRight) {
10616                        maxRight = mRight;
10617                    } else {
10618                        maxRight = right;
10619                    }
10620                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
10621                }
10622            } else {
10623                // Double-invalidation is necessary to capture view's old and new areas
10624                invalidate(true);
10625            }
10626
10627            int oldWidth = mRight - mLeft;
10628            int height = mBottom - mTop;
10629
10630            mRight = right;
10631            if (mDisplayList != null) {
10632                mDisplayList.setRight(mRight);
10633            }
10634
10635            sizeChange(mRight - mLeft, height, oldWidth, height);
10636
10637            if (!matrixIsIdentity) {
10638                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
10639                    // A change in dimension means an auto-centered pivot point changes, too
10640                    mTransformationInfo.mMatrixDirty = true;
10641                }
10642                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10643                invalidate(true);
10644            }
10645            mBackgroundSizeChanged = true;
10646            invalidateParentIfNeeded();
10647            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10648                // View was rejected last time it was drawn by its parent; this may have changed
10649                invalidateParentIfNeeded();
10650            }
10651        }
10652    }
10653
10654    /**
10655     * The visual x position of this view, in pixels. This is equivalent to the
10656     * {@link #setTranslationX(float) translationX} property plus the current
10657     * {@link #getLeft() left} property.
10658     *
10659     * @return The visual x position of this view, in pixels.
10660     */
10661    @ViewDebug.ExportedProperty(category = "drawing")
10662    public float getX() {
10663        return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0);
10664    }
10665
10666    /**
10667     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
10668     * {@link #setTranslationX(float) translationX} property to be the difference between
10669     * the x value passed in and the current {@link #getLeft() left} property.
10670     *
10671     * @param x The visual x position of this view, in pixels.
10672     */
10673    public void setX(float x) {
10674        setTranslationX(x - mLeft);
10675    }
10676
10677    /**
10678     * The visual y position of this view, in pixels. This is equivalent to the
10679     * {@link #setTranslationY(float) translationY} property plus the current
10680     * {@link #getTop() top} property.
10681     *
10682     * @return The visual y position of this view, in pixels.
10683     */
10684    @ViewDebug.ExportedProperty(category = "drawing")
10685    public float getY() {
10686        return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0);
10687    }
10688
10689    /**
10690     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
10691     * {@link #setTranslationY(float) translationY} property to be the difference between
10692     * the y value passed in and the current {@link #getTop() top} property.
10693     *
10694     * @param y The visual y position of this view, in pixels.
10695     */
10696    public void setY(float y) {
10697        setTranslationY(y - mTop);
10698    }
10699
10700
10701    /**
10702     * The horizontal location of this view relative to its {@link #getLeft() left} position.
10703     * This position is post-layout, in addition to wherever the object's
10704     * layout placed it.
10705     *
10706     * @return The horizontal position of this view relative to its left position, in pixels.
10707     */
10708    @ViewDebug.ExportedProperty(category = "drawing")
10709    public float getTranslationX() {
10710        return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0;
10711    }
10712
10713    /**
10714     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
10715     * This effectively positions the object post-layout, in addition to wherever the object's
10716     * layout placed it.
10717     *
10718     * @param translationX The horizontal position of this view relative to its left position,
10719     * in pixels.
10720     *
10721     * @attr ref android.R.styleable#View_translationX
10722     */
10723    public void setTranslationX(float translationX) {
10724        ensureTransformationInfo();
10725        final TransformationInfo info = mTransformationInfo;
10726        if (info.mTranslationX != translationX) {
10727            // Double-invalidation is necessary to capture view's old and new areas
10728            invalidateViewProperty(true, false);
10729            info.mTranslationX = translationX;
10730            info.mMatrixDirty = true;
10731            invalidateViewProperty(false, true);
10732            if (mDisplayList != null) {
10733                mDisplayList.setTranslationX(translationX);
10734            }
10735            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10736                // View was rejected last time it was drawn by its parent; this may have changed
10737                invalidateParentIfNeeded();
10738            }
10739        }
10740    }
10741
10742    /**
10743     * The vertical location of this view relative to its {@link #getTop() top} position.
10744     * This position is post-layout, in addition to wherever the object's
10745     * layout placed it.
10746     *
10747     * @return The vertical position of this view relative to its top position,
10748     * in pixels.
10749     */
10750    @ViewDebug.ExportedProperty(category = "drawing")
10751    public float getTranslationY() {
10752        return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0;
10753    }
10754
10755    /**
10756     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
10757     * This effectively positions the object post-layout, in addition to wherever the object's
10758     * layout placed it.
10759     *
10760     * @param translationY The vertical position of this view relative to its top position,
10761     * in pixels.
10762     *
10763     * @attr ref android.R.styleable#View_translationY
10764     */
10765    public void setTranslationY(float translationY) {
10766        ensureTransformationInfo();
10767        final TransformationInfo info = mTransformationInfo;
10768        if (info.mTranslationY != translationY) {
10769            invalidateViewProperty(true, false);
10770            info.mTranslationY = translationY;
10771            info.mMatrixDirty = true;
10772            invalidateViewProperty(false, true);
10773            if (mDisplayList != null) {
10774                mDisplayList.setTranslationY(translationY);
10775            }
10776            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10777                // View was rejected last time it was drawn by its parent; this may have changed
10778                invalidateParentIfNeeded();
10779            }
10780        }
10781    }
10782
10783    /**
10784     * The depth location of this view relative to its parent.
10785     *
10786     * @return The depth of this view relative to its parent.
10787     */
10788    @ViewDebug.ExportedProperty(category = "drawing")
10789    public float getTranslationZ() {
10790        return mTransformationInfo != null ? mTransformationInfo.mTranslationZ : 0;
10791    }
10792
10793    /**
10794     * Sets the depth location of this view relative to its parent.
10795     *
10796     * @attr ref android.R.styleable#View_translationZ
10797     */
10798    public void setTranslationZ(float translationZ) {
10799        ensureTransformationInfo();
10800        final TransformationInfo info = mTransformationInfo;
10801        if (info.mTranslationZ != translationZ) {
10802            invalidateViewProperty(true, false);
10803            info.mTranslationZ = translationZ;
10804            info.mMatrixDirty = true;
10805            invalidateViewProperty(false, true);
10806            if (mDisplayList != null) {
10807                mDisplayList.setTranslationZ(translationZ);
10808            }
10809            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10810                // View was rejected last time it was drawn by its parent; this may have changed
10811                invalidateParentIfNeeded();
10812            }
10813        }
10814    }
10815
10816    /**
10817     * Copies the Outline of the View into the Path parameter.
10818     * <p>
10819     * If the outline is not set, the parameter Path is set to empty.
10820     *
10821     * @param outline Path into which View's outline will be copied. Must be non-null.
10822     *
10823     * @see #setOutline(Path)
10824     * @see #getClipToOutline()
10825     * @see #setClipToOutline(boolean)
10826     */
10827    public final void getOutline(@NonNull Path outline) {
10828        if (outline == null) {
10829            throw new IllegalArgumentException("Path must be non-null");
10830        }
10831        if (mOutline == null) {
10832            outline.reset();
10833        } else {
10834            outline.set(mOutline);
10835        }
10836    }
10837
10838    /**
10839     * Sets the outline of the view, which defines the shape of the shadow it
10840     * casts, and can used for clipping.
10841     * <p>
10842     * If the outline is not set, or {@link Path#isEmpty()}, shadows will be
10843     * cast from the bounds of the View, and clipToOutline will be ignored.
10844     *
10845     * @param outline The new outline of the view. Must be non-null.
10846     *
10847     * @see #getOutline(Path)
10848     * @see #getClipToOutline()
10849     * @see #setClipToOutline(boolean)
10850     */
10851    public void setOutline(@NonNull Path outline) {
10852        if (outline == null) {
10853            throw new IllegalArgumentException("Path must be non-null");
10854        }
10855        // always copy the path since caller may reuse
10856        if (mOutline == null) {
10857            mOutline = new Path(outline);
10858        } else {
10859            mOutline.set(outline);
10860        }
10861
10862        if (mDisplayList != null) {
10863            mDisplayList.setOutline(outline);
10864        }
10865    }
10866
10867    /**
10868     * Returns whether the outline of the View will be used for clipping.
10869     *
10870     * @see #getOutline(Path)
10871     * @see #setOutline(Path)
10872     */
10873    public final boolean getClipToOutline() {
10874        return ((mPrivateFlags3 & PFLAG3_CLIP_TO_OUTLINE) != 0);
10875    }
10876
10877    /**
10878     * Sets whether the outline of the View will be used for clipping.
10879     * <p>
10880     * The current implementation of outline clipping uses Canvas#clipPath(),
10881     * and thus does not support anti-aliasing, and is expensive in terms of
10882     * graphics performance. Therefore, it is strongly recommended that this
10883     * property only be set temporarily, as in an animation. For the same
10884     * reasons, there is no parallel XML attribute for this property.
10885     * <p>
10886     * If the outline of the view is not set or is empty, no clipping will be
10887     * performed.
10888     *
10889     * @see #getOutline(Path)
10890     * @see #setOutline(Path)
10891     */
10892    public void setClipToOutline(boolean clipToOutline) {
10893        // TODO : Add a fast invalidation here.
10894        if (getClipToOutline() != clipToOutline) {
10895            if (clipToOutline) {
10896                mPrivateFlags3 |= PFLAG3_CLIP_TO_OUTLINE;
10897            } else {
10898                mPrivateFlags3 &= ~PFLAG3_CLIP_TO_OUTLINE;
10899            }
10900            if (mDisplayList != null) {
10901                mDisplayList.setClipToOutline(clipToOutline);
10902            }
10903        }
10904    }
10905
10906    /**
10907     * Returns whether the View will cast shadows when its
10908     * {@link #setTranslationZ(float) z translation} is greater than 0, or it is
10909     * rotated in 3D.
10910     *
10911     * @see #setTranslationZ(float)
10912     * @see #setRotationX(float)
10913     * @see #setRotationY(float)
10914     * @see #setCastsShadow(boolean)
10915     * @attr ref android.R.styleable#View_castsShadow
10916     */
10917    public final boolean getCastsShadow() {
10918        return ((mPrivateFlags3 & PFLAG3_CASTS_SHADOW) != 0);
10919    }
10920
10921    /**
10922     * Set to true to enable this View to cast shadows.
10923     * <p>
10924     * If enabled, and the View has a z translation greater than 0, or is
10925     * rotated in 3D, the shadow will be cast onto the current
10926     * {@link ViewGroup#setIsolatedZVolume(boolean) isolated Z volume},
10927     * at the z = 0 plane.
10928     * <p>
10929     * The shape of the shadow being cast is defined by the
10930     * {@link #setOutline(Path) outline} of the view, or the rectangular bounds
10931     * of the view if the outline is not set or is empty.
10932     *
10933     * @see #setTranslationZ(float)
10934     * @see #getCastsShadow()
10935     * @attr ref android.R.styleable#View_castsShadow
10936     */
10937    public void setCastsShadow(boolean castsShadow) {
10938        // TODO : Add a fast invalidation here.
10939        if (getCastsShadow() != castsShadow) {
10940            if (castsShadow) {
10941                mPrivateFlags3 |= PFLAG3_CASTS_SHADOW;
10942            } else {
10943                mPrivateFlags3 &= ~PFLAG3_CASTS_SHADOW;
10944            }
10945            if (mDisplayList != null) {
10946                mDisplayList.setCastsShadow(castsShadow);
10947            }
10948        }
10949    }
10950
10951    /**
10952     * Returns whether the View will be transformed by the global camera.
10953     *
10954     * @see #setUsesGlobalCamera(boolean)
10955     *
10956     * @hide
10957     */
10958    public final boolean getUsesGlobalCamera() {
10959        return ((mPrivateFlags3 & PFLAG3_USES_GLOBAL_CAMERA) != 0);
10960    }
10961
10962    /**
10963     * Sets whether the View should be transformed by the global camera.
10964     * <p>
10965     * If the view has a Z translation or 3D rotation, perspective from the
10966     * global camera will be applied. This enables an app to transform multiple
10967     * views in 3D with coherent perspective projection among them all.
10968     * <p>
10969     * Setting this to true will cause {@link #setCameraDistance() camera distance}
10970     * to be ignored, as the global camera's position will dictate perspective
10971     * transform.
10972     * <p>
10973     * This should not be used in conjunction with {@link android.graphics.Camera}.
10974     *
10975     * @see #getUsesGlobalCamera()
10976     * @see #setTranslationZ(float)
10977     * @see #setRotationX(float)
10978     * @see #setRotationY(float)
10979     *
10980     * @hide
10981     */
10982    public void setUsesGlobalCamera(boolean usesGlobalCamera) {
10983        // TODO : Add a fast invalidation here.
10984        if (getUsesGlobalCamera() != usesGlobalCamera) {
10985            if (usesGlobalCamera) {
10986                mPrivateFlags3 |= PFLAG3_USES_GLOBAL_CAMERA;
10987            } else {
10988                mPrivateFlags3 &= ~PFLAG3_USES_GLOBAL_CAMERA;
10989            }
10990            if (mDisplayList != null) {
10991                mDisplayList.setUsesGlobalCamera(usesGlobalCamera);
10992            }
10993        }
10994    }
10995
10996    /**
10997     * Hit rectangle in parent's coordinates
10998     *
10999     * @param outRect The hit rectangle of the view.
11000     */
11001    public void getHitRect(Rect outRect) {
11002        updateMatrix();
11003        final TransformationInfo info = mTransformationInfo;
11004        if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) {
11005            outRect.set(mLeft, mTop, mRight, mBottom);
11006        } else {
11007            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
11008            tmpRect.set(0, 0, getWidth(), getHeight());
11009            info.mMatrix.mapRect(tmpRect);
11010            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
11011                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
11012        }
11013    }
11014
11015    /**
11016     * Determines whether the given point, in local coordinates is inside the view.
11017     */
11018    /*package*/ final boolean pointInView(float localX, float localY) {
11019        return localX >= 0 && localX < (mRight - mLeft)
11020                && localY >= 0 && localY < (mBottom - mTop);
11021    }
11022
11023    /**
11024     * Utility method to determine whether the given point, in local coordinates,
11025     * is inside the view, where the area of the view is expanded by the slop factor.
11026     * This method is called while processing touch-move events to determine if the event
11027     * is still within the view.
11028     *
11029     * @hide
11030     */
11031    public boolean pointInView(float localX, float localY, float slop) {
11032        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
11033                localY < ((mBottom - mTop) + slop);
11034    }
11035
11036    /**
11037     * When a view has focus and the user navigates away from it, the next view is searched for
11038     * starting from the rectangle filled in by this method.
11039     *
11040     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
11041     * of the view.  However, if your view maintains some idea of internal selection,
11042     * such as a cursor, or a selected row or column, you should override this method and
11043     * fill in a more specific rectangle.
11044     *
11045     * @param r The rectangle to fill in, in this view's coordinates.
11046     */
11047    public void getFocusedRect(Rect r) {
11048        getDrawingRect(r);
11049    }
11050
11051    /**
11052     * If some part of this view is not clipped by any of its parents, then
11053     * return that area in r in global (root) coordinates. To convert r to local
11054     * coordinates (without taking possible View rotations into account), offset
11055     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
11056     * If the view is completely clipped or translated out, return false.
11057     *
11058     * @param r If true is returned, r holds the global coordinates of the
11059     *        visible portion of this view.
11060     * @param globalOffset If true is returned, globalOffset holds the dx,dy
11061     *        between this view and its root. globalOffet may be null.
11062     * @return true if r is non-empty (i.e. part of the view is visible at the
11063     *         root level.
11064     */
11065    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
11066        int width = mRight - mLeft;
11067        int height = mBottom - mTop;
11068        if (width > 0 && height > 0) {
11069            r.set(0, 0, width, height);
11070            if (globalOffset != null) {
11071                globalOffset.set(-mScrollX, -mScrollY);
11072            }
11073            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
11074        }
11075        return false;
11076    }
11077
11078    public final boolean getGlobalVisibleRect(Rect r) {
11079        return getGlobalVisibleRect(r, null);
11080    }
11081
11082    public final boolean getLocalVisibleRect(Rect r) {
11083        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
11084        if (getGlobalVisibleRect(r, offset)) {
11085            r.offset(-offset.x, -offset.y); // make r local
11086            return true;
11087        }
11088        return false;
11089    }
11090
11091    /**
11092     * Offset this view's vertical location by the specified number of pixels.
11093     *
11094     * @param offset the number of pixels to offset the view by
11095     */
11096    public void offsetTopAndBottom(int offset) {
11097        if (offset != 0) {
11098            updateMatrix();
11099            final boolean matrixIsIdentity = mTransformationInfo == null
11100                    || mTransformationInfo.mMatrixIsIdentity;
11101            if (matrixIsIdentity) {
11102                if (mDisplayList != null) {
11103                    invalidateViewProperty(false, false);
11104                } else {
11105                    final ViewParent p = mParent;
11106                    if (p != null && mAttachInfo != null) {
11107                        final Rect r = mAttachInfo.mTmpInvalRect;
11108                        int minTop;
11109                        int maxBottom;
11110                        int yLoc;
11111                        if (offset < 0) {
11112                            minTop = mTop + offset;
11113                            maxBottom = mBottom;
11114                            yLoc = offset;
11115                        } else {
11116                            minTop = mTop;
11117                            maxBottom = mBottom + offset;
11118                            yLoc = 0;
11119                        }
11120                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
11121                        p.invalidateChild(this, r);
11122                    }
11123                }
11124            } else {
11125                invalidateViewProperty(false, false);
11126            }
11127
11128            mTop += offset;
11129            mBottom += offset;
11130            if (mDisplayList != null) {
11131                mDisplayList.offsetTopAndBottom(offset);
11132                invalidateViewProperty(false, false);
11133            } else {
11134                if (!matrixIsIdentity) {
11135                    invalidateViewProperty(false, true);
11136                }
11137                invalidateParentIfNeeded();
11138            }
11139        }
11140    }
11141
11142    /**
11143     * Offset this view's horizontal location by the specified amount of pixels.
11144     *
11145     * @param offset the number of pixels to offset the view by
11146     */
11147    public void offsetLeftAndRight(int offset) {
11148        if (offset != 0) {
11149            updateMatrix();
11150            final boolean matrixIsIdentity = mTransformationInfo == null
11151                    || mTransformationInfo.mMatrixIsIdentity;
11152            if (matrixIsIdentity) {
11153                if (mDisplayList != null) {
11154                    invalidateViewProperty(false, false);
11155                } else {
11156                    final ViewParent p = mParent;
11157                    if (p != null && mAttachInfo != null) {
11158                        final Rect r = mAttachInfo.mTmpInvalRect;
11159                        int minLeft;
11160                        int maxRight;
11161                        if (offset < 0) {
11162                            minLeft = mLeft + offset;
11163                            maxRight = mRight;
11164                        } else {
11165                            minLeft = mLeft;
11166                            maxRight = mRight + offset;
11167                        }
11168                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
11169                        p.invalidateChild(this, r);
11170                    }
11171                }
11172            } else {
11173                invalidateViewProperty(false, false);
11174            }
11175
11176            mLeft += offset;
11177            mRight += offset;
11178            if (mDisplayList != null) {
11179                mDisplayList.offsetLeftAndRight(offset);
11180                invalidateViewProperty(false, false);
11181            } else {
11182                if (!matrixIsIdentity) {
11183                    invalidateViewProperty(false, true);
11184                }
11185                invalidateParentIfNeeded();
11186            }
11187        }
11188    }
11189
11190    /**
11191     * Get the LayoutParams associated with this view. All views should have
11192     * layout parameters. These supply parameters to the <i>parent</i> of this
11193     * view specifying how it should be arranged. There are many subclasses of
11194     * ViewGroup.LayoutParams, and these correspond to the different subclasses
11195     * of ViewGroup that are responsible for arranging their children.
11196     *
11197     * This method may return null if this View is not attached to a parent
11198     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
11199     * was not invoked successfully. When a View is attached to a parent
11200     * ViewGroup, this method must not return null.
11201     *
11202     * @return The LayoutParams associated with this view, or null if no
11203     *         parameters have been set yet
11204     */
11205    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
11206    public ViewGroup.LayoutParams getLayoutParams() {
11207        return mLayoutParams;
11208    }
11209
11210    /**
11211     * Set the layout parameters associated with this view. These supply
11212     * parameters to the <i>parent</i> of this view specifying how it should be
11213     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
11214     * correspond to the different subclasses of ViewGroup that are responsible
11215     * for arranging their children.
11216     *
11217     * @param params The layout parameters for this view, cannot be null
11218     */
11219    public void setLayoutParams(ViewGroup.LayoutParams params) {
11220        if (params == null) {
11221            throw new NullPointerException("Layout parameters cannot be null");
11222        }
11223        mLayoutParams = params;
11224        resolveLayoutParams();
11225        if (mParent instanceof ViewGroup) {
11226            ((ViewGroup) mParent).onSetLayoutParams(this, params);
11227        }
11228        requestLayout();
11229    }
11230
11231    /**
11232     * Resolve the layout parameters depending on the resolved layout direction
11233     *
11234     * @hide
11235     */
11236    public void resolveLayoutParams() {
11237        if (mLayoutParams != null) {
11238            mLayoutParams.resolveLayoutDirection(getLayoutDirection());
11239        }
11240    }
11241
11242    /**
11243     * Set the scrolled position of your view. This will cause a call to
11244     * {@link #onScrollChanged(int, int, int, int)} and the view will be
11245     * invalidated.
11246     * @param x the x position to scroll to
11247     * @param y the y position to scroll to
11248     */
11249    public void scrollTo(int x, int y) {
11250        if (mScrollX != x || mScrollY != y) {
11251            int oldX = mScrollX;
11252            int oldY = mScrollY;
11253            mScrollX = x;
11254            mScrollY = y;
11255            invalidateParentCaches();
11256            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
11257            if (!awakenScrollBars()) {
11258                postInvalidateOnAnimation();
11259            }
11260        }
11261    }
11262
11263    /**
11264     * Move the scrolled position of your view. This will cause a call to
11265     * {@link #onScrollChanged(int, int, int, int)} and the view will be
11266     * invalidated.
11267     * @param x the amount of pixels to scroll by horizontally
11268     * @param y the amount of pixels to scroll by vertically
11269     */
11270    public void scrollBy(int x, int y) {
11271        scrollTo(mScrollX + x, mScrollY + y);
11272    }
11273
11274    /**
11275     * <p>Trigger the scrollbars to draw. When invoked this method starts an
11276     * animation to fade the scrollbars out after a default delay. If a subclass
11277     * provides animated scrolling, the start delay should equal the duration
11278     * of the scrolling animation.</p>
11279     *
11280     * <p>The animation starts only if at least one of the scrollbars is
11281     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
11282     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11283     * this method returns true, and false otherwise. If the animation is
11284     * started, this method calls {@link #invalidate()}; in that case the
11285     * caller should not call {@link #invalidate()}.</p>
11286     *
11287     * <p>This method should be invoked every time a subclass directly updates
11288     * the scroll parameters.</p>
11289     *
11290     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
11291     * and {@link #scrollTo(int, int)}.</p>
11292     *
11293     * @return true if the animation is played, false otherwise
11294     *
11295     * @see #awakenScrollBars(int)
11296     * @see #scrollBy(int, int)
11297     * @see #scrollTo(int, int)
11298     * @see #isHorizontalScrollBarEnabled()
11299     * @see #isVerticalScrollBarEnabled()
11300     * @see #setHorizontalScrollBarEnabled(boolean)
11301     * @see #setVerticalScrollBarEnabled(boolean)
11302     */
11303    protected boolean awakenScrollBars() {
11304        return mScrollCache != null &&
11305                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
11306    }
11307
11308    /**
11309     * Trigger the scrollbars to draw.
11310     * This method differs from awakenScrollBars() only in its default duration.
11311     * initialAwakenScrollBars() will show the scroll bars for longer than
11312     * usual to give the user more of a chance to notice them.
11313     *
11314     * @return true if the animation is played, false otherwise.
11315     */
11316    private boolean initialAwakenScrollBars() {
11317        return mScrollCache != null &&
11318                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
11319    }
11320
11321    /**
11322     * <p>
11323     * Trigger the scrollbars to draw. When invoked this method starts an
11324     * animation to fade the scrollbars out after a fixed delay. If a subclass
11325     * provides animated scrolling, the start delay should equal the duration of
11326     * the scrolling animation.
11327     * </p>
11328     *
11329     * <p>
11330     * The animation starts only if at least one of the scrollbars is enabled,
11331     * as specified by {@link #isHorizontalScrollBarEnabled()} and
11332     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11333     * this method returns true, and false otherwise. If the animation is
11334     * started, this method calls {@link #invalidate()}; in that case the caller
11335     * should not call {@link #invalidate()}.
11336     * </p>
11337     *
11338     * <p>
11339     * This method should be invoked everytime a subclass directly updates the
11340     * scroll parameters.
11341     * </p>
11342     *
11343     * @param startDelay the delay, in milliseconds, after which the animation
11344     *        should start; when the delay is 0, the animation starts
11345     *        immediately
11346     * @return true if the animation is played, false otherwise
11347     *
11348     * @see #scrollBy(int, int)
11349     * @see #scrollTo(int, int)
11350     * @see #isHorizontalScrollBarEnabled()
11351     * @see #isVerticalScrollBarEnabled()
11352     * @see #setHorizontalScrollBarEnabled(boolean)
11353     * @see #setVerticalScrollBarEnabled(boolean)
11354     */
11355    protected boolean awakenScrollBars(int startDelay) {
11356        return awakenScrollBars(startDelay, true);
11357    }
11358
11359    /**
11360     * <p>
11361     * Trigger the scrollbars to draw. When invoked this method starts an
11362     * animation to fade the scrollbars out after a fixed delay. If a subclass
11363     * provides animated scrolling, the start delay should equal the duration of
11364     * the scrolling animation.
11365     * </p>
11366     *
11367     * <p>
11368     * The animation starts only if at least one of the scrollbars is enabled,
11369     * as specified by {@link #isHorizontalScrollBarEnabled()} and
11370     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11371     * this method returns true, and false otherwise. If the animation is
11372     * started, this method calls {@link #invalidate()} if the invalidate parameter
11373     * is set to true; in that case the caller
11374     * should not call {@link #invalidate()}.
11375     * </p>
11376     *
11377     * <p>
11378     * This method should be invoked everytime a subclass directly updates the
11379     * scroll parameters.
11380     * </p>
11381     *
11382     * @param startDelay the delay, in milliseconds, after which the animation
11383     *        should start; when the delay is 0, the animation starts
11384     *        immediately
11385     *
11386     * @param invalidate Wheter this method should call invalidate
11387     *
11388     * @return true if the animation is played, false otherwise
11389     *
11390     * @see #scrollBy(int, int)
11391     * @see #scrollTo(int, int)
11392     * @see #isHorizontalScrollBarEnabled()
11393     * @see #isVerticalScrollBarEnabled()
11394     * @see #setHorizontalScrollBarEnabled(boolean)
11395     * @see #setVerticalScrollBarEnabled(boolean)
11396     */
11397    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
11398        final ScrollabilityCache scrollCache = mScrollCache;
11399
11400        if (scrollCache == null || !scrollCache.fadeScrollBars) {
11401            return false;
11402        }
11403
11404        if (scrollCache.scrollBar == null) {
11405            scrollCache.scrollBar = new ScrollBarDrawable();
11406        }
11407
11408        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
11409
11410            if (invalidate) {
11411                // Invalidate to show the scrollbars
11412                postInvalidateOnAnimation();
11413            }
11414
11415            if (scrollCache.state == ScrollabilityCache.OFF) {
11416                // FIXME: this is copied from WindowManagerService.
11417                // We should get this value from the system when it
11418                // is possible to do so.
11419                final int KEY_REPEAT_FIRST_DELAY = 750;
11420                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
11421            }
11422
11423            // Tell mScrollCache when we should start fading. This may
11424            // extend the fade start time if one was already scheduled
11425            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
11426            scrollCache.fadeStartTime = fadeStartTime;
11427            scrollCache.state = ScrollabilityCache.ON;
11428
11429            // Schedule our fader to run, unscheduling any old ones first
11430            if (mAttachInfo != null) {
11431                mAttachInfo.mHandler.removeCallbacks(scrollCache);
11432                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
11433            }
11434
11435            return true;
11436        }
11437
11438        return false;
11439    }
11440
11441    /**
11442     * Do not invalidate views which are not visible and which are not running an animation. They
11443     * will not get drawn and they should not set dirty flags as if they will be drawn
11444     */
11445    private boolean skipInvalidate() {
11446        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
11447                (!(mParent instanceof ViewGroup) ||
11448                        !((ViewGroup) mParent).isViewTransitioning(this));
11449    }
11450
11451    /**
11452     * Mark the area defined by dirty as needing to be drawn. If the view is
11453     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
11454     * point in the future.
11455     * <p>
11456     * This must be called from a UI thread. To call from a non-UI thread, call
11457     * {@link #postInvalidate()}.
11458     * <p>
11459     * <b>WARNING:</b> In API 19 and below, this method may be destructive to
11460     * {@code dirty}.
11461     *
11462     * @param dirty the rectangle representing the bounds of the dirty region
11463     */
11464    public void invalidate(Rect dirty) {
11465        final int scrollX = mScrollX;
11466        final int scrollY = mScrollY;
11467        invalidateInternal(dirty.left - scrollX, dirty.top - scrollY,
11468                dirty.right - scrollX, dirty.bottom - scrollY, true, false);
11469    }
11470
11471    /**
11472     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The
11473     * coordinates of the dirty rect are relative to the view. If the view is
11474     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
11475     * point in the future.
11476     * <p>
11477     * This must be called from a UI thread. To call from a non-UI thread, call
11478     * {@link #postInvalidate()}.
11479     *
11480     * @param l the left position of the dirty region
11481     * @param t the top position of the dirty region
11482     * @param r the right position of the dirty region
11483     * @param b the bottom position of the dirty region
11484     */
11485    public void invalidate(int l, int t, int r, int b) {
11486        final int scrollX = mScrollX;
11487        final int scrollY = mScrollY;
11488        invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false);
11489    }
11490
11491    /**
11492     * Invalidate the whole view. If the view is visible,
11493     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
11494     * the future.
11495     * <p>
11496     * This must be called from a UI thread. To call from a non-UI thread, call
11497     * {@link #postInvalidate()}.
11498     */
11499    public void invalidate() {
11500        invalidate(true);
11501    }
11502
11503    /**
11504     * This is where the invalidate() work actually happens. A full invalidate()
11505     * causes the drawing cache to be invalidated, but this function can be
11506     * called with invalidateCache set to false to skip that invalidation step
11507     * for cases that do not need it (for example, a component that remains at
11508     * the same dimensions with the same content).
11509     *
11510     * @param invalidateCache Whether the drawing cache for this view should be
11511     *            invalidated as well. This is usually true for a full
11512     *            invalidate, but may be set to false if the View's contents or
11513     *            dimensions have not changed.
11514     */
11515    void invalidate(boolean invalidateCache) {
11516        invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true);
11517    }
11518
11519    void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache,
11520            boolean fullInvalidate) {
11521        if (skipInvalidate()) {
11522            return;
11523        }
11524
11525        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)
11526                || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID)
11527                || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED
11528                || (fullInvalidate && isOpaque() != mLastIsOpaque)) {
11529            if (fullInvalidate) {
11530                mLastIsOpaque = isOpaque();
11531                mPrivateFlags &= ~PFLAG_DRAWN;
11532            }
11533
11534            mPrivateFlags |= PFLAG_DIRTY;
11535
11536            if (invalidateCache) {
11537                mPrivateFlags |= PFLAG_INVALIDATED;
11538                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
11539            }
11540
11541            // Propagate the damage rectangle to the parent view.
11542            final AttachInfo ai = mAttachInfo;
11543            final ViewParent p = mParent;
11544            if (p != null && ai != null && l < r && t < b) {
11545                final Rect damage = ai.mTmpInvalRect;
11546                damage.set(l, t, r, b);
11547                p.invalidateChild(this, damage);
11548            }
11549
11550            // Damage the entire projection receiver, if necessary.
11551            if (mBackground != null && mBackground.isProjected()) {
11552                final View receiver = getProjectionReceiver();
11553                if (receiver != null) {
11554                    receiver.damageInParent();
11555                }
11556            }
11557
11558            // Damage the entire IsolatedZVolume recieving this view's shadow.
11559            if (getCastsShadow() && getTranslationZ() != 0) {
11560                damageIsolatedZVolume();
11561            }
11562        }
11563    }
11564
11565    /**
11566     * @return this view's projection receiver, or {@code null} if none exists
11567     */
11568    private View getProjectionReceiver() {
11569        ViewParent p = getParent();
11570        while (p != null && p instanceof View) {
11571            final View v = (View) p;
11572            if (v.isProjectionReceiver()) {
11573                return v;
11574            }
11575            p = p.getParent();
11576        }
11577
11578        return null;
11579    }
11580
11581    /**
11582     * @return whether the view is a projection receiver
11583     */
11584    private boolean isProjectionReceiver() {
11585        return mBackground != null;
11586    }
11587
11588    /**
11589     * Damage area of the screen covered by the current isolated Z volume
11590     *
11591     * This method will guarantee that any changes to shadows cast by a View
11592     * are damaged on the screen for future redraw.
11593     */
11594    private void damageIsolatedZVolume() {
11595        final AttachInfo ai = mAttachInfo;
11596        if (ai != null) {
11597            ViewParent p = getParent();
11598            while (p != null) {
11599                if (p instanceof ViewGroup) {
11600                    final ViewGroup vg = (ViewGroup) p;
11601                    if (vg.hasIsolatedZVolume()) {
11602                        vg.damageInParent();
11603                        return;
11604                    }
11605                }
11606                p = p.getParent();
11607            }
11608        }
11609    }
11610
11611    /**
11612     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
11613     * set any flags or handle all of the cases handled by the default invalidation methods.
11614     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
11615     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
11616     * walk up the hierarchy, transforming the dirty rect as necessary.
11617     *
11618     * The method also handles normal invalidation logic if display list properties are not
11619     * being used in this view. The invalidateParent and forceRedraw flags are used by that
11620     * backup approach, to handle these cases used in the various property-setting methods.
11621     *
11622     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
11623     * are not being used in this view
11624     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
11625     * list properties are not being used in this view
11626     */
11627    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
11628        if (mDisplayList == null || (mPrivateFlags & PFLAG_DRAW_ANIMATION) == PFLAG_DRAW_ANIMATION) {
11629            if (invalidateParent) {
11630                invalidateParentCaches();
11631            }
11632            if (forceRedraw) {
11633                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
11634            }
11635            invalidate(false);
11636        } else {
11637            damageInParent();
11638        }
11639        if (invalidateParent && getCastsShadow() && getTranslationZ() != 0) {
11640            damageIsolatedZVolume();
11641        }
11642    }
11643
11644    /**
11645     * Tells the parent view to damage this view's bounds.
11646     *
11647     * @hide
11648     */
11649    protected void damageInParent() {
11650        final AttachInfo ai = mAttachInfo;
11651        final ViewParent p = mParent;
11652        if (p != null && ai != null) {
11653            final Rect r = ai.mTmpInvalRect;
11654            r.set(0, 0, mRight - mLeft, mBottom - mTop);
11655            if (mParent instanceof ViewGroup) {
11656                ((ViewGroup) mParent).invalidateChildFast(this, r);
11657            } else {
11658                mParent.invalidateChild(this, r);
11659            }
11660        }
11661    }
11662
11663    /**
11664     * Utility method to transform a given Rect by the current matrix of this view.
11665     */
11666    void transformRect(final Rect rect) {
11667        if (!getMatrix().isIdentity()) {
11668            RectF boundingRect = mAttachInfo.mTmpTransformRect;
11669            boundingRect.set(rect);
11670            getMatrix().mapRect(boundingRect);
11671            rect.set((int) Math.floor(boundingRect.left),
11672                    (int) Math.floor(boundingRect.top),
11673                    (int) Math.ceil(boundingRect.right),
11674                    (int) Math.ceil(boundingRect.bottom));
11675        }
11676    }
11677
11678    /**
11679     * Used to indicate that the parent of this view should clear its caches. This functionality
11680     * is used to force the parent to rebuild its display list (when hardware-accelerated),
11681     * which is necessary when various parent-managed properties of the view change, such as
11682     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
11683     * clears the parent caches and does not causes an invalidate event.
11684     *
11685     * @hide
11686     */
11687    protected void invalidateParentCaches() {
11688        if (mParent instanceof View) {
11689            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
11690        }
11691    }
11692
11693    /**
11694     * Used to indicate that the parent of this view should be invalidated. This functionality
11695     * is used to force the parent to rebuild its display list (when hardware-accelerated),
11696     * which is necessary when various parent-managed properties of the view change, such as
11697     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
11698     * an invalidation event to the parent.
11699     *
11700     * @hide
11701     */
11702    protected void invalidateParentIfNeeded() {
11703        if (isHardwareAccelerated() && mParent instanceof View) {
11704            ((View) mParent).invalidate(true);
11705        }
11706    }
11707
11708    /**
11709     * Indicates whether this View is opaque. An opaque View guarantees that it will
11710     * draw all the pixels overlapping its bounds using a fully opaque color.
11711     *
11712     * Subclasses of View should override this method whenever possible to indicate
11713     * whether an instance is opaque. Opaque Views are treated in a special way by
11714     * the View hierarchy, possibly allowing it to perform optimizations during
11715     * invalidate/draw passes.
11716     *
11717     * @return True if this View is guaranteed to be fully opaque, false otherwise.
11718     */
11719    @ViewDebug.ExportedProperty(category = "drawing")
11720    public boolean isOpaque() {
11721        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
11722                getFinalAlpha() >= 1.0f;
11723    }
11724
11725    /**
11726     * @hide
11727     */
11728    protected void computeOpaqueFlags() {
11729        // Opaque if:
11730        //   - Has a background
11731        //   - Background is opaque
11732        //   - Doesn't have scrollbars or scrollbars overlay
11733
11734        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
11735            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
11736        } else {
11737            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
11738        }
11739
11740        final int flags = mViewFlags;
11741        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
11742                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY ||
11743                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) {
11744            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
11745        } else {
11746            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
11747        }
11748    }
11749
11750    /**
11751     * @hide
11752     */
11753    protected boolean hasOpaqueScrollbars() {
11754        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
11755    }
11756
11757    /**
11758     * @return A handler associated with the thread running the View. This
11759     * handler can be used to pump events in the UI events queue.
11760     */
11761    public Handler getHandler() {
11762        final AttachInfo attachInfo = mAttachInfo;
11763        if (attachInfo != null) {
11764            return attachInfo.mHandler;
11765        }
11766        return null;
11767    }
11768
11769    /**
11770     * Gets the view root associated with the View.
11771     * @return The view root, or null if none.
11772     * @hide
11773     */
11774    public ViewRootImpl getViewRootImpl() {
11775        if (mAttachInfo != null) {
11776            return mAttachInfo.mViewRootImpl;
11777        }
11778        return null;
11779    }
11780
11781    /**
11782     * @hide
11783     */
11784    public HardwareRenderer getHardwareRenderer() {
11785        return mAttachInfo != null ? mAttachInfo.mHardwareRenderer : null;
11786    }
11787
11788    /**
11789     * <p>Causes the Runnable to be added to the message queue.
11790     * The runnable will be run on the user interface thread.</p>
11791     *
11792     * @param action The Runnable that will be executed.
11793     *
11794     * @return Returns true if the Runnable was successfully placed in to the
11795     *         message queue.  Returns false on failure, usually because the
11796     *         looper processing the message queue is exiting.
11797     *
11798     * @see #postDelayed
11799     * @see #removeCallbacks
11800     */
11801    public boolean post(Runnable action) {
11802        final AttachInfo attachInfo = mAttachInfo;
11803        if (attachInfo != null) {
11804            return attachInfo.mHandler.post(action);
11805        }
11806        // Assume that post will succeed later
11807        ViewRootImpl.getRunQueue().post(action);
11808        return true;
11809    }
11810
11811    /**
11812     * <p>Causes the Runnable to be added to the message queue, to be run
11813     * after the specified amount of time elapses.
11814     * The runnable will be run on the user interface thread.</p>
11815     *
11816     * @param action The Runnable that will be executed.
11817     * @param delayMillis The delay (in milliseconds) until the Runnable
11818     *        will be executed.
11819     *
11820     * @return true if the Runnable was successfully placed in to the
11821     *         message queue.  Returns false on failure, usually because the
11822     *         looper processing the message queue is exiting.  Note that a
11823     *         result of true does not mean the Runnable will be processed --
11824     *         if the looper is quit before the delivery time of the message
11825     *         occurs then the message will be dropped.
11826     *
11827     * @see #post
11828     * @see #removeCallbacks
11829     */
11830    public boolean postDelayed(Runnable action, long delayMillis) {
11831        final AttachInfo attachInfo = mAttachInfo;
11832        if (attachInfo != null) {
11833            return attachInfo.mHandler.postDelayed(action, delayMillis);
11834        }
11835        // Assume that post will succeed later
11836        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
11837        return true;
11838    }
11839
11840    /**
11841     * <p>Causes the Runnable to execute on the next animation time step.
11842     * The runnable will be run on the user interface thread.</p>
11843     *
11844     * @param action The Runnable that will be executed.
11845     *
11846     * @see #postOnAnimationDelayed
11847     * @see #removeCallbacks
11848     */
11849    public void postOnAnimation(Runnable action) {
11850        final AttachInfo attachInfo = mAttachInfo;
11851        if (attachInfo != null) {
11852            attachInfo.mViewRootImpl.mChoreographer.postCallback(
11853                    Choreographer.CALLBACK_ANIMATION, action, null);
11854        } else {
11855            // Assume that post will succeed later
11856            ViewRootImpl.getRunQueue().post(action);
11857        }
11858    }
11859
11860    /**
11861     * <p>Causes the Runnable to execute on the next animation time step,
11862     * after the specified amount of time elapses.
11863     * The runnable will be run on the user interface thread.</p>
11864     *
11865     * @param action The Runnable that will be executed.
11866     * @param delayMillis The delay (in milliseconds) until the Runnable
11867     *        will be executed.
11868     *
11869     * @see #postOnAnimation
11870     * @see #removeCallbacks
11871     */
11872    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
11873        final AttachInfo attachInfo = mAttachInfo;
11874        if (attachInfo != null) {
11875            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
11876                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
11877        } else {
11878            // Assume that post will succeed later
11879            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
11880        }
11881    }
11882
11883    /**
11884     * <p>Removes the specified Runnable from the message queue.</p>
11885     *
11886     * @param action The Runnable to remove from the message handling queue
11887     *
11888     * @return true if this view could ask the Handler to remove the Runnable,
11889     *         false otherwise. When the returned value is true, the Runnable
11890     *         may or may not have been actually removed from the message queue
11891     *         (for instance, if the Runnable was not in the queue already.)
11892     *
11893     * @see #post
11894     * @see #postDelayed
11895     * @see #postOnAnimation
11896     * @see #postOnAnimationDelayed
11897     */
11898    public boolean removeCallbacks(Runnable action) {
11899        if (action != null) {
11900            final AttachInfo attachInfo = mAttachInfo;
11901            if (attachInfo != null) {
11902                attachInfo.mHandler.removeCallbacks(action);
11903                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
11904                        Choreographer.CALLBACK_ANIMATION, action, null);
11905            }
11906            // Assume that post will succeed later
11907            ViewRootImpl.getRunQueue().removeCallbacks(action);
11908        }
11909        return true;
11910    }
11911
11912    /**
11913     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
11914     * Use this to invalidate the View from a non-UI thread.</p>
11915     *
11916     * <p>This method can be invoked from outside of the UI thread
11917     * only when this View is attached to a window.</p>
11918     *
11919     * @see #invalidate()
11920     * @see #postInvalidateDelayed(long)
11921     */
11922    public void postInvalidate() {
11923        postInvalidateDelayed(0);
11924    }
11925
11926    /**
11927     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
11928     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
11929     *
11930     * <p>This method can be invoked from outside of the UI thread
11931     * only when this View is attached to a window.</p>
11932     *
11933     * @param left The left coordinate of the rectangle to invalidate.
11934     * @param top The top coordinate of the rectangle to invalidate.
11935     * @param right The right coordinate of the rectangle to invalidate.
11936     * @param bottom The bottom coordinate of the rectangle to invalidate.
11937     *
11938     * @see #invalidate(int, int, int, int)
11939     * @see #invalidate(Rect)
11940     * @see #postInvalidateDelayed(long, int, int, int, int)
11941     */
11942    public void postInvalidate(int left, int top, int right, int bottom) {
11943        postInvalidateDelayed(0, left, top, right, bottom);
11944    }
11945
11946    /**
11947     * <p>Cause an invalidate to happen on a subsequent cycle through the event
11948     * loop. Waits for the specified amount of time.</p>
11949     *
11950     * <p>This method can be invoked from outside of the UI thread
11951     * only when this View is attached to a window.</p>
11952     *
11953     * @param delayMilliseconds the duration in milliseconds to delay the
11954     *         invalidation by
11955     *
11956     * @see #invalidate()
11957     * @see #postInvalidate()
11958     */
11959    public void postInvalidateDelayed(long delayMilliseconds) {
11960        // We try only with the AttachInfo because there's no point in invalidating
11961        // if we are not attached to our window
11962        final AttachInfo attachInfo = mAttachInfo;
11963        if (attachInfo != null) {
11964            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
11965        }
11966    }
11967
11968    /**
11969     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
11970     * through the event loop. Waits for the specified amount of time.</p>
11971     *
11972     * <p>This method can be invoked from outside of the UI thread
11973     * only when this View is attached to a window.</p>
11974     *
11975     * @param delayMilliseconds the duration in milliseconds to delay the
11976     *         invalidation by
11977     * @param left The left coordinate of the rectangle to invalidate.
11978     * @param top The top coordinate of the rectangle to invalidate.
11979     * @param right The right coordinate of the rectangle to invalidate.
11980     * @param bottom The bottom coordinate of the rectangle to invalidate.
11981     *
11982     * @see #invalidate(int, int, int, int)
11983     * @see #invalidate(Rect)
11984     * @see #postInvalidate(int, int, int, int)
11985     */
11986    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
11987            int right, int bottom) {
11988
11989        // We try only with the AttachInfo because there's no point in invalidating
11990        // if we are not attached to our window
11991        final AttachInfo attachInfo = mAttachInfo;
11992        if (attachInfo != null) {
11993            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
11994            info.target = this;
11995            info.left = left;
11996            info.top = top;
11997            info.right = right;
11998            info.bottom = bottom;
11999
12000            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
12001        }
12002    }
12003
12004    /**
12005     * <p>Cause an invalidate to happen on the next animation time step, typically the
12006     * next display frame.</p>
12007     *
12008     * <p>This method can be invoked from outside of the UI thread
12009     * only when this View is attached to a window.</p>
12010     *
12011     * @see #invalidate()
12012     */
12013    public void postInvalidateOnAnimation() {
12014        // We try only with the AttachInfo because there's no point in invalidating
12015        // if we are not attached to our window
12016        final AttachInfo attachInfo = mAttachInfo;
12017        if (attachInfo != null) {
12018            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
12019        }
12020    }
12021
12022    /**
12023     * <p>Cause an invalidate of the specified area to happen on the next animation
12024     * time step, typically the next display frame.</p>
12025     *
12026     * <p>This method can be invoked from outside of the UI thread
12027     * only when this View is attached to a window.</p>
12028     *
12029     * @param left The left coordinate of the rectangle to invalidate.
12030     * @param top The top coordinate of the rectangle to invalidate.
12031     * @param right The right coordinate of the rectangle to invalidate.
12032     * @param bottom The bottom coordinate of the rectangle to invalidate.
12033     *
12034     * @see #invalidate(int, int, int, int)
12035     * @see #invalidate(Rect)
12036     */
12037    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
12038        // We try only with the AttachInfo because there's no point in invalidating
12039        // if we are not attached to our window
12040        final AttachInfo attachInfo = mAttachInfo;
12041        if (attachInfo != null) {
12042            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
12043            info.target = this;
12044            info.left = left;
12045            info.top = top;
12046            info.right = right;
12047            info.bottom = bottom;
12048
12049            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
12050        }
12051    }
12052
12053    /**
12054     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
12055     * This event is sent at most once every
12056     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
12057     */
12058    private void postSendViewScrolledAccessibilityEventCallback() {
12059        if (mSendViewScrolledAccessibilityEvent == null) {
12060            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
12061        }
12062        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
12063            mSendViewScrolledAccessibilityEvent.mIsPending = true;
12064            postDelayed(mSendViewScrolledAccessibilityEvent,
12065                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
12066        }
12067    }
12068
12069    /**
12070     * Called by a parent to request that a child update its values for mScrollX
12071     * and mScrollY if necessary. This will typically be done if the child is
12072     * animating a scroll using a {@link android.widget.Scroller Scroller}
12073     * object.
12074     */
12075    public void computeScroll() {
12076    }
12077
12078    /**
12079     * <p>Indicate whether the horizontal edges are faded when the view is
12080     * scrolled horizontally.</p>
12081     *
12082     * @return true if the horizontal edges should are faded on scroll, false
12083     *         otherwise
12084     *
12085     * @see #setHorizontalFadingEdgeEnabled(boolean)
12086     *
12087     * @attr ref android.R.styleable#View_requiresFadingEdge
12088     */
12089    public boolean isHorizontalFadingEdgeEnabled() {
12090        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
12091    }
12092
12093    /**
12094     * <p>Define whether the horizontal edges should be faded when this view
12095     * is scrolled horizontally.</p>
12096     *
12097     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
12098     *                                    be faded when the view is scrolled
12099     *                                    horizontally
12100     *
12101     * @see #isHorizontalFadingEdgeEnabled()
12102     *
12103     * @attr ref android.R.styleable#View_requiresFadingEdge
12104     */
12105    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
12106        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
12107            if (horizontalFadingEdgeEnabled) {
12108                initScrollCache();
12109            }
12110
12111            mViewFlags ^= FADING_EDGE_HORIZONTAL;
12112        }
12113    }
12114
12115    /**
12116     * <p>Indicate whether the vertical edges are faded when the view is
12117     * scrolled horizontally.</p>
12118     *
12119     * @return true if the vertical edges should are faded on scroll, false
12120     *         otherwise
12121     *
12122     * @see #setVerticalFadingEdgeEnabled(boolean)
12123     *
12124     * @attr ref android.R.styleable#View_requiresFadingEdge
12125     */
12126    public boolean isVerticalFadingEdgeEnabled() {
12127        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
12128    }
12129
12130    /**
12131     * <p>Define whether the vertical edges should be faded when this view
12132     * is scrolled vertically.</p>
12133     *
12134     * @param verticalFadingEdgeEnabled true if the vertical edges should
12135     *                                  be faded when the view is scrolled
12136     *                                  vertically
12137     *
12138     * @see #isVerticalFadingEdgeEnabled()
12139     *
12140     * @attr ref android.R.styleable#View_requiresFadingEdge
12141     */
12142    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
12143        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
12144            if (verticalFadingEdgeEnabled) {
12145                initScrollCache();
12146            }
12147
12148            mViewFlags ^= FADING_EDGE_VERTICAL;
12149        }
12150    }
12151
12152    /**
12153     * Returns the strength, or intensity, of the top faded edge. The strength is
12154     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12155     * returns 0.0 or 1.0 but no value in between.
12156     *
12157     * Subclasses should override this method to provide a smoother fade transition
12158     * when scrolling occurs.
12159     *
12160     * @return the intensity of the top fade as a float between 0.0f and 1.0f
12161     */
12162    protected float getTopFadingEdgeStrength() {
12163        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
12164    }
12165
12166    /**
12167     * Returns the strength, or intensity, of the bottom faded edge. The strength is
12168     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12169     * returns 0.0 or 1.0 but no value in between.
12170     *
12171     * Subclasses should override this method to provide a smoother fade transition
12172     * when scrolling occurs.
12173     *
12174     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
12175     */
12176    protected float getBottomFadingEdgeStrength() {
12177        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
12178                computeVerticalScrollRange() ? 1.0f : 0.0f;
12179    }
12180
12181    /**
12182     * Returns the strength, or intensity, of the left faded edge. The strength is
12183     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12184     * returns 0.0 or 1.0 but no value in between.
12185     *
12186     * Subclasses should override this method to provide a smoother fade transition
12187     * when scrolling occurs.
12188     *
12189     * @return the intensity of the left fade as a float between 0.0f and 1.0f
12190     */
12191    protected float getLeftFadingEdgeStrength() {
12192        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
12193    }
12194
12195    /**
12196     * Returns the strength, or intensity, of the right faded edge. The strength is
12197     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12198     * returns 0.0 or 1.0 but no value in between.
12199     *
12200     * Subclasses should override this method to provide a smoother fade transition
12201     * when scrolling occurs.
12202     *
12203     * @return the intensity of the right fade as a float between 0.0f and 1.0f
12204     */
12205    protected float getRightFadingEdgeStrength() {
12206        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
12207                computeHorizontalScrollRange() ? 1.0f : 0.0f;
12208    }
12209
12210    /**
12211     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
12212     * scrollbar is not drawn by default.</p>
12213     *
12214     * @return true if the horizontal scrollbar should be painted, false
12215     *         otherwise
12216     *
12217     * @see #setHorizontalScrollBarEnabled(boolean)
12218     */
12219    public boolean isHorizontalScrollBarEnabled() {
12220        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
12221    }
12222
12223    /**
12224     * <p>Define whether the horizontal scrollbar should be drawn or not. The
12225     * scrollbar is not drawn by default.</p>
12226     *
12227     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
12228     *                                   be painted
12229     *
12230     * @see #isHorizontalScrollBarEnabled()
12231     */
12232    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
12233        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
12234            mViewFlags ^= SCROLLBARS_HORIZONTAL;
12235            computeOpaqueFlags();
12236            resolvePadding();
12237        }
12238    }
12239
12240    /**
12241     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
12242     * scrollbar is not drawn by default.</p>
12243     *
12244     * @return true if the vertical scrollbar should be painted, false
12245     *         otherwise
12246     *
12247     * @see #setVerticalScrollBarEnabled(boolean)
12248     */
12249    public boolean isVerticalScrollBarEnabled() {
12250        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
12251    }
12252
12253    /**
12254     * <p>Define whether the vertical scrollbar should be drawn or not. The
12255     * scrollbar is not drawn by default.</p>
12256     *
12257     * @param verticalScrollBarEnabled true if the vertical scrollbar should
12258     *                                 be painted
12259     *
12260     * @see #isVerticalScrollBarEnabled()
12261     */
12262    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
12263        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
12264            mViewFlags ^= SCROLLBARS_VERTICAL;
12265            computeOpaqueFlags();
12266            resolvePadding();
12267        }
12268    }
12269
12270    /**
12271     * @hide
12272     */
12273    protected void recomputePadding() {
12274        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
12275    }
12276
12277    /**
12278     * Define whether scrollbars will fade when the view is not scrolling.
12279     *
12280     * @param fadeScrollbars wheter to enable fading
12281     *
12282     * @attr ref android.R.styleable#View_fadeScrollbars
12283     */
12284    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
12285        initScrollCache();
12286        final ScrollabilityCache scrollabilityCache = mScrollCache;
12287        scrollabilityCache.fadeScrollBars = fadeScrollbars;
12288        if (fadeScrollbars) {
12289            scrollabilityCache.state = ScrollabilityCache.OFF;
12290        } else {
12291            scrollabilityCache.state = ScrollabilityCache.ON;
12292        }
12293    }
12294
12295    /**
12296     *
12297     * Returns true if scrollbars will fade when this view is not scrolling
12298     *
12299     * @return true if scrollbar fading is enabled
12300     *
12301     * @attr ref android.R.styleable#View_fadeScrollbars
12302     */
12303    public boolean isScrollbarFadingEnabled() {
12304        return mScrollCache != null && mScrollCache.fadeScrollBars;
12305    }
12306
12307    /**
12308     *
12309     * Returns the delay before scrollbars fade.
12310     *
12311     * @return the delay before scrollbars fade
12312     *
12313     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
12314     */
12315    public int getScrollBarDefaultDelayBeforeFade() {
12316        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
12317                mScrollCache.scrollBarDefaultDelayBeforeFade;
12318    }
12319
12320    /**
12321     * Define the delay before scrollbars fade.
12322     *
12323     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
12324     *
12325     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
12326     */
12327    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
12328        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
12329    }
12330
12331    /**
12332     *
12333     * Returns the scrollbar fade duration.
12334     *
12335     * @return the scrollbar fade duration
12336     *
12337     * @attr ref android.R.styleable#View_scrollbarFadeDuration
12338     */
12339    public int getScrollBarFadeDuration() {
12340        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
12341                mScrollCache.scrollBarFadeDuration;
12342    }
12343
12344    /**
12345     * Define the scrollbar fade duration.
12346     *
12347     * @param scrollBarFadeDuration - the scrollbar fade duration
12348     *
12349     * @attr ref android.R.styleable#View_scrollbarFadeDuration
12350     */
12351    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
12352        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
12353    }
12354
12355    /**
12356     *
12357     * Returns the scrollbar size.
12358     *
12359     * @return the scrollbar size
12360     *
12361     * @attr ref android.R.styleable#View_scrollbarSize
12362     */
12363    public int getScrollBarSize() {
12364        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
12365                mScrollCache.scrollBarSize;
12366    }
12367
12368    /**
12369     * Define the scrollbar size.
12370     *
12371     * @param scrollBarSize - the scrollbar size
12372     *
12373     * @attr ref android.R.styleable#View_scrollbarSize
12374     */
12375    public void setScrollBarSize(int scrollBarSize) {
12376        getScrollCache().scrollBarSize = scrollBarSize;
12377    }
12378
12379    /**
12380     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
12381     * inset. When inset, they add to the padding of the view. And the scrollbars
12382     * can be drawn inside the padding area or on the edge of the view. For example,
12383     * if a view has a background drawable and you want to draw the scrollbars
12384     * inside the padding specified by the drawable, you can use
12385     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
12386     * appear at the edge of the view, ignoring the padding, then you can use
12387     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
12388     * @param style the style of the scrollbars. Should be one of
12389     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
12390     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
12391     * @see #SCROLLBARS_INSIDE_OVERLAY
12392     * @see #SCROLLBARS_INSIDE_INSET
12393     * @see #SCROLLBARS_OUTSIDE_OVERLAY
12394     * @see #SCROLLBARS_OUTSIDE_INSET
12395     *
12396     * @attr ref android.R.styleable#View_scrollbarStyle
12397     */
12398    public void setScrollBarStyle(@ScrollBarStyle int style) {
12399        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
12400            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
12401            computeOpaqueFlags();
12402            resolvePadding();
12403        }
12404    }
12405
12406    /**
12407     * <p>Returns the current scrollbar style.</p>
12408     * @return the current scrollbar style
12409     * @see #SCROLLBARS_INSIDE_OVERLAY
12410     * @see #SCROLLBARS_INSIDE_INSET
12411     * @see #SCROLLBARS_OUTSIDE_OVERLAY
12412     * @see #SCROLLBARS_OUTSIDE_INSET
12413     *
12414     * @attr ref android.R.styleable#View_scrollbarStyle
12415     */
12416    @ViewDebug.ExportedProperty(mapping = {
12417            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
12418            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
12419            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
12420            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
12421    })
12422    @ScrollBarStyle
12423    public int getScrollBarStyle() {
12424        return mViewFlags & SCROLLBARS_STYLE_MASK;
12425    }
12426
12427    /**
12428     * <p>Compute the horizontal range that the horizontal scrollbar
12429     * represents.</p>
12430     *
12431     * <p>The range is expressed in arbitrary units that must be the same as the
12432     * units used by {@link #computeHorizontalScrollExtent()} and
12433     * {@link #computeHorizontalScrollOffset()}.</p>
12434     *
12435     * <p>The default range is the drawing width of this view.</p>
12436     *
12437     * @return the total horizontal range represented by the horizontal
12438     *         scrollbar
12439     *
12440     * @see #computeHorizontalScrollExtent()
12441     * @see #computeHorizontalScrollOffset()
12442     * @see android.widget.ScrollBarDrawable
12443     */
12444    protected int computeHorizontalScrollRange() {
12445        return getWidth();
12446    }
12447
12448    /**
12449     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
12450     * within the horizontal range. This value is used to compute the position
12451     * of the thumb within the scrollbar's track.</p>
12452     *
12453     * <p>The range is expressed in arbitrary units that must be the same as the
12454     * units used by {@link #computeHorizontalScrollRange()} and
12455     * {@link #computeHorizontalScrollExtent()}.</p>
12456     *
12457     * <p>The default offset is the scroll offset of this view.</p>
12458     *
12459     * @return the horizontal offset of the scrollbar's thumb
12460     *
12461     * @see #computeHorizontalScrollRange()
12462     * @see #computeHorizontalScrollExtent()
12463     * @see android.widget.ScrollBarDrawable
12464     */
12465    protected int computeHorizontalScrollOffset() {
12466        return mScrollX;
12467    }
12468
12469    /**
12470     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
12471     * within the horizontal range. This value is used to compute the length
12472     * of the thumb within the scrollbar's track.</p>
12473     *
12474     * <p>The range is expressed in arbitrary units that must be the same as the
12475     * units used by {@link #computeHorizontalScrollRange()} and
12476     * {@link #computeHorizontalScrollOffset()}.</p>
12477     *
12478     * <p>The default extent is the drawing width of this view.</p>
12479     *
12480     * @return the horizontal extent of the scrollbar's thumb
12481     *
12482     * @see #computeHorizontalScrollRange()
12483     * @see #computeHorizontalScrollOffset()
12484     * @see android.widget.ScrollBarDrawable
12485     */
12486    protected int computeHorizontalScrollExtent() {
12487        return getWidth();
12488    }
12489
12490    /**
12491     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
12492     *
12493     * <p>The range is expressed in arbitrary units that must be the same as the
12494     * units used by {@link #computeVerticalScrollExtent()} and
12495     * {@link #computeVerticalScrollOffset()}.</p>
12496     *
12497     * @return the total vertical range represented by the vertical scrollbar
12498     *
12499     * <p>The default range is the drawing height of this view.</p>
12500     *
12501     * @see #computeVerticalScrollExtent()
12502     * @see #computeVerticalScrollOffset()
12503     * @see android.widget.ScrollBarDrawable
12504     */
12505    protected int computeVerticalScrollRange() {
12506        return getHeight();
12507    }
12508
12509    /**
12510     * <p>Compute the vertical offset of the vertical scrollbar's thumb
12511     * within the horizontal range. This value is used to compute the position
12512     * of the thumb within the scrollbar's track.</p>
12513     *
12514     * <p>The range is expressed in arbitrary units that must be the same as the
12515     * units used by {@link #computeVerticalScrollRange()} and
12516     * {@link #computeVerticalScrollExtent()}.</p>
12517     *
12518     * <p>The default offset is the scroll offset of this view.</p>
12519     *
12520     * @return the vertical offset of the scrollbar's thumb
12521     *
12522     * @see #computeVerticalScrollRange()
12523     * @see #computeVerticalScrollExtent()
12524     * @see android.widget.ScrollBarDrawable
12525     */
12526    protected int computeVerticalScrollOffset() {
12527        return mScrollY;
12528    }
12529
12530    /**
12531     * <p>Compute the vertical extent of the vertical scrollbar's thumb
12532     * within the vertical range. This value is used to compute the length
12533     * of the thumb within the scrollbar's track.</p>
12534     *
12535     * <p>The range is expressed in arbitrary units that must be the same as the
12536     * units used by {@link #computeVerticalScrollRange()} and
12537     * {@link #computeVerticalScrollOffset()}.</p>
12538     *
12539     * <p>The default extent is the drawing height of this view.</p>
12540     *
12541     * @return the vertical extent of the scrollbar's thumb
12542     *
12543     * @see #computeVerticalScrollRange()
12544     * @see #computeVerticalScrollOffset()
12545     * @see android.widget.ScrollBarDrawable
12546     */
12547    protected int computeVerticalScrollExtent() {
12548        return getHeight();
12549    }
12550
12551    /**
12552     * Check if this view can be scrolled horizontally in a certain direction.
12553     *
12554     * @param direction Negative to check scrolling left, positive to check scrolling right.
12555     * @return true if this view can be scrolled in the specified direction, false otherwise.
12556     */
12557    public boolean canScrollHorizontally(int direction) {
12558        final int offset = computeHorizontalScrollOffset();
12559        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
12560        if (range == 0) return false;
12561        if (direction < 0) {
12562            return offset > 0;
12563        } else {
12564            return offset < range - 1;
12565        }
12566    }
12567
12568    /**
12569     * Check if this view can be scrolled vertically in a certain direction.
12570     *
12571     * @param direction Negative to check scrolling up, positive to check scrolling down.
12572     * @return true if this view can be scrolled in the specified direction, false otherwise.
12573     */
12574    public boolean canScrollVertically(int direction) {
12575        final int offset = computeVerticalScrollOffset();
12576        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
12577        if (range == 0) return false;
12578        if (direction < 0) {
12579            return offset > 0;
12580        } else {
12581            return offset < range - 1;
12582        }
12583    }
12584
12585    /**
12586     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
12587     * scrollbars are painted only if they have been awakened first.</p>
12588     *
12589     * @param canvas the canvas on which to draw the scrollbars
12590     *
12591     * @see #awakenScrollBars(int)
12592     */
12593    protected final void onDrawScrollBars(Canvas canvas) {
12594        // scrollbars are drawn only when the animation is running
12595        final ScrollabilityCache cache = mScrollCache;
12596        if (cache != null) {
12597
12598            int state = cache.state;
12599
12600            if (state == ScrollabilityCache.OFF) {
12601                return;
12602            }
12603
12604            boolean invalidate = false;
12605
12606            if (state == ScrollabilityCache.FADING) {
12607                // We're fading -- get our fade interpolation
12608                if (cache.interpolatorValues == null) {
12609                    cache.interpolatorValues = new float[1];
12610                }
12611
12612                float[] values = cache.interpolatorValues;
12613
12614                // Stops the animation if we're done
12615                if (cache.scrollBarInterpolator.timeToValues(values) ==
12616                        Interpolator.Result.FREEZE_END) {
12617                    cache.state = ScrollabilityCache.OFF;
12618                } else {
12619                    cache.scrollBar.setAlpha(Math.round(values[0]));
12620                }
12621
12622                // This will make the scroll bars inval themselves after
12623                // drawing. We only want this when we're fading so that
12624                // we prevent excessive redraws
12625                invalidate = true;
12626            } else {
12627                // We're just on -- but we may have been fading before so
12628                // reset alpha
12629                cache.scrollBar.setAlpha(255);
12630            }
12631
12632
12633            final int viewFlags = mViewFlags;
12634
12635            final boolean drawHorizontalScrollBar =
12636                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
12637            final boolean drawVerticalScrollBar =
12638                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
12639                && !isVerticalScrollBarHidden();
12640
12641            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
12642                final int width = mRight - mLeft;
12643                final int height = mBottom - mTop;
12644
12645                final ScrollBarDrawable scrollBar = cache.scrollBar;
12646
12647                final int scrollX = mScrollX;
12648                final int scrollY = mScrollY;
12649                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
12650
12651                int left;
12652                int top;
12653                int right;
12654                int bottom;
12655
12656                if (drawHorizontalScrollBar) {
12657                    int size = scrollBar.getSize(false);
12658                    if (size <= 0) {
12659                        size = cache.scrollBarSize;
12660                    }
12661
12662                    scrollBar.setParameters(computeHorizontalScrollRange(),
12663                                            computeHorizontalScrollOffset(),
12664                                            computeHorizontalScrollExtent(), false);
12665                    final int verticalScrollBarGap = drawVerticalScrollBar ?
12666                            getVerticalScrollbarWidth() : 0;
12667                    top = scrollY + height - size - (mUserPaddingBottom & inside);
12668                    left = scrollX + (mPaddingLeft & inside);
12669                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
12670                    bottom = top + size;
12671                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
12672                    if (invalidate) {
12673                        invalidate(left, top, right, bottom);
12674                    }
12675                }
12676
12677                if (drawVerticalScrollBar) {
12678                    int size = scrollBar.getSize(true);
12679                    if (size <= 0) {
12680                        size = cache.scrollBarSize;
12681                    }
12682
12683                    scrollBar.setParameters(computeVerticalScrollRange(),
12684                                            computeVerticalScrollOffset(),
12685                                            computeVerticalScrollExtent(), true);
12686                    int verticalScrollbarPosition = mVerticalScrollbarPosition;
12687                    if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
12688                        verticalScrollbarPosition = isLayoutRtl() ?
12689                                SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
12690                    }
12691                    switch (verticalScrollbarPosition) {
12692                        default:
12693                        case SCROLLBAR_POSITION_RIGHT:
12694                            left = scrollX + width - size - (mUserPaddingRight & inside);
12695                            break;
12696                        case SCROLLBAR_POSITION_LEFT:
12697                            left = scrollX + (mUserPaddingLeft & inside);
12698                            break;
12699                    }
12700                    top = scrollY + (mPaddingTop & inside);
12701                    right = left + size;
12702                    bottom = scrollY + height - (mUserPaddingBottom & inside);
12703                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
12704                    if (invalidate) {
12705                        invalidate(left, top, right, bottom);
12706                    }
12707                }
12708            }
12709        }
12710    }
12711
12712    /**
12713     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
12714     * FastScroller is visible.
12715     * @return whether to temporarily hide the vertical scrollbar
12716     * @hide
12717     */
12718    protected boolean isVerticalScrollBarHidden() {
12719        return false;
12720    }
12721
12722    /**
12723     * <p>Draw the horizontal scrollbar if
12724     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
12725     *
12726     * @param canvas the canvas on which to draw the scrollbar
12727     * @param scrollBar the scrollbar's drawable
12728     *
12729     * @see #isHorizontalScrollBarEnabled()
12730     * @see #computeHorizontalScrollRange()
12731     * @see #computeHorizontalScrollExtent()
12732     * @see #computeHorizontalScrollOffset()
12733     * @see android.widget.ScrollBarDrawable
12734     * @hide
12735     */
12736    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
12737            int l, int t, int r, int b) {
12738        scrollBar.setBounds(l, t, r, b);
12739        scrollBar.draw(canvas);
12740    }
12741
12742    /**
12743     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
12744     * returns true.</p>
12745     *
12746     * @param canvas the canvas on which to draw the scrollbar
12747     * @param scrollBar the scrollbar's drawable
12748     *
12749     * @see #isVerticalScrollBarEnabled()
12750     * @see #computeVerticalScrollRange()
12751     * @see #computeVerticalScrollExtent()
12752     * @see #computeVerticalScrollOffset()
12753     * @see android.widget.ScrollBarDrawable
12754     * @hide
12755     */
12756    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
12757            int l, int t, int r, int b) {
12758        scrollBar.setBounds(l, t, r, b);
12759        scrollBar.draw(canvas);
12760    }
12761
12762    /**
12763     * Implement this to do your drawing.
12764     *
12765     * @param canvas the canvas on which the background will be drawn
12766     */
12767    protected void onDraw(Canvas canvas) {
12768    }
12769
12770    /*
12771     * Caller is responsible for calling requestLayout if necessary.
12772     * (This allows addViewInLayout to not request a new layout.)
12773     */
12774    void assignParent(ViewParent parent) {
12775        if (mParent == null) {
12776            mParent = parent;
12777        } else if (parent == null) {
12778            mParent = null;
12779        } else {
12780            throw new RuntimeException("view " + this + " being added, but"
12781                    + " it already has a parent");
12782        }
12783    }
12784
12785    /**
12786     * This is called when the view is attached to a window.  At this point it
12787     * has a Surface and will start drawing.  Note that this function is
12788     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
12789     * however it may be called any time before the first onDraw -- including
12790     * before or after {@link #onMeasure(int, int)}.
12791     *
12792     * @see #onDetachedFromWindow()
12793     */
12794    protected void onAttachedToWindow() {
12795        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
12796            mParent.requestTransparentRegion(this);
12797        }
12798
12799        if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
12800            initialAwakenScrollBars();
12801            mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
12802        }
12803
12804        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
12805
12806        jumpDrawablesToCurrentState();
12807
12808        resetSubtreeAccessibilityStateChanged();
12809
12810        if (isFocused()) {
12811            InputMethodManager imm = InputMethodManager.peekInstance();
12812            imm.focusIn(this);
12813        }
12814    }
12815
12816    /**
12817     * Resolve all RTL related properties.
12818     *
12819     * @return true if resolution of RTL properties has been done
12820     *
12821     * @hide
12822     */
12823    public boolean resolveRtlPropertiesIfNeeded() {
12824        if (!needRtlPropertiesResolution()) return false;
12825
12826        // Order is important here: LayoutDirection MUST be resolved first
12827        if (!isLayoutDirectionResolved()) {
12828            resolveLayoutDirection();
12829            resolveLayoutParams();
12830        }
12831        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
12832        if (!isTextDirectionResolved()) {
12833            resolveTextDirection();
12834        }
12835        if (!isTextAlignmentResolved()) {
12836            resolveTextAlignment();
12837        }
12838        // Should resolve Drawables before Padding because we need the layout direction of the
12839        // Drawable to correctly resolve Padding.
12840        if (!isDrawablesResolved()) {
12841            resolveDrawables();
12842        }
12843        if (!isPaddingResolved()) {
12844            resolvePadding();
12845        }
12846        onRtlPropertiesChanged(getLayoutDirection());
12847        return true;
12848    }
12849
12850    /**
12851     * Reset resolution of all RTL related properties.
12852     *
12853     * @hide
12854     */
12855    public void resetRtlProperties() {
12856        resetResolvedLayoutDirection();
12857        resetResolvedTextDirection();
12858        resetResolvedTextAlignment();
12859        resetResolvedPadding();
12860        resetResolvedDrawables();
12861    }
12862
12863    /**
12864     * @see #onScreenStateChanged(int)
12865     */
12866    void dispatchScreenStateChanged(int screenState) {
12867        onScreenStateChanged(screenState);
12868    }
12869
12870    /**
12871     * This method is called whenever the state of the screen this view is
12872     * attached to changes. A state change will usually occurs when the screen
12873     * turns on or off (whether it happens automatically or the user does it
12874     * manually.)
12875     *
12876     * @param screenState The new state of the screen. Can be either
12877     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
12878     */
12879    public void onScreenStateChanged(int screenState) {
12880    }
12881
12882    /**
12883     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
12884     */
12885    private boolean hasRtlSupport() {
12886        return mContext.getApplicationInfo().hasRtlSupport();
12887    }
12888
12889    /**
12890     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
12891     * RTL not supported)
12892     */
12893    private boolean isRtlCompatibilityMode() {
12894        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
12895        return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport();
12896    }
12897
12898    /**
12899     * @return true if RTL properties need resolution.
12900     *
12901     */
12902    private boolean needRtlPropertiesResolution() {
12903        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
12904    }
12905
12906    /**
12907     * Called when any RTL property (layout direction or text direction or text alignment) has
12908     * been changed.
12909     *
12910     * Subclasses need to override this method to take care of cached information that depends on the
12911     * resolved layout direction, or to inform child views that inherit their layout direction.
12912     *
12913     * The default implementation does nothing.
12914     *
12915     * @param layoutDirection the direction of the layout
12916     *
12917     * @see #LAYOUT_DIRECTION_LTR
12918     * @see #LAYOUT_DIRECTION_RTL
12919     */
12920    public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) {
12921    }
12922
12923    /**
12924     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
12925     * that the parent directionality can and will be resolved before its children.
12926     *
12927     * @return true if resolution has been done, false otherwise.
12928     *
12929     * @hide
12930     */
12931    public boolean resolveLayoutDirection() {
12932        // Clear any previous layout direction resolution
12933        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
12934
12935        if (hasRtlSupport()) {
12936            // Set resolved depending on layout direction
12937            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
12938                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
12939                case LAYOUT_DIRECTION_INHERIT:
12940                    // We cannot resolve yet. LTR is by default and let the resolution happen again
12941                    // later to get the correct resolved value
12942                    if (!canResolveLayoutDirection()) return false;
12943
12944                    // Parent has not yet resolved, LTR is still the default
12945                    try {
12946                        if (!mParent.isLayoutDirectionResolved()) return false;
12947
12948                        if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
12949                            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12950                        }
12951                    } catch (AbstractMethodError e) {
12952                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
12953                                " does not fully implement ViewParent", e);
12954                    }
12955                    break;
12956                case LAYOUT_DIRECTION_RTL:
12957                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12958                    break;
12959                case LAYOUT_DIRECTION_LOCALE:
12960                    if((LAYOUT_DIRECTION_RTL ==
12961                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
12962                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12963                    }
12964                    break;
12965                default:
12966                    // Nothing to do, LTR by default
12967            }
12968        }
12969
12970        // Set to resolved
12971        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
12972        return true;
12973    }
12974
12975    /**
12976     * Check if layout direction resolution can be done.
12977     *
12978     * @return true if layout direction resolution can be done otherwise return false.
12979     */
12980    public boolean canResolveLayoutDirection() {
12981        switch (getRawLayoutDirection()) {
12982            case LAYOUT_DIRECTION_INHERIT:
12983                if (mParent != null) {
12984                    try {
12985                        return mParent.canResolveLayoutDirection();
12986                    } catch (AbstractMethodError e) {
12987                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
12988                                " does not fully implement ViewParent", e);
12989                    }
12990                }
12991                return false;
12992
12993            default:
12994                return true;
12995        }
12996    }
12997
12998    /**
12999     * Reset the resolved layout direction. Layout direction will be resolved during a call to
13000     * {@link #onMeasure(int, int)}.
13001     *
13002     * @hide
13003     */
13004    public void resetResolvedLayoutDirection() {
13005        // Reset the current resolved bits
13006        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
13007    }
13008
13009    /**
13010     * @return true if the layout direction is inherited.
13011     *
13012     * @hide
13013     */
13014    public boolean isLayoutDirectionInherited() {
13015        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
13016    }
13017
13018    /**
13019     * @return true if layout direction has been resolved.
13020     */
13021    public boolean isLayoutDirectionResolved() {
13022        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
13023    }
13024
13025    /**
13026     * Return if padding has been resolved
13027     *
13028     * @hide
13029     */
13030    boolean isPaddingResolved() {
13031        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
13032    }
13033
13034    /**
13035     * Resolves padding depending on layout direction, if applicable, and
13036     * recomputes internal padding values to adjust for scroll bars.
13037     *
13038     * @hide
13039     */
13040    public void resolvePadding() {
13041        final int resolvedLayoutDirection = getLayoutDirection();
13042
13043        if (!isRtlCompatibilityMode()) {
13044            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
13045            // If start / end padding are defined, they will be resolved (hence overriding) to
13046            // left / right or right / left depending on the resolved layout direction.
13047            // If start / end padding are not defined, use the left / right ones.
13048            if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) {
13049                Rect padding = sThreadLocal.get();
13050                if (padding == null) {
13051                    padding = new Rect();
13052                    sThreadLocal.set(padding);
13053                }
13054                mBackground.getPadding(padding);
13055                if (!mLeftPaddingDefined) {
13056                    mUserPaddingLeftInitial = padding.left;
13057                }
13058                if (!mRightPaddingDefined) {
13059                    mUserPaddingRightInitial = padding.right;
13060                }
13061            }
13062            switch (resolvedLayoutDirection) {
13063                case LAYOUT_DIRECTION_RTL:
13064                    if (mUserPaddingStart != UNDEFINED_PADDING) {
13065                        mUserPaddingRight = mUserPaddingStart;
13066                    } else {
13067                        mUserPaddingRight = mUserPaddingRightInitial;
13068                    }
13069                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
13070                        mUserPaddingLeft = mUserPaddingEnd;
13071                    } else {
13072                        mUserPaddingLeft = mUserPaddingLeftInitial;
13073                    }
13074                    break;
13075                case LAYOUT_DIRECTION_LTR:
13076                default:
13077                    if (mUserPaddingStart != UNDEFINED_PADDING) {
13078                        mUserPaddingLeft = mUserPaddingStart;
13079                    } else {
13080                        mUserPaddingLeft = mUserPaddingLeftInitial;
13081                    }
13082                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
13083                        mUserPaddingRight = mUserPaddingEnd;
13084                    } else {
13085                        mUserPaddingRight = mUserPaddingRightInitial;
13086                    }
13087            }
13088
13089            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
13090        }
13091
13092        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
13093        onRtlPropertiesChanged(resolvedLayoutDirection);
13094
13095        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
13096    }
13097
13098    /**
13099     * Reset the resolved layout direction.
13100     *
13101     * @hide
13102     */
13103    public void resetResolvedPadding() {
13104        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
13105    }
13106
13107    /**
13108     * This is called when the view is detached from a window.  At this point it
13109     * no longer has a surface for drawing.
13110     *
13111     * @see #onAttachedToWindow()
13112     */
13113    protected void onDetachedFromWindow() {
13114        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
13115        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
13116
13117        removeUnsetPressCallback();
13118        removeLongPressCallback();
13119        removePerformClickCallback();
13120        removeSendViewScrolledAccessibilityEventCallback();
13121
13122        destroyDrawingCache();
13123        destroyLayer(false);
13124
13125        cleanupDraw();
13126
13127        mCurrentAnimation = null;
13128    }
13129
13130    private void cleanupDraw() {
13131        resetDisplayList();
13132        mAttachInfo.mViewRootImpl.cancelInvalidate(this);
13133    }
13134
13135    /**
13136     * This method ensures the hardware renderer is in a valid state
13137     * before executing the specified action.
13138     *
13139     * This method will attempt to set a valid state even if the window
13140     * the renderer is attached to was destroyed.
13141     *
13142     * This method is not guaranteed to work. If the hardware renderer
13143     * does not exist or cannot be put in a valid state, this method
13144     * will not executed the specified action.
13145     *
13146     * The specified action is executed synchronously.
13147     *
13148     * @param action The action to execute after the renderer is in a valid state
13149     *
13150     * @return True if the specified Runnable was executed, false otherwise
13151     *
13152     * @hide
13153     */
13154    public boolean executeHardwareAction(Runnable action) {
13155        //noinspection SimplifiableIfStatement
13156        if (mAttachInfo != null && mAttachInfo.mHardwareRenderer != null) {
13157            return mAttachInfo.mHardwareRenderer.safelyRun(action);
13158        }
13159        return false;
13160    }
13161
13162    void invalidateInheritedLayoutMode(int layoutModeOfRoot) {
13163    }
13164
13165    /**
13166     * @return The number of times this view has been attached to a window
13167     */
13168    protected int getWindowAttachCount() {
13169        return mWindowAttachCount;
13170    }
13171
13172    /**
13173     * Retrieve a unique token identifying the window this view is attached to.
13174     * @return Return the window's token for use in
13175     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
13176     */
13177    public IBinder getWindowToken() {
13178        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
13179    }
13180
13181    /**
13182     * Retrieve the {@link WindowId} for the window this view is
13183     * currently attached to.
13184     */
13185    public WindowId getWindowId() {
13186        if (mAttachInfo == null) {
13187            return null;
13188        }
13189        if (mAttachInfo.mWindowId == null) {
13190            try {
13191                mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId(
13192                        mAttachInfo.mWindowToken);
13193                mAttachInfo.mWindowId = new WindowId(
13194                        mAttachInfo.mIWindowId);
13195            } catch (RemoteException e) {
13196            }
13197        }
13198        return mAttachInfo.mWindowId;
13199    }
13200
13201    /**
13202     * Retrieve a unique token identifying the top-level "real" window of
13203     * the window that this view is attached to.  That is, this is like
13204     * {@link #getWindowToken}, except if the window this view in is a panel
13205     * window (attached to another containing window), then the token of
13206     * the containing window is returned instead.
13207     *
13208     * @return Returns the associated window token, either
13209     * {@link #getWindowToken()} or the containing window's token.
13210     */
13211    public IBinder getApplicationWindowToken() {
13212        AttachInfo ai = mAttachInfo;
13213        if (ai != null) {
13214            IBinder appWindowToken = ai.mPanelParentWindowToken;
13215            if (appWindowToken == null) {
13216                appWindowToken = ai.mWindowToken;
13217            }
13218            return appWindowToken;
13219        }
13220        return null;
13221    }
13222
13223    /**
13224     * Gets the logical display to which the view's window has been attached.
13225     *
13226     * @return The logical display, or null if the view is not currently attached to a window.
13227     */
13228    public Display getDisplay() {
13229        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
13230    }
13231
13232    /**
13233     * Retrieve private session object this view hierarchy is using to
13234     * communicate with the window manager.
13235     * @return the session object to communicate with the window manager
13236     */
13237    /*package*/ IWindowSession getWindowSession() {
13238        return mAttachInfo != null ? mAttachInfo.mSession : null;
13239    }
13240
13241    /**
13242     * @param info the {@link android.view.View.AttachInfo} to associated with
13243     *        this view
13244     */
13245    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
13246        //System.out.println("Attached! " + this);
13247        mAttachInfo = info;
13248        if (mOverlay != null) {
13249            mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
13250        }
13251        mWindowAttachCount++;
13252        // We will need to evaluate the drawable state at least once.
13253        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
13254        if (mFloatingTreeObserver != null) {
13255            info.mTreeObserver.merge(mFloatingTreeObserver);
13256            mFloatingTreeObserver = null;
13257        }
13258        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
13259            mAttachInfo.mScrollContainers.add(this);
13260            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
13261        }
13262        performCollectViewAttributes(mAttachInfo, visibility);
13263        onAttachedToWindow();
13264
13265        ListenerInfo li = mListenerInfo;
13266        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
13267                li != null ? li.mOnAttachStateChangeListeners : null;
13268        if (listeners != null && listeners.size() > 0) {
13269            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
13270            // perform the dispatching. The iterator is a safe guard against listeners that
13271            // could mutate the list by calling the various add/remove methods. This prevents
13272            // the array from being modified while we iterate it.
13273            for (OnAttachStateChangeListener listener : listeners) {
13274                listener.onViewAttachedToWindow(this);
13275            }
13276        }
13277
13278        int vis = info.mWindowVisibility;
13279        if (vis != GONE) {
13280            onWindowVisibilityChanged(vis);
13281        }
13282        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
13283            // If nobody has evaluated the drawable state yet, then do it now.
13284            refreshDrawableState();
13285        }
13286        needGlobalAttributesUpdate(false);
13287    }
13288
13289    void dispatchDetachedFromWindow() {
13290        AttachInfo info = mAttachInfo;
13291        if (info != null) {
13292            int vis = info.mWindowVisibility;
13293            if (vis != GONE) {
13294                onWindowVisibilityChanged(GONE);
13295            }
13296        }
13297
13298        onDetachedFromWindow();
13299
13300        ListenerInfo li = mListenerInfo;
13301        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
13302                li != null ? li.mOnAttachStateChangeListeners : null;
13303        if (listeners != null && listeners.size() > 0) {
13304            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
13305            // perform the dispatching. The iterator is a safe guard against listeners that
13306            // could mutate the list by calling the various add/remove methods. This prevents
13307            // the array from being modified while we iterate it.
13308            for (OnAttachStateChangeListener listener : listeners) {
13309                listener.onViewDetachedFromWindow(this);
13310            }
13311        }
13312
13313        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
13314            mAttachInfo.mScrollContainers.remove(this);
13315            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
13316        }
13317
13318        mAttachInfo = null;
13319        if (mOverlay != null) {
13320            mOverlay.getOverlayView().dispatchDetachedFromWindow();
13321        }
13322    }
13323
13324    /**
13325     * Cancel any deferred high-level input events that were previously posted to the event queue.
13326     *
13327     * <p>Many views post high-level events such as click handlers to the event queue
13328     * to run deferred in order to preserve a desired user experience - clearing visible
13329     * pressed states before executing, etc. This method will abort any events of this nature
13330     * that are currently in flight.</p>
13331     *
13332     * <p>Custom views that generate their own high-level deferred input events should override
13333     * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p>
13334     *
13335     * <p>This will also cancel pending input events for any child views.</p>
13336     *
13337     * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases.
13338     * This will not impact newer events posted after this call that may occur as a result of
13339     * lower-level input events still waiting in the queue. If you are trying to prevent
13340     * double-submitted  events for the duration of some sort of asynchronous transaction
13341     * you should also take other steps to protect against unexpected double inputs e.g. calling
13342     * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when
13343     * the transaction completes, tracking already submitted transaction IDs, etc.</p>
13344     */
13345    public final void cancelPendingInputEvents() {
13346        dispatchCancelPendingInputEvents();
13347    }
13348
13349    /**
13350     * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight.
13351     * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling.
13352     */
13353    void dispatchCancelPendingInputEvents() {
13354        mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER;
13355        onCancelPendingInputEvents();
13356        if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) {
13357            throw new SuperNotCalledException("View " + getClass().getSimpleName() +
13358                    " did not call through to super.onCancelPendingInputEvents()");
13359        }
13360    }
13361
13362    /**
13363     * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or
13364     * a parent view.
13365     *
13366     * <p>This method is responsible for removing any pending high-level input events that were
13367     * posted to the event queue to run later. Custom view classes that post their own deferred
13368     * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or
13369     * {@link android.os.Handler} should override this method, call
13370     * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate.
13371     * </p>
13372     */
13373    public void onCancelPendingInputEvents() {
13374        removePerformClickCallback();
13375        cancelLongPress();
13376        mPrivateFlags3 |= PFLAG3_CALLED_SUPER;
13377    }
13378
13379    /**
13380     * Store this view hierarchy's frozen state into the given container.
13381     *
13382     * @param container The SparseArray in which to save the view's state.
13383     *
13384     * @see #restoreHierarchyState(android.util.SparseArray)
13385     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13386     * @see #onSaveInstanceState()
13387     */
13388    public void saveHierarchyState(SparseArray<Parcelable> container) {
13389        dispatchSaveInstanceState(container);
13390    }
13391
13392    /**
13393     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
13394     * this view and its children. May be overridden to modify how freezing happens to a
13395     * view's children; for example, some views may want to not store state for their children.
13396     *
13397     * @param container The SparseArray in which to save the view's state.
13398     *
13399     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13400     * @see #saveHierarchyState(android.util.SparseArray)
13401     * @see #onSaveInstanceState()
13402     */
13403    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
13404        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
13405            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
13406            Parcelable state = onSaveInstanceState();
13407            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
13408                throw new IllegalStateException(
13409                        "Derived class did not call super.onSaveInstanceState()");
13410            }
13411            if (state != null) {
13412                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
13413                // + ": " + state);
13414                container.put(mID, state);
13415            }
13416        }
13417    }
13418
13419    /**
13420     * Hook allowing a view to generate a representation of its internal state
13421     * that can later be used to create a new instance with that same state.
13422     * This state should only contain information that is not persistent or can
13423     * not be reconstructed later. For example, you will never store your
13424     * current position on screen because that will be computed again when a
13425     * new instance of the view is placed in its view hierarchy.
13426     * <p>
13427     * Some examples of things you may store here: the current cursor position
13428     * in a text view (but usually not the text itself since that is stored in a
13429     * content provider or other persistent storage), the currently selected
13430     * item in a list view.
13431     *
13432     * @return Returns a Parcelable object containing the view's current dynamic
13433     *         state, or null if there is nothing interesting to save. The
13434     *         default implementation returns null.
13435     * @see #onRestoreInstanceState(android.os.Parcelable)
13436     * @see #saveHierarchyState(android.util.SparseArray)
13437     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13438     * @see #setSaveEnabled(boolean)
13439     */
13440    protected Parcelable onSaveInstanceState() {
13441        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
13442        return BaseSavedState.EMPTY_STATE;
13443    }
13444
13445    /**
13446     * Restore this view hierarchy's frozen state from the given container.
13447     *
13448     * @param container The SparseArray which holds previously frozen states.
13449     *
13450     * @see #saveHierarchyState(android.util.SparseArray)
13451     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13452     * @see #onRestoreInstanceState(android.os.Parcelable)
13453     */
13454    public void restoreHierarchyState(SparseArray<Parcelable> container) {
13455        dispatchRestoreInstanceState(container);
13456    }
13457
13458    /**
13459     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
13460     * state for this view and its children. May be overridden to modify how restoring
13461     * happens to a view's children; for example, some views may want to not store state
13462     * for their children.
13463     *
13464     * @param container The SparseArray which holds previously saved state.
13465     *
13466     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13467     * @see #restoreHierarchyState(android.util.SparseArray)
13468     * @see #onRestoreInstanceState(android.os.Parcelable)
13469     */
13470    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
13471        if (mID != NO_ID) {
13472            Parcelable state = container.get(mID);
13473            if (state != null) {
13474                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
13475                // + ": " + state);
13476                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
13477                onRestoreInstanceState(state);
13478                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
13479                    throw new IllegalStateException(
13480                            "Derived class did not call super.onRestoreInstanceState()");
13481                }
13482            }
13483        }
13484    }
13485
13486    /**
13487     * Hook allowing a view to re-apply a representation of its internal state that had previously
13488     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
13489     * null state.
13490     *
13491     * @param state The frozen state that had previously been returned by
13492     *        {@link #onSaveInstanceState}.
13493     *
13494     * @see #onSaveInstanceState()
13495     * @see #restoreHierarchyState(android.util.SparseArray)
13496     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13497     */
13498    protected void onRestoreInstanceState(Parcelable state) {
13499        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
13500        if (state != BaseSavedState.EMPTY_STATE && state != null) {
13501            throw new IllegalArgumentException("Wrong state class, expecting View State but "
13502                    + "received " + state.getClass().toString() + " instead. This usually happens "
13503                    + "when two views of different type have the same id in the same hierarchy. "
13504                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
13505                    + "other views do not use the same id.");
13506        }
13507    }
13508
13509    /**
13510     * <p>Return the time at which the drawing of the view hierarchy started.</p>
13511     *
13512     * @return the drawing start time in milliseconds
13513     */
13514    public long getDrawingTime() {
13515        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
13516    }
13517
13518    /**
13519     * <p>Enables or disables the duplication of the parent's state into this view. When
13520     * duplication is enabled, this view gets its drawable state from its parent rather
13521     * than from its own internal properties.</p>
13522     *
13523     * <p>Note: in the current implementation, setting this property to true after the
13524     * view was added to a ViewGroup might have no effect at all. This property should
13525     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
13526     *
13527     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
13528     * property is enabled, an exception will be thrown.</p>
13529     *
13530     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
13531     * parent, these states should not be affected by this method.</p>
13532     *
13533     * @param enabled True to enable duplication of the parent's drawable state, false
13534     *                to disable it.
13535     *
13536     * @see #getDrawableState()
13537     * @see #isDuplicateParentStateEnabled()
13538     */
13539    public void setDuplicateParentStateEnabled(boolean enabled) {
13540        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
13541    }
13542
13543    /**
13544     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
13545     *
13546     * @return True if this view's drawable state is duplicated from the parent,
13547     *         false otherwise
13548     *
13549     * @see #getDrawableState()
13550     * @see #setDuplicateParentStateEnabled(boolean)
13551     */
13552    public boolean isDuplicateParentStateEnabled() {
13553        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
13554    }
13555
13556    /**
13557     * <p>Specifies the type of layer backing this view. The layer can be
13558     * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13559     * {@link #LAYER_TYPE_HARDWARE}.</p>
13560     *
13561     * <p>A layer is associated with an optional {@link android.graphics.Paint}
13562     * instance that controls how the layer is composed on screen. The following
13563     * properties of the paint are taken into account when composing the layer:</p>
13564     * <ul>
13565     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
13566     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
13567     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
13568     * </ul>
13569     *
13570     * <p>If this view has an alpha value set to < 1.0 by calling
13571     * {@link #setAlpha(float)}, the alpha value of the layer's paint is superceded
13572     * by this view's alpha value.</p>
13573     *
13574     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE},
13575     * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE}
13576     * for more information on when and how to use layers.</p>
13577     *
13578     * @param layerType The type of layer to use with this view, must be one of
13579     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13580     *        {@link #LAYER_TYPE_HARDWARE}
13581     * @param paint The paint used to compose the layer. This argument is optional
13582     *        and can be null. It is ignored when the layer type is
13583     *        {@link #LAYER_TYPE_NONE}
13584     *
13585     * @see #getLayerType()
13586     * @see #LAYER_TYPE_NONE
13587     * @see #LAYER_TYPE_SOFTWARE
13588     * @see #LAYER_TYPE_HARDWARE
13589     * @see #setAlpha(float)
13590     *
13591     * @attr ref android.R.styleable#View_layerType
13592     */
13593    public void setLayerType(int layerType, Paint paint) {
13594        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
13595            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
13596                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
13597        }
13598
13599        if (layerType == mLayerType) {
13600            if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) {
13601                mLayerPaint = paint == null ? new Paint() : paint;
13602                invalidateParentCaches();
13603                invalidate(true);
13604            }
13605            return;
13606        }
13607
13608        // Destroy any previous software drawing cache if needed
13609        switch (mLayerType) {
13610            case LAYER_TYPE_HARDWARE:
13611                destroyLayer(false);
13612                // fall through - non-accelerated views may use software layer mechanism instead
13613            case LAYER_TYPE_SOFTWARE:
13614                destroyDrawingCache();
13615                break;
13616            default:
13617                break;
13618        }
13619
13620        mLayerType = layerType;
13621        final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE;
13622        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
13623        mLocalDirtyRect = layerDisabled ? null : new Rect();
13624
13625        invalidateParentCaches();
13626        invalidate(true);
13627    }
13628
13629    /**
13630     * Updates the {@link Paint} object used with the current layer (used only if the current
13631     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
13632     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
13633     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
13634     * ensure that the view gets redrawn immediately.
13635     *
13636     * <p>A layer is associated with an optional {@link android.graphics.Paint}
13637     * instance that controls how the layer is composed on screen. The following
13638     * properties of the paint are taken into account when composing the layer:</p>
13639     * <ul>
13640     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
13641     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
13642     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
13643     * </ul>
13644     *
13645     * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the
13646     * alpha value of the layer's paint is superceded by this view's alpha value.</p>
13647     *
13648     * @param paint The paint used to compose the layer. This argument is optional
13649     *        and can be null. It is ignored when the layer type is
13650     *        {@link #LAYER_TYPE_NONE}
13651     *
13652     * @see #setLayerType(int, android.graphics.Paint)
13653     */
13654    public void setLayerPaint(Paint paint) {
13655        int layerType = getLayerType();
13656        if (layerType != LAYER_TYPE_NONE) {
13657            mLayerPaint = paint == null ? new Paint() : paint;
13658            if (layerType == LAYER_TYPE_HARDWARE) {
13659                HardwareLayer layer = getHardwareLayer();
13660                if (layer != null) {
13661                    layer.setLayerPaint(paint);
13662                }
13663                invalidateViewProperty(false, false);
13664            } else {
13665                invalidate();
13666            }
13667        }
13668    }
13669
13670    /**
13671     * Indicates whether this view has a static layer. A view with layer type
13672     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
13673     * dynamic.
13674     */
13675    boolean hasStaticLayer() {
13676        return true;
13677    }
13678
13679    /**
13680     * Indicates what type of layer is currently associated with this view. By default
13681     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
13682     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
13683     * for more information on the different types of layers.
13684     *
13685     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13686     *         {@link #LAYER_TYPE_HARDWARE}
13687     *
13688     * @see #setLayerType(int, android.graphics.Paint)
13689     * @see #buildLayer()
13690     * @see #LAYER_TYPE_NONE
13691     * @see #LAYER_TYPE_SOFTWARE
13692     * @see #LAYER_TYPE_HARDWARE
13693     */
13694    public int getLayerType() {
13695        return mLayerType;
13696    }
13697
13698    /**
13699     * Forces this view's layer to be created and this view to be rendered
13700     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
13701     * invoking this method will have no effect.
13702     *
13703     * This method can for instance be used to render a view into its layer before
13704     * starting an animation. If this view is complex, rendering into the layer
13705     * before starting the animation will avoid skipping frames.
13706     *
13707     * @throws IllegalStateException If this view is not attached to a window
13708     *
13709     * @see #setLayerType(int, android.graphics.Paint)
13710     */
13711    public void buildLayer() {
13712        if (mLayerType == LAYER_TYPE_NONE) return;
13713
13714        final AttachInfo attachInfo = mAttachInfo;
13715        if (attachInfo == null) {
13716            throw new IllegalStateException("This view must be attached to a window first");
13717        }
13718
13719        switch (mLayerType) {
13720            case LAYER_TYPE_HARDWARE:
13721                getHardwareLayer();
13722                // TODO: We need a better way to handle this case
13723                // If views have registered pre-draw listeners they need
13724                // to be notified before we build the layer. Those listeners
13725                // may however rely on other events to happen first so we
13726                // cannot just invoke them here until they don't cancel the
13727                // current frame
13728                if (!attachInfo.mTreeObserver.hasOnPreDrawListeners()) {
13729                    attachInfo.mViewRootImpl.dispatchFlushHardwareLayerUpdates();
13730                }
13731                break;
13732            case LAYER_TYPE_SOFTWARE:
13733                buildDrawingCache(true);
13734                break;
13735        }
13736    }
13737
13738    /**
13739     * <p>Returns a hardware layer that can be used to draw this view again
13740     * without executing its draw method.</p>
13741     *
13742     * @return A HardwareLayer ready to render, or null if an error occurred.
13743     */
13744    HardwareLayer getHardwareLayer() {
13745        if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null ||
13746                !mAttachInfo.mHardwareRenderer.isEnabled()) {
13747            return null;
13748        }
13749
13750        final int width = mRight - mLeft;
13751        final int height = mBottom - mTop;
13752
13753        if (width == 0 || height == 0) {
13754            return null;
13755        }
13756
13757        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
13758            if (mHardwareLayer == null) {
13759                mHardwareLayer = mAttachInfo.mHardwareRenderer.createDisplayListLayer(
13760                        width, height);
13761                mLocalDirtyRect.set(0, 0, width, height);
13762            } else if (mHardwareLayer.isValid()) {
13763                // This should not be necessary but applications that change
13764                // the parameters of their background drawable without calling
13765                // this.setBackground(Drawable) can leave the view in a bad state
13766                // (for instance isOpaque() returns true, but the background is
13767                // not opaque.)
13768                computeOpaqueFlags();
13769
13770                if (mHardwareLayer.prepare(width, height, isOpaque())) {
13771                    mLocalDirtyRect.set(0, 0, width, height);
13772                }
13773            }
13774
13775            // The layer is not valid if the underlying GPU resources cannot be allocated
13776            mHardwareLayer.flushChanges();
13777            if (!mHardwareLayer.isValid()) {
13778                return null;
13779            }
13780
13781            mHardwareLayer.setLayerPaint(mLayerPaint);
13782            DisplayList displayList = mHardwareLayer.startRecording();
13783            if (getDisplayList(displayList, true) != displayList) {
13784                throw new IllegalStateException("getDisplayList() didn't return"
13785                        + " the input displaylist for a hardware layer!");
13786            }
13787            mHardwareLayer.endRecording(mLocalDirtyRect);
13788            mLocalDirtyRect.setEmpty();
13789        }
13790
13791        return mHardwareLayer;
13792    }
13793
13794    /**
13795     * Destroys this View's hardware layer if possible.
13796     *
13797     * @return True if the layer was destroyed, false otherwise.
13798     *
13799     * @see #setLayerType(int, android.graphics.Paint)
13800     * @see #LAYER_TYPE_HARDWARE
13801     */
13802    boolean destroyLayer(boolean valid) {
13803        if (mHardwareLayer != null) {
13804            mHardwareLayer.destroy();
13805            mHardwareLayer = null;
13806
13807            invalidate(true);
13808            invalidateParentCaches();
13809            return true;
13810        }
13811        return false;
13812    }
13813
13814    /**
13815     * Destroys all hardware rendering resources. This method is invoked
13816     * when the system needs to reclaim resources. Upon execution of this
13817     * method, you should free any OpenGL resources created by the view.
13818     *
13819     * Note: you <strong>must</strong> call
13820     * <code>super.destroyHardwareResources()</code> when overriding
13821     * this method.
13822     *
13823     * @hide
13824     */
13825    protected void destroyHardwareResources() {
13826        resetDisplayList();
13827        destroyLayer(true);
13828    }
13829
13830    /**
13831     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
13832     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
13833     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
13834     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
13835     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
13836     * null.</p>
13837     *
13838     * <p>Enabling the drawing cache is similar to
13839     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
13840     * acceleration is turned off. When hardware acceleration is turned on, enabling the
13841     * drawing cache has no effect on rendering because the system uses a different mechanism
13842     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
13843     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
13844     * for information on how to enable software and hardware layers.</p>
13845     *
13846     * <p>This API can be used to manually generate
13847     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
13848     * {@link #getDrawingCache()}.</p>
13849     *
13850     * @param enabled true to enable the drawing cache, false otherwise
13851     *
13852     * @see #isDrawingCacheEnabled()
13853     * @see #getDrawingCache()
13854     * @see #buildDrawingCache()
13855     * @see #setLayerType(int, android.graphics.Paint)
13856     */
13857    public void setDrawingCacheEnabled(boolean enabled) {
13858        mCachingFailed = false;
13859        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
13860    }
13861
13862    /**
13863     * <p>Indicates whether the drawing cache is enabled for this view.</p>
13864     *
13865     * @return true if the drawing cache is enabled
13866     *
13867     * @see #setDrawingCacheEnabled(boolean)
13868     * @see #getDrawingCache()
13869     */
13870    @ViewDebug.ExportedProperty(category = "drawing")
13871    public boolean isDrawingCacheEnabled() {
13872        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
13873    }
13874
13875    /**
13876     * Debugging utility which recursively outputs the dirty state of a view and its
13877     * descendants.
13878     *
13879     * @hide
13880     */
13881    @SuppressWarnings({"UnusedDeclaration"})
13882    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
13883        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
13884                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
13885                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
13886                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
13887        if (clear) {
13888            mPrivateFlags &= clearMask;
13889        }
13890        if (this instanceof ViewGroup) {
13891            ViewGroup parent = (ViewGroup) this;
13892            final int count = parent.getChildCount();
13893            for (int i = 0; i < count; i++) {
13894                final View child = parent.getChildAt(i);
13895                child.outputDirtyFlags(indent + "  ", clear, clearMask);
13896            }
13897        }
13898    }
13899
13900    /**
13901     * This method is used by ViewGroup to cause its children to restore or recreate their
13902     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
13903     * to recreate its own display list, which would happen if it went through the normal
13904     * draw/dispatchDraw mechanisms.
13905     *
13906     * @hide
13907     */
13908    protected void dispatchGetDisplayList() {}
13909
13910    /**
13911     * A view that is not attached or hardware accelerated cannot create a display list.
13912     * This method checks these conditions and returns the appropriate result.
13913     *
13914     * @return true if view has the ability to create a display list, false otherwise.
13915     *
13916     * @hide
13917     */
13918    public boolean canHaveDisplayList() {
13919        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
13920    }
13921
13922    /**
13923     * Returns a DisplayList. If the incoming displayList is null, one will be created.
13924     * Otherwise, the same display list will be returned (after having been rendered into
13925     * along the way, depending on the invalidation state of the view).
13926     *
13927     * @param displayList The previous version of this displayList, could be null.
13928     * @param isLayer Whether the requester of the display list is a layer. If so,
13929     * the view will avoid creating a layer inside the resulting display list.
13930     * @return A new or reused DisplayList object.
13931     */
13932    private DisplayList getDisplayList(DisplayList displayList, boolean isLayer) {
13933        if (!canHaveDisplayList()) {
13934            return null;
13935        }
13936
13937        if (((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 ||
13938                displayList == null || !displayList.isValid() ||
13939                (!isLayer && mRecreateDisplayList))) {
13940            // Don't need to recreate the display list, just need to tell our
13941            // children to restore/recreate theirs
13942            if (displayList != null && displayList.isValid() &&
13943                    !isLayer && !mRecreateDisplayList) {
13944                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13945                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13946                dispatchGetDisplayList();
13947
13948                return displayList;
13949            }
13950
13951            if (!isLayer) {
13952                // If we got here, we're recreating it. Mark it as such to ensure that
13953                // we copy in child display lists into ours in drawChild()
13954                mRecreateDisplayList = true;
13955            }
13956            if (displayList == null) {
13957                displayList = DisplayList.create(getClass().getName());
13958                // If we're creating a new display list, make sure our parent gets invalidated
13959                // since they will need to recreate their display list to account for this
13960                // new child display list.
13961                invalidateParentCaches();
13962            }
13963
13964            boolean caching = false;
13965            int width = mRight - mLeft;
13966            int height = mBottom - mTop;
13967            int layerType = getLayerType();
13968
13969            final HardwareCanvas canvas = displayList.start(width, height);
13970
13971            try {
13972                if (!isLayer && layerType != LAYER_TYPE_NONE) {
13973                    if (layerType == LAYER_TYPE_HARDWARE) {
13974                        final HardwareLayer layer = getHardwareLayer();
13975                        if (layer != null && layer.isValid()) {
13976                            canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
13977                        } else {
13978                            canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint,
13979                                    Canvas.HAS_ALPHA_LAYER_SAVE_FLAG |
13980                                            Canvas.CLIP_TO_LAYER_SAVE_FLAG);
13981                        }
13982                        caching = true;
13983                    } else {
13984                        buildDrawingCache(true);
13985                        Bitmap cache = getDrawingCache(true);
13986                        if (cache != null) {
13987                            canvas.drawBitmap(cache, 0, 0, mLayerPaint);
13988                            caching = true;
13989                        }
13990                    }
13991                } else {
13992
13993                    computeScroll();
13994
13995                    canvas.translate(-mScrollX, -mScrollY);
13996                    if (!isLayer) {
13997                        mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13998                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13999                    }
14000
14001                    // Fast path for layouts with no backgrounds
14002                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14003                        dispatchDraw(canvas);
14004                        if (mOverlay != null && !mOverlay.isEmpty()) {
14005                            mOverlay.getOverlayView().draw(canvas);
14006                        }
14007                    } else {
14008                        draw(canvas);
14009                    }
14010                }
14011            } finally {
14012                displayList.end(getHardwareRenderer(), canvas);
14013                displayList.setCaching(caching);
14014                if (isLayer) {
14015                    displayList.setLeftTopRightBottom(0, 0, width, height);
14016                } else {
14017                    setDisplayListProperties(displayList);
14018                }
14019            }
14020        } else if (!isLayer) {
14021            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
14022            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14023        }
14024
14025        return displayList;
14026    }
14027
14028    /**
14029     * <p>Returns a display list that can be used to draw this view again
14030     * without executing its draw method.</p>
14031     *
14032     * @return A DisplayList ready to replay, or null if caching is not enabled.
14033     *
14034     * @hide
14035     */
14036    public DisplayList getDisplayList() {
14037        mDisplayList = getDisplayList(mDisplayList, false);
14038        return mDisplayList;
14039    }
14040
14041    private void resetDisplayList() {
14042        HardwareRenderer renderer = getHardwareRenderer();
14043        if (mDisplayList != null && mDisplayList.isValid()) {
14044            mDisplayList.destroyDisplayListData(renderer);
14045        }
14046
14047        if (mBackgroundDisplayList != null && mBackgroundDisplayList.isValid()) {
14048            mBackgroundDisplayList.destroyDisplayListData(renderer);
14049        }
14050    }
14051
14052    /**
14053     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
14054     *
14055     * @return A non-scaled bitmap representing this view or null if cache is disabled.
14056     *
14057     * @see #getDrawingCache(boolean)
14058     */
14059    public Bitmap getDrawingCache() {
14060        return getDrawingCache(false);
14061    }
14062
14063    /**
14064     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
14065     * is null when caching is disabled. If caching is enabled and the cache is not ready,
14066     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
14067     * draw from the cache when the cache is enabled. To benefit from the cache, you must
14068     * request the drawing cache by calling this method and draw it on screen if the
14069     * returned bitmap is not null.</p>
14070     *
14071     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
14072     * this method will create a bitmap of the same size as this view. Because this bitmap
14073     * will be drawn scaled by the parent ViewGroup, the result on screen might show
14074     * scaling artifacts. To avoid such artifacts, you should call this method by setting
14075     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
14076     * size than the view. This implies that your application must be able to handle this
14077     * size.</p>
14078     *
14079     * @param autoScale Indicates whether the generated bitmap should be scaled based on
14080     *        the current density of the screen when the application is in compatibility
14081     *        mode.
14082     *
14083     * @return A bitmap representing this view or null if cache is disabled.
14084     *
14085     * @see #setDrawingCacheEnabled(boolean)
14086     * @see #isDrawingCacheEnabled()
14087     * @see #buildDrawingCache(boolean)
14088     * @see #destroyDrawingCache()
14089     */
14090    public Bitmap getDrawingCache(boolean autoScale) {
14091        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
14092            return null;
14093        }
14094        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
14095            buildDrawingCache(autoScale);
14096        }
14097        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
14098    }
14099
14100    /**
14101     * <p>Frees the resources used by the drawing cache. If you call
14102     * {@link #buildDrawingCache()} manually without calling
14103     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
14104     * should cleanup the cache with this method afterwards.</p>
14105     *
14106     * @see #setDrawingCacheEnabled(boolean)
14107     * @see #buildDrawingCache()
14108     * @see #getDrawingCache()
14109     */
14110    public void destroyDrawingCache() {
14111        if (mDrawingCache != null) {
14112            mDrawingCache.recycle();
14113            mDrawingCache = null;
14114        }
14115        if (mUnscaledDrawingCache != null) {
14116            mUnscaledDrawingCache.recycle();
14117            mUnscaledDrawingCache = null;
14118        }
14119    }
14120
14121    /**
14122     * Setting a solid background color for the drawing cache's bitmaps will improve
14123     * performance and memory usage. Note, though that this should only be used if this
14124     * view will always be drawn on top of a solid color.
14125     *
14126     * @param color The background color to use for the drawing cache's bitmap
14127     *
14128     * @see #setDrawingCacheEnabled(boolean)
14129     * @see #buildDrawingCache()
14130     * @see #getDrawingCache()
14131     */
14132    public void setDrawingCacheBackgroundColor(int color) {
14133        if (color != mDrawingCacheBackgroundColor) {
14134            mDrawingCacheBackgroundColor = color;
14135            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
14136        }
14137    }
14138
14139    /**
14140     * @see #setDrawingCacheBackgroundColor(int)
14141     *
14142     * @return The background color to used for the drawing cache's bitmap
14143     */
14144    public int getDrawingCacheBackgroundColor() {
14145        return mDrawingCacheBackgroundColor;
14146    }
14147
14148    /**
14149     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
14150     *
14151     * @see #buildDrawingCache(boolean)
14152     */
14153    public void buildDrawingCache() {
14154        buildDrawingCache(false);
14155    }
14156
14157    /**
14158     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
14159     *
14160     * <p>If you call {@link #buildDrawingCache()} manually without calling
14161     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
14162     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
14163     *
14164     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
14165     * this method will create a bitmap of the same size as this view. Because this bitmap
14166     * will be drawn scaled by the parent ViewGroup, the result on screen might show
14167     * scaling artifacts. To avoid such artifacts, you should call this method by setting
14168     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
14169     * size than the view. This implies that your application must be able to handle this
14170     * size.</p>
14171     *
14172     * <p>You should avoid calling this method when hardware acceleration is enabled. If
14173     * you do not need the drawing cache bitmap, calling this method will increase memory
14174     * usage and cause the view to be rendered in software once, thus negatively impacting
14175     * performance.</p>
14176     *
14177     * @see #getDrawingCache()
14178     * @see #destroyDrawingCache()
14179     */
14180    public void buildDrawingCache(boolean autoScale) {
14181        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
14182                mDrawingCache == null : mUnscaledDrawingCache == null)) {
14183            mCachingFailed = false;
14184
14185            int width = mRight - mLeft;
14186            int height = mBottom - mTop;
14187
14188            final AttachInfo attachInfo = mAttachInfo;
14189            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
14190
14191            if (autoScale && scalingRequired) {
14192                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
14193                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
14194            }
14195
14196            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
14197            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
14198            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
14199
14200            final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
14201            final long drawingCacheSize =
14202                    ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
14203            if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
14204                if (width > 0 && height > 0) {
14205                    Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs "
14206                            + projectedBitmapSize + " bytes, only "
14207                            + drawingCacheSize + " available");
14208                }
14209                destroyDrawingCache();
14210                mCachingFailed = true;
14211                return;
14212            }
14213
14214            boolean clear = true;
14215            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
14216
14217            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
14218                Bitmap.Config quality;
14219                if (!opaque) {
14220                    // Never pick ARGB_4444 because it looks awful
14221                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
14222                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
14223                        case DRAWING_CACHE_QUALITY_AUTO:
14224                        case DRAWING_CACHE_QUALITY_LOW:
14225                        case DRAWING_CACHE_QUALITY_HIGH:
14226                        default:
14227                            quality = Bitmap.Config.ARGB_8888;
14228                            break;
14229                    }
14230                } else {
14231                    // Optimization for translucent windows
14232                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
14233                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
14234                }
14235
14236                // Try to cleanup memory
14237                if (bitmap != null) bitmap.recycle();
14238
14239                try {
14240                    bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
14241                            width, height, quality);
14242                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
14243                    if (autoScale) {
14244                        mDrawingCache = bitmap;
14245                    } else {
14246                        mUnscaledDrawingCache = bitmap;
14247                    }
14248                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
14249                } catch (OutOfMemoryError e) {
14250                    // If there is not enough memory to create the bitmap cache, just
14251                    // ignore the issue as bitmap caches are not required to draw the
14252                    // view hierarchy
14253                    if (autoScale) {
14254                        mDrawingCache = null;
14255                    } else {
14256                        mUnscaledDrawingCache = null;
14257                    }
14258                    mCachingFailed = true;
14259                    return;
14260                }
14261
14262                clear = drawingCacheBackgroundColor != 0;
14263            }
14264
14265            Canvas canvas;
14266            if (attachInfo != null) {
14267                canvas = attachInfo.mCanvas;
14268                if (canvas == null) {
14269                    canvas = new Canvas();
14270                }
14271                canvas.setBitmap(bitmap);
14272                // Temporarily clobber the cached Canvas in case one of our children
14273                // is also using a drawing cache. Without this, the children would
14274                // steal the canvas by attaching their own bitmap to it and bad, bad
14275                // thing would happen (invisible views, corrupted drawings, etc.)
14276                attachInfo.mCanvas = null;
14277            } else {
14278                // This case should hopefully never or seldom happen
14279                canvas = new Canvas(bitmap);
14280            }
14281
14282            if (clear) {
14283                bitmap.eraseColor(drawingCacheBackgroundColor);
14284            }
14285
14286            computeScroll();
14287            final int restoreCount = canvas.save();
14288
14289            if (autoScale && scalingRequired) {
14290                final float scale = attachInfo.mApplicationScale;
14291                canvas.scale(scale, scale);
14292            }
14293
14294            canvas.translate(-mScrollX, -mScrollY);
14295
14296            mPrivateFlags |= PFLAG_DRAWN;
14297            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
14298                    mLayerType != LAYER_TYPE_NONE) {
14299                mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
14300            }
14301
14302            // Fast path for layouts with no backgrounds
14303            if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14304                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14305                dispatchDraw(canvas);
14306                if (mOverlay != null && !mOverlay.isEmpty()) {
14307                    mOverlay.getOverlayView().draw(canvas);
14308                }
14309            } else {
14310                draw(canvas);
14311            }
14312
14313            canvas.restoreToCount(restoreCount);
14314            canvas.setBitmap(null);
14315
14316            if (attachInfo != null) {
14317                // Restore the cached Canvas for our siblings
14318                attachInfo.mCanvas = canvas;
14319            }
14320        }
14321    }
14322
14323    /**
14324     * Create a snapshot of the view into a bitmap.  We should probably make
14325     * some form of this public, but should think about the API.
14326     */
14327    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
14328        int width = mRight - mLeft;
14329        int height = mBottom - mTop;
14330
14331        final AttachInfo attachInfo = mAttachInfo;
14332        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
14333        width = (int) ((width * scale) + 0.5f);
14334        height = (int) ((height * scale) + 0.5f);
14335
14336        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
14337                width > 0 ? width : 1, height > 0 ? height : 1, quality);
14338        if (bitmap == null) {
14339            throw new OutOfMemoryError();
14340        }
14341
14342        Resources resources = getResources();
14343        if (resources != null) {
14344            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
14345        }
14346
14347        Canvas canvas;
14348        if (attachInfo != null) {
14349            canvas = attachInfo.mCanvas;
14350            if (canvas == null) {
14351                canvas = new Canvas();
14352            }
14353            canvas.setBitmap(bitmap);
14354            // Temporarily clobber the cached Canvas in case one of our children
14355            // is also using a drawing cache. Without this, the children would
14356            // steal the canvas by attaching their own bitmap to it and bad, bad
14357            // things would happen (invisible views, corrupted drawings, etc.)
14358            attachInfo.mCanvas = null;
14359        } else {
14360            // This case should hopefully never or seldom happen
14361            canvas = new Canvas(bitmap);
14362        }
14363
14364        if ((backgroundColor & 0xff000000) != 0) {
14365            bitmap.eraseColor(backgroundColor);
14366        }
14367
14368        computeScroll();
14369        final int restoreCount = canvas.save();
14370        canvas.scale(scale, scale);
14371        canvas.translate(-mScrollX, -mScrollY);
14372
14373        // Temporarily remove the dirty mask
14374        int flags = mPrivateFlags;
14375        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14376
14377        // Fast path for layouts with no backgrounds
14378        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14379            dispatchDraw(canvas);
14380            if (mOverlay != null && !mOverlay.isEmpty()) {
14381                mOverlay.getOverlayView().draw(canvas);
14382            }
14383        } else {
14384            draw(canvas);
14385        }
14386
14387        mPrivateFlags = flags;
14388
14389        canvas.restoreToCount(restoreCount);
14390        canvas.setBitmap(null);
14391
14392        if (attachInfo != null) {
14393            // Restore the cached Canvas for our siblings
14394            attachInfo.mCanvas = canvas;
14395        }
14396
14397        return bitmap;
14398    }
14399
14400    /**
14401     * Indicates whether this View is currently in edit mode. A View is usually
14402     * in edit mode when displayed within a developer tool. For instance, if
14403     * this View is being drawn by a visual user interface builder, this method
14404     * should return true.
14405     *
14406     * Subclasses should check the return value of this method to provide
14407     * different behaviors if their normal behavior might interfere with the
14408     * host environment. For instance: the class spawns a thread in its
14409     * constructor, the drawing code relies on device-specific features, etc.
14410     *
14411     * This method is usually checked in the drawing code of custom widgets.
14412     *
14413     * @return True if this View is in edit mode, false otherwise.
14414     */
14415    public boolean isInEditMode() {
14416        return false;
14417    }
14418
14419    /**
14420     * If the View draws content inside its padding and enables fading edges,
14421     * it needs to support padding offsets. Padding offsets are added to the
14422     * fading edges to extend the length of the fade so that it covers pixels
14423     * drawn inside the padding.
14424     *
14425     * Subclasses of this class should override this method if they need
14426     * to draw content inside the padding.
14427     *
14428     * @return True if padding offset must be applied, false otherwise.
14429     *
14430     * @see #getLeftPaddingOffset()
14431     * @see #getRightPaddingOffset()
14432     * @see #getTopPaddingOffset()
14433     * @see #getBottomPaddingOffset()
14434     *
14435     * @since CURRENT
14436     */
14437    protected boolean isPaddingOffsetRequired() {
14438        return false;
14439    }
14440
14441    /**
14442     * Amount by which to extend the left fading region. Called only when
14443     * {@link #isPaddingOffsetRequired()} returns true.
14444     *
14445     * @return The left padding offset in pixels.
14446     *
14447     * @see #isPaddingOffsetRequired()
14448     *
14449     * @since CURRENT
14450     */
14451    protected int getLeftPaddingOffset() {
14452        return 0;
14453    }
14454
14455    /**
14456     * Amount by which to extend the right fading region. Called only when
14457     * {@link #isPaddingOffsetRequired()} returns true.
14458     *
14459     * @return The right padding offset in pixels.
14460     *
14461     * @see #isPaddingOffsetRequired()
14462     *
14463     * @since CURRENT
14464     */
14465    protected int getRightPaddingOffset() {
14466        return 0;
14467    }
14468
14469    /**
14470     * Amount by which to extend the top fading region. Called only when
14471     * {@link #isPaddingOffsetRequired()} returns true.
14472     *
14473     * @return The top padding offset in pixels.
14474     *
14475     * @see #isPaddingOffsetRequired()
14476     *
14477     * @since CURRENT
14478     */
14479    protected int getTopPaddingOffset() {
14480        return 0;
14481    }
14482
14483    /**
14484     * Amount by which to extend the bottom fading region. Called only when
14485     * {@link #isPaddingOffsetRequired()} returns true.
14486     *
14487     * @return The bottom padding offset in pixels.
14488     *
14489     * @see #isPaddingOffsetRequired()
14490     *
14491     * @since CURRENT
14492     */
14493    protected int getBottomPaddingOffset() {
14494        return 0;
14495    }
14496
14497    /**
14498     * @hide
14499     * @param offsetRequired
14500     */
14501    protected int getFadeTop(boolean offsetRequired) {
14502        int top = mPaddingTop;
14503        if (offsetRequired) top += getTopPaddingOffset();
14504        return top;
14505    }
14506
14507    /**
14508     * @hide
14509     * @param offsetRequired
14510     */
14511    protected int getFadeHeight(boolean offsetRequired) {
14512        int padding = mPaddingTop;
14513        if (offsetRequired) padding += getTopPaddingOffset();
14514        return mBottom - mTop - mPaddingBottom - padding;
14515    }
14516
14517    /**
14518     * <p>Indicates whether this view is attached to a hardware accelerated
14519     * window or not.</p>
14520     *
14521     * <p>Even if this method returns true, it does not mean that every call
14522     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
14523     * accelerated {@link android.graphics.Canvas}. For instance, if this view
14524     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
14525     * window is hardware accelerated,
14526     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
14527     * return false, and this method will return true.</p>
14528     *
14529     * @return True if the view is attached to a window and the window is
14530     *         hardware accelerated; false in any other case.
14531     */
14532    public boolean isHardwareAccelerated() {
14533        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
14534    }
14535
14536    /**
14537     * Sets a rectangular area on this view to which the view will be clipped
14538     * when it is drawn. Setting the value to null will remove the clip bounds
14539     * and the view will draw normally, using its full bounds.
14540     *
14541     * @param clipBounds The rectangular area, in the local coordinates of
14542     * this view, to which future drawing operations will be clipped.
14543     */
14544    public void setClipBounds(Rect clipBounds) {
14545        if (clipBounds != null) {
14546            if (clipBounds.equals(mClipBounds)) {
14547                return;
14548            }
14549            if (mClipBounds == null) {
14550                invalidate();
14551                mClipBounds = new Rect(clipBounds);
14552            } else {
14553                invalidate(Math.min(mClipBounds.left, clipBounds.left),
14554                        Math.min(mClipBounds.top, clipBounds.top),
14555                        Math.max(mClipBounds.right, clipBounds.right),
14556                        Math.max(mClipBounds.bottom, clipBounds.bottom));
14557                mClipBounds.set(clipBounds);
14558            }
14559        } else {
14560            if (mClipBounds != null) {
14561                invalidate();
14562                mClipBounds = null;
14563            }
14564        }
14565    }
14566
14567    /**
14568     * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}.
14569     *
14570     * @return A copy of the current clip bounds if clip bounds are set,
14571     * otherwise null.
14572     */
14573    public Rect getClipBounds() {
14574        return (mClipBounds != null) ? new Rect(mClipBounds) : null;
14575    }
14576
14577    /**
14578     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
14579     * case of an active Animation being run on the view.
14580     */
14581    private boolean drawAnimation(ViewGroup parent, long drawingTime,
14582            Animation a, boolean scalingRequired) {
14583        Transformation invalidationTransform;
14584        final int flags = parent.mGroupFlags;
14585        final boolean initialized = a.isInitialized();
14586        if (!initialized) {
14587            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
14588            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
14589            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
14590            onAnimationStart();
14591        }
14592
14593        final Transformation t = parent.getChildTransformation();
14594        boolean more = a.getTransformation(drawingTime, t, 1f);
14595        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
14596            if (parent.mInvalidationTransformation == null) {
14597                parent.mInvalidationTransformation = new Transformation();
14598            }
14599            invalidationTransform = parent.mInvalidationTransformation;
14600            a.getTransformation(drawingTime, invalidationTransform, 1f);
14601        } else {
14602            invalidationTransform = t;
14603        }
14604
14605        if (more) {
14606            if (!a.willChangeBounds()) {
14607                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
14608                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
14609                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
14610                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
14611                    // The child need to draw an animation, potentially offscreen, so
14612                    // make sure we do not cancel invalidate requests
14613                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
14614                    parent.invalidate(mLeft, mTop, mRight, mBottom);
14615                }
14616            } else {
14617                if (parent.mInvalidateRegion == null) {
14618                    parent.mInvalidateRegion = new RectF();
14619                }
14620                final RectF region = parent.mInvalidateRegion;
14621                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
14622                        invalidationTransform);
14623
14624                // The child need to draw an animation, potentially offscreen, so
14625                // make sure we do not cancel invalidate requests
14626                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
14627
14628                final int left = mLeft + (int) region.left;
14629                final int top = mTop + (int) region.top;
14630                parent.invalidate(left, top, left + (int) (region.width() + .5f),
14631                        top + (int) (region.height() + .5f));
14632            }
14633        }
14634        return more;
14635    }
14636
14637    /**
14638     * This method is called by getDisplayList() when a display list is created or re-rendered.
14639     * It sets or resets the current value of all properties on that display list (resetting is
14640     * necessary when a display list is being re-created, because we need to make sure that
14641     * previously-set transform values
14642     */
14643    void setDisplayListProperties(DisplayList displayList) {
14644        if (displayList != null) {
14645            displayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
14646            displayList.setHasOverlappingRendering(hasOverlappingRendering());
14647            if (mParent instanceof ViewGroup) {
14648                displayList.setClipToBounds(
14649                        (((ViewGroup) mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0);
14650            }
14651            if (this instanceof ViewGroup) {
14652                displayList.setIsolatedZVolume(
14653                        (((ViewGroup) this).mGroupFlags & ViewGroup.FLAG_ISOLATED_Z_VOLUME) != 0);
14654            }
14655            displayList.setOutline(mOutline);
14656            displayList.setClipToOutline(getClipToOutline());
14657            displayList.setCastsShadow(getCastsShadow());
14658            displayList.setUsesGlobalCamera(getUsesGlobalCamera());
14659            float alpha = 1;
14660            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
14661                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
14662                ViewGroup parentVG = (ViewGroup) mParent;
14663                final Transformation t = parentVG.getChildTransformation();
14664                if (parentVG.getChildStaticTransformation(this, t)) {
14665                    final int transformType = t.getTransformationType();
14666                    if (transformType != Transformation.TYPE_IDENTITY) {
14667                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
14668                            alpha = t.getAlpha();
14669                        }
14670                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
14671                            displayList.setStaticMatrix(t.getMatrix());
14672                        }
14673                    }
14674                }
14675            }
14676            if (mTransformationInfo != null) {
14677                alpha *= getFinalAlpha();
14678                if (alpha < 1) {
14679                    final int multipliedAlpha = (int) (255 * alpha);
14680                    if (onSetAlpha(multipliedAlpha)) {
14681                        alpha = 1;
14682                    }
14683                }
14684                displayList.setTransformationInfo(alpha,
14685                        mTransformationInfo.mTranslationX, mTransformationInfo.mTranslationY,
14686                        mTransformationInfo.mTranslationZ,
14687                        mTransformationInfo.mRotation, mTransformationInfo.mRotationX,
14688                        mTransformationInfo.mRotationY, mTransformationInfo.mScaleX,
14689                        mTransformationInfo.mScaleY);
14690                if (mTransformationInfo.mCamera == null) {
14691                    mTransformationInfo.mCamera = new Camera();
14692                    mTransformationInfo.matrix3D = new Matrix();
14693                }
14694                displayList.setCameraDistance(mTransformationInfo.mCamera.getLocationZ());
14695                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == PFLAG_PIVOT_EXPLICITLY_SET) {
14696                    displayList.setPivotX(getPivotX());
14697                    displayList.setPivotY(getPivotY());
14698                }
14699            } else if (alpha < 1) {
14700                displayList.setAlpha(alpha);
14701            }
14702        }
14703    }
14704
14705    /**
14706     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
14707     * This draw() method is an implementation detail and is not intended to be overridden or
14708     * to be called from anywhere else other than ViewGroup.drawChild().
14709     */
14710    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
14711        boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
14712        boolean more = false;
14713        final boolean childHasIdentityMatrix = hasIdentityMatrix();
14714        final int flags = parent.mGroupFlags;
14715
14716        if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) {
14717            parent.getChildTransformation().clear();
14718            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14719        }
14720
14721        Transformation transformToApply = null;
14722        boolean concatMatrix = false;
14723
14724        boolean scalingRequired = false;
14725        boolean caching;
14726        int layerType = getLayerType();
14727
14728        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
14729        if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 ||
14730                (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) {
14731            caching = true;
14732            // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList
14733            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
14734        } else {
14735            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
14736        }
14737
14738        final Animation a = getAnimation();
14739        if (a != null) {
14740            more = drawAnimation(parent, drawingTime, a, scalingRequired);
14741            concatMatrix = a.willChangeTransformationMatrix();
14742            if (concatMatrix) {
14743                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
14744            }
14745            transformToApply = parent.getChildTransformation();
14746        } else {
14747            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) ==
14748                    PFLAG3_VIEW_IS_ANIMATING_TRANSFORM && mDisplayList != null) {
14749                // No longer animating: clear out old animation matrix
14750                mDisplayList.setAnimationMatrix(null);
14751                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
14752            }
14753            if (!useDisplayListProperties &&
14754                    (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
14755                final Transformation t = parent.getChildTransformation();
14756                final boolean hasTransform = parent.getChildStaticTransformation(this, t);
14757                if (hasTransform) {
14758                    final int transformType = t.getTransformationType();
14759                    transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null;
14760                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
14761                }
14762            }
14763        }
14764
14765        concatMatrix |= !childHasIdentityMatrix;
14766
14767        // Sets the flag as early as possible to allow draw() implementations
14768        // to call invalidate() successfully when doing animations
14769        mPrivateFlags |= PFLAG_DRAWN;
14770
14771        if (!concatMatrix &&
14772                (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
14773                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
14774                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
14775                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
14776            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
14777            return more;
14778        }
14779        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
14780
14781        if (hardwareAccelerated) {
14782            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
14783            // retain the flag's value temporarily in the mRecreateDisplayList flag
14784            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED;
14785            mPrivateFlags &= ~PFLAG_INVALIDATED;
14786        }
14787
14788        DisplayList displayList = null;
14789        Bitmap cache = null;
14790        boolean hasDisplayList = false;
14791        if (caching) {
14792            if (!hardwareAccelerated) {
14793                if (layerType != LAYER_TYPE_NONE) {
14794                    layerType = LAYER_TYPE_SOFTWARE;
14795                    buildDrawingCache(true);
14796                }
14797                cache = getDrawingCache(true);
14798            } else {
14799                switch (layerType) {
14800                    case LAYER_TYPE_SOFTWARE:
14801                        if (useDisplayListProperties) {
14802                            hasDisplayList = canHaveDisplayList();
14803                        } else {
14804                            buildDrawingCache(true);
14805                            cache = getDrawingCache(true);
14806                        }
14807                        break;
14808                    case LAYER_TYPE_HARDWARE:
14809                        if (useDisplayListProperties) {
14810                            hasDisplayList = canHaveDisplayList();
14811                        }
14812                        break;
14813                    case LAYER_TYPE_NONE:
14814                        // Delay getting the display list until animation-driven alpha values are
14815                        // set up and possibly passed on to the view
14816                        hasDisplayList = canHaveDisplayList();
14817                        break;
14818                }
14819            }
14820        }
14821        useDisplayListProperties &= hasDisplayList;
14822        if (useDisplayListProperties) {
14823            displayList = getDisplayList();
14824            if (!displayList.isValid()) {
14825                // Uncommon, but possible. If a view is removed from the hierarchy during the call
14826                // to getDisplayList(), the display list will be marked invalid and we should not
14827                // try to use it again.
14828                displayList = null;
14829                hasDisplayList = false;
14830                useDisplayListProperties = false;
14831            }
14832        }
14833
14834        int sx = 0;
14835        int sy = 0;
14836        if (!hasDisplayList) {
14837            computeScroll();
14838            sx = mScrollX;
14839            sy = mScrollY;
14840        }
14841
14842        final boolean hasNoCache = cache == null || hasDisplayList;
14843        final boolean offsetForScroll = cache == null && !hasDisplayList &&
14844                layerType != LAYER_TYPE_HARDWARE;
14845
14846        int restoreTo = -1;
14847        if (!useDisplayListProperties || transformToApply != null) {
14848            restoreTo = canvas.save();
14849        }
14850        if (offsetForScroll) {
14851            canvas.translate(mLeft - sx, mTop - sy);
14852        } else {
14853            if (!useDisplayListProperties) {
14854                canvas.translate(mLeft, mTop);
14855            }
14856            if (scalingRequired) {
14857                if (useDisplayListProperties) {
14858                    // TODO: Might not need this if we put everything inside the DL
14859                    restoreTo = canvas.save();
14860                }
14861                // mAttachInfo cannot be null, otherwise scalingRequired == false
14862                final float scale = 1.0f / mAttachInfo.mApplicationScale;
14863                canvas.scale(scale, scale);
14864            }
14865        }
14866
14867        float alpha = useDisplayListProperties ? 1 : (getAlpha() * getTransitionAlpha());
14868        if (transformToApply != null || alpha < 1 ||  !hasIdentityMatrix() ||
14869                (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
14870            if (transformToApply != null || !childHasIdentityMatrix) {
14871                int transX = 0;
14872                int transY = 0;
14873
14874                if (offsetForScroll) {
14875                    transX = -sx;
14876                    transY = -sy;
14877                }
14878
14879                if (transformToApply != null) {
14880                    if (concatMatrix) {
14881                        if (useDisplayListProperties) {
14882                            displayList.setAnimationMatrix(transformToApply.getMatrix());
14883                        } else {
14884                            // Undo the scroll translation, apply the transformation matrix,
14885                            // then redo the scroll translate to get the correct result.
14886                            canvas.translate(-transX, -transY);
14887                            canvas.concat(transformToApply.getMatrix());
14888                            canvas.translate(transX, transY);
14889                        }
14890                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14891                    }
14892
14893                    float transformAlpha = transformToApply.getAlpha();
14894                    if (transformAlpha < 1) {
14895                        alpha *= transformAlpha;
14896                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14897                    }
14898                }
14899
14900                if (!childHasIdentityMatrix && !useDisplayListProperties) {
14901                    canvas.translate(-transX, -transY);
14902                    canvas.concat(getMatrix());
14903                    canvas.translate(transX, transY);
14904                }
14905            }
14906
14907            // Deal with alpha if it is or used to be <1
14908            if (alpha < 1 ||
14909                    (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
14910                if (alpha < 1) {
14911                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
14912                } else {
14913                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
14914                }
14915                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14916                if (hasNoCache) {
14917                    final int multipliedAlpha = (int) (255 * alpha);
14918                    if (!onSetAlpha(multipliedAlpha)) {
14919                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
14920                        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 ||
14921                                layerType != LAYER_TYPE_NONE) {
14922                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
14923                        }
14924                        if (useDisplayListProperties) {
14925                            displayList.setAlpha(alpha * getAlpha() * getTransitionAlpha());
14926                        } else  if (layerType == LAYER_TYPE_NONE) {
14927                            final int scrollX = hasDisplayList ? 0 : sx;
14928                            final int scrollY = hasDisplayList ? 0 : sy;
14929                            canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft,
14930                                    scrollY + mBottom - mTop, multipliedAlpha, layerFlags);
14931                        }
14932                    } else {
14933                        // Alpha is handled by the child directly, clobber the layer's alpha
14934                        mPrivateFlags |= PFLAG_ALPHA_SET;
14935                    }
14936                }
14937            }
14938        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
14939            onSetAlpha(255);
14940            mPrivateFlags &= ~PFLAG_ALPHA_SET;
14941        }
14942
14943        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN &&
14944                !useDisplayListProperties && cache == null) {
14945            if (offsetForScroll) {
14946                canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
14947            } else {
14948                if (!scalingRequired || cache == null) {
14949                    canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
14950                } else {
14951                    canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
14952                }
14953            }
14954        }
14955
14956        if (!useDisplayListProperties && hasDisplayList) {
14957            displayList = getDisplayList();
14958            if (!displayList.isValid()) {
14959                // Uncommon, but possible. If a view is removed from the hierarchy during the call
14960                // to getDisplayList(), the display list will be marked invalid and we should not
14961                // try to use it again.
14962                displayList = null;
14963                hasDisplayList = false;
14964            }
14965        }
14966
14967        if (hasNoCache) {
14968            boolean layerRendered = false;
14969            if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) {
14970                final HardwareLayer layer = getHardwareLayer();
14971                if (layer != null && layer.isValid()) {
14972                    mLayerPaint.setAlpha((int) (alpha * 255));
14973                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
14974                    layerRendered = true;
14975                } else {
14976                    final int scrollX = hasDisplayList ? 0 : sx;
14977                    final int scrollY = hasDisplayList ? 0 : sy;
14978                    canvas.saveLayer(scrollX, scrollY,
14979                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
14980                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
14981                }
14982            }
14983
14984            if (!layerRendered) {
14985                if (!hasDisplayList) {
14986                    // Fast path for layouts with no backgrounds
14987                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14988                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14989                        dispatchDraw(canvas);
14990                    } else {
14991                        draw(canvas);
14992                    }
14993                } else {
14994                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14995                    ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags);
14996                }
14997            }
14998        } else if (cache != null) {
14999            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
15000            Paint cachePaint;
15001
15002            if (layerType == LAYER_TYPE_NONE) {
15003                cachePaint = parent.mCachePaint;
15004                if (cachePaint == null) {
15005                    cachePaint = new Paint();
15006                    cachePaint.setDither(false);
15007                    parent.mCachePaint = cachePaint;
15008                }
15009                if (alpha < 1) {
15010                    cachePaint.setAlpha((int) (alpha * 255));
15011                    parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
15012                } else if  ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) {
15013                    cachePaint.setAlpha(255);
15014                    parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
15015                }
15016            } else {
15017                cachePaint = mLayerPaint;
15018                cachePaint.setAlpha((int) (alpha * 255));
15019            }
15020            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
15021        }
15022
15023        if (restoreTo >= 0) {
15024            canvas.restoreToCount(restoreTo);
15025        }
15026
15027        if (a != null && !more) {
15028            if (!hardwareAccelerated && !a.getFillAfter()) {
15029                onSetAlpha(255);
15030            }
15031            parent.finishAnimatingView(this, a);
15032        }
15033
15034        if (more && hardwareAccelerated) {
15035            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
15036                // alpha animations should cause the child to recreate its display list
15037                invalidate(true);
15038            }
15039        }
15040
15041        mRecreateDisplayList = false;
15042
15043        return more;
15044    }
15045
15046    /**
15047     * Manually render this view (and all of its children) to the given Canvas.
15048     * The view must have already done a full layout before this function is
15049     * called.  When implementing a view, implement
15050     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
15051     * If you do need to override this method, call the superclass version.
15052     *
15053     * @param canvas The Canvas to which the View is rendered.
15054     */
15055    public void draw(Canvas canvas) {
15056        if (mClipBounds != null) {
15057            canvas.clipRect(mClipBounds);
15058        }
15059        final int privateFlags = mPrivateFlags;
15060        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
15061                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
15062        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
15063
15064        /*
15065         * Draw traversal performs several drawing steps which must be executed
15066         * in the appropriate order:
15067         *
15068         *      1. Draw the background
15069         *      2. If necessary, save the canvas' layers to prepare for fading
15070         *      3. Draw view's content
15071         *      4. Draw children
15072         *      5. If necessary, draw the fading edges and restore layers
15073         *      6. Draw decorations (scrollbars for instance)
15074         */
15075
15076        // Step 1, draw the background, if needed
15077        int saveCount;
15078
15079        if (!dirtyOpaque) {
15080            drawBackground(canvas);
15081        }
15082
15083        // skip step 2 & 5 if possible (common case)
15084        final int viewFlags = mViewFlags;
15085        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
15086        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
15087        if (!verticalEdges && !horizontalEdges) {
15088            // Step 3, draw the content
15089            if (!dirtyOpaque) onDraw(canvas);
15090
15091            // Step 4, draw the children
15092            dispatchDraw(canvas);
15093
15094            // Step 6, draw decorations (scrollbars)
15095            onDrawScrollBars(canvas);
15096
15097            if (mOverlay != null && !mOverlay.isEmpty()) {
15098                mOverlay.getOverlayView().dispatchDraw(canvas);
15099            }
15100
15101            // we're done...
15102            return;
15103        }
15104
15105        /*
15106         * Here we do the full fledged routine...
15107         * (this is an uncommon case where speed matters less,
15108         * this is why we repeat some of the tests that have been
15109         * done above)
15110         */
15111
15112        boolean drawTop = false;
15113        boolean drawBottom = false;
15114        boolean drawLeft = false;
15115        boolean drawRight = false;
15116
15117        float topFadeStrength = 0.0f;
15118        float bottomFadeStrength = 0.0f;
15119        float leftFadeStrength = 0.0f;
15120        float rightFadeStrength = 0.0f;
15121
15122        // Step 2, save the canvas' layers
15123        int paddingLeft = mPaddingLeft;
15124
15125        final boolean offsetRequired = isPaddingOffsetRequired();
15126        if (offsetRequired) {
15127            paddingLeft += getLeftPaddingOffset();
15128        }
15129
15130        int left = mScrollX + paddingLeft;
15131        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
15132        int top = mScrollY + getFadeTop(offsetRequired);
15133        int bottom = top + getFadeHeight(offsetRequired);
15134
15135        if (offsetRequired) {
15136            right += getRightPaddingOffset();
15137            bottom += getBottomPaddingOffset();
15138        }
15139
15140        final ScrollabilityCache scrollabilityCache = mScrollCache;
15141        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
15142        int length = (int) fadeHeight;
15143
15144        // clip the fade length if top and bottom fades overlap
15145        // overlapping fades produce odd-looking artifacts
15146        if (verticalEdges && (top + length > bottom - length)) {
15147            length = (bottom - top) / 2;
15148        }
15149
15150        // also clip horizontal fades if necessary
15151        if (horizontalEdges && (left + length > right - length)) {
15152            length = (right - left) / 2;
15153        }
15154
15155        if (verticalEdges) {
15156            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
15157            drawTop = topFadeStrength * fadeHeight > 1.0f;
15158            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
15159            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
15160        }
15161
15162        if (horizontalEdges) {
15163            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
15164            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
15165            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
15166            drawRight = rightFadeStrength * fadeHeight > 1.0f;
15167        }
15168
15169        saveCount = canvas.getSaveCount();
15170
15171        int solidColor = getSolidColor();
15172        if (solidColor == 0) {
15173            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
15174
15175            if (drawTop) {
15176                canvas.saveLayer(left, top, right, top + length, null, flags);
15177            }
15178
15179            if (drawBottom) {
15180                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
15181            }
15182
15183            if (drawLeft) {
15184                canvas.saveLayer(left, top, left + length, bottom, null, flags);
15185            }
15186
15187            if (drawRight) {
15188                canvas.saveLayer(right - length, top, right, bottom, null, flags);
15189            }
15190        } else {
15191            scrollabilityCache.setFadeColor(solidColor);
15192        }
15193
15194        // Step 3, draw the content
15195        if (!dirtyOpaque) onDraw(canvas);
15196
15197        // Step 4, draw the children
15198        dispatchDraw(canvas);
15199
15200        // Step 5, draw the fade effect and restore layers
15201        final Paint p = scrollabilityCache.paint;
15202        final Matrix matrix = scrollabilityCache.matrix;
15203        final Shader fade = scrollabilityCache.shader;
15204
15205        if (drawTop) {
15206            matrix.setScale(1, fadeHeight * topFadeStrength);
15207            matrix.postTranslate(left, top);
15208            fade.setLocalMatrix(matrix);
15209            canvas.drawRect(left, top, right, top + length, p);
15210        }
15211
15212        if (drawBottom) {
15213            matrix.setScale(1, fadeHeight * bottomFadeStrength);
15214            matrix.postRotate(180);
15215            matrix.postTranslate(left, bottom);
15216            fade.setLocalMatrix(matrix);
15217            canvas.drawRect(left, bottom - length, right, bottom, p);
15218        }
15219
15220        if (drawLeft) {
15221            matrix.setScale(1, fadeHeight * leftFadeStrength);
15222            matrix.postRotate(-90);
15223            matrix.postTranslate(left, top);
15224            fade.setLocalMatrix(matrix);
15225            canvas.drawRect(left, top, left + length, bottom, p);
15226        }
15227
15228        if (drawRight) {
15229            matrix.setScale(1, fadeHeight * rightFadeStrength);
15230            matrix.postRotate(90);
15231            matrix.postTranslate(right, top);
15232            fade.setLocalMatrix(matrix);
15233            canvas.drawRect(right - length, top, right, bottom, p);
15234        }
15235
15236        canvas.restoreToCount(saveCount);
15237
15238        // Step 6, draw decorations (scrollbars)
15239        onDrawScrollBars(canvas);
15240
15241        if (mOverlay != null && !mOverlay.isEmpty()) {
15242            mOverlay.getOverlayView().dispatchDraw(canvas);
15243        }
15244    }
15245
15246    /**
15247     * Draws the background onto the specified canvas.
15248     *
15249     * @param canvas Canvas on which to draw the background
15250     */
15251    private void drawBackground(Canvas canvas) {
15252        final Drawable background = mBackground;
15253        if (background == null) {
15254            return;
15255        }
15256
15257        if (mBackgroundSizeChanged) {
15258            background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
15259            mBackgroundSizeChanged = false;
15260        }
15261
15262
15263        // Attempt to use a display list if requested.
15264        if (canvas != null && canvas.isHardwareAccelerated()) {
15265            mBackgroundDisplayList = getDrawableDisplayList(background, mBackgroundDisplayList);
15266
15267            final DisplayList displayList = mBackgroundDisplayList;
15268            if (displayList != null && displayList.isValid()) {
15269                setBackgroundDisplayListProperties(displayList);
15270                ((HardwareCanvas) canvas).drawDisplayList(displayList);
15271                return;
15272            }
15273        }
15274
15275        final int scrollX = mScrollX;
15276        final int scrollY = mScrollY;
15277        if ((scrollX | scrollY) == 0) {
15278            background.draw(canvas);
15279        } else {
15280            canvas.translate(scrollX, scrollY);
15281            background.draw(canvas);
15282            canvas.translate(-scrollX, -scrollY);
15283        }
15284    }
15285
15286    /**
15287     * Set up background drawable display list properties.
15288     *
15289     * @param displayList Valid display list for the background drawable
15290     */
15291    private void setBackgroundDisplayListProperties(DisplayList displayList) {
15292        displayList.setTranslationX(mScrollX);
15293        displayList.setTranslationY(mScrollY);
15294    }
15295
15296    /**
15297     * Creates a new display list or updates the existing display list for the
15298     * specified Drawable.
15299     *
15300     * @param drawable Drawable for which to create a display list
15301     * @param displayList Existing display list, or {@code null}
15302     * @return A valid display list for the specified drawable
15303     */
15304    private DisplayList getDrawableDisplayList(Drawable drawable, DisplayList displayList) {
15305        if (displayList == null) {
15306            displayList = DisplayList.create(drawable.getClass().getName());
15307        }
15308
15309        final Rect bounds = drawable.getBounds();
15310        final int width = bounds.width();
15311        final int height = bounds.height();
15312        final HardwareCanvas canvas = displayList.start(width, height);
15313        drawable.draw(canvas);
15314        displayList.end(getHardwareRenderer(), canvas);
15315
15316        // Set up drawable properties that are view-independent.
15317        displayList.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom);
15318        displayList.setProjectBackwards(drawable.isProjected());
15319        displayList.setProjectionReceiver(true);
15320        displayList.setClipToBounds(false);
15321        return displayList;
15322    }
15323
15324    /**
15325     * Returns the overlay for this view, creating it if it does not yet exist.
15326     * Adding drawables to the overlay will cause them to be displayed whenever
15327     * the view itself is redrawn. Objects in the overlay should be actively
15328     * managed: remove them when they should not be displayed anymore. The
15329     * overlay will always have the same size as its host view.
15330     *
15331     * <p>Note: Overlays do not currently work correctly with {@link
15332     * SurfaceView} or {@link TextureView}; contents in overlays for these
15333     * types of views may not display correctly.</p>
15334     *
15335     * @return The ViewOverlay object for this view.
15336     * @see ViewOverlay
15337     */
15338    public ViewOverlay getOverlay() {
15339        if (mOverlay == null) {
15340            mOverlay = new ViewOverlay(mContext, this);
15341        }
15342        return mOverlay;
15343    }
15344
15345    /**
15346     * Override this if your view is known to always be drawn on top of a solid color background,
15347     * and needs to draw fading edges. Returning a non-zero color enables the view system to
15348     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
15349     * should be set to 0xFF.
15350     *
15351     * @see #setVerticalFadingEdgeEnabled(boolean)
15352     * @see #setHorizontalFadingEdgeEnabled(boolean)
15353     *
15354     * @return The known solid color background for this view, or 0 if the color may vary
15355     */
15356    @ViewDebug.ExportedProperty(category = "drawing")
15357    public int getSolidColor() {
15358        return 0;
15359    }
15360
15361    /**
15362     * Build a human readable string representation of the specified view flags.
15363     *
15364     * @param flags the view flags to convert to a string
15365     * @return a String representing the supplied flags
15366     */
15367    private static String printFlags(int flags) {
15368        String output = "";
15369        int numFlags = 0;
15370        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
15371            output += "TAKES_FOCUS";
15372            numFlags++;
15373        }
15374
15375        switch (flags & VISIBILITY_MASK) {
15376        case INVISIBLE:
15377            if (numFlags > 0) {
15378                output += " ";
15379            }
15380            output += "INVISIBLE";
15381            // USELESS HERE numFlags++;
15382            break;
15383        case GONE:
15384            if (numFlags > 0) {
15385                output += " ";
15386            }
15387            output += "GONE";
15388            // USELESS HERE numFlags++;
15389            break;
15390        default:
15391            break;
15392        }
15393        return output;
15394    }
15395
15396    /**
15397     * Build a human readable string representation of the specified private
15398     * view flags.
15399     *
15400     * @param privateFlags the private view flags to convert to a string
15401     * @return a String representing the supplied flags
15402     */
15403    private static String printPrivateFlags(int privateFlags) {
15404        String output = "";
15405        int numFlags = 0;
15406
15407        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
15408            output += "WANTS_FOCUS";
15409            numFlags++;
15410        }
15411
15412        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
15413            if (numFlags > 0) {
15414                output += " ";
15415            }
15416            output += "FOCUSED";
15417            numFlags++;
15418        }
15419
15420        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
15421            if (numFlags > 0) {
15422                output += " ";
15423            }
15424            output += "SELECTED";
15425            numFlags++;
15426        }
15427
15428        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
15429            if (numFlags > 0) {
15430                output += " ";
15431            }
15432            output += "IS_ROOT_NAMESPACE";
15433            numFlags++;
15434        }
15435
15436        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
15437            if (numFlags > 0) {
15438                output += " ";
15439            }
15440            output += "HAS_BOUNDS";
15441            numFlags++;
15442        }
15443
15444        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
15445            if (numFlags > 0) {
15446                output += " ";
15447            }
15448            output += "DRAWN";
15449            // USELESS HERE numFlags++;
15450        }
15451        return output;
15452    }
15453
15454    /**
15455     * <p>Indicates whether or not this view's layout will be requested during
15456     * the next hierarchy layout pass.</p>
15457     *
15458     * @return true if the layout will be forced during next layout pass
15459     */
15460    public boolean isLayoutRequested() {
15461        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
15462    }
15463
15464    /**
15465     * Return true if o is a ViewGroup that is laying out using optical bounds.
15466     * @hide
15467     */
15468    public static boolean isLayoutModeOptical(Object o) {
15469        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
15470    }
15471
15472    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
15473        Insets parentInsets = mParent instanceof View ?
15474                ((View) mParent).getOpticalInsets() : Insets.NONE;
15475        Insets childInsets = getOpticalInsets();
15476        return setFrame(
15477                left   + parentInsets.left - childInsets.left,
15478                top    + parentInsets.top  - childInsets.top,
15479                right  + parentInsets.left + childInsets.right,
15480                bottom + parentInsets.top  + childInsets.bottom);
15481    }
15482
15483    /**
15484     * Assign a size and position to a view and all of its
15485     * descendants
15486     *
15487     * <p>This is the second phase of the layout mechanism.
15488     * (The first is measuring). In this phase, each parent calls
15489     * layout on all of its children to position them.
15490     * This is typically done using the child measurements
15491     * that were stored in the measure pass().</p>
15492     *
15493     * <p>Derived classes should not override this method.
15494     * Derived classes with children should override
15495     * onLayout. In that method, they should
15496     * call layout on each of their children.</p>
15497     *
15498     * @param l Left position, relative to parent
15499     * @param t Top position, relative to parent
15500     * @param r Right position, relative to parent
15501     * @param b Bottom position, relative to parent
15502     */
15503    @SuppressWarnings({"unchecked"})
15504    public void layout(int l, int t, int r, int b) {
15505        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
15506            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
15507            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
15508        }
15509
15510        int oldL = mLeft;
15511        int oldT = mTop;
15512        int oldB = mBottom;
15513        int oldR = mRight;
15514
15515        boolean changed = isLayoutModeOptical(mParent) ?
15516                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
15517
15518        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
15519            onLayout(changed, l, t, r, b);
15520            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
15521
15522            ListenerInfo li = mListenerInfo;
15523            if (li != null && li.mOnLayoutChangeListeners != null) {
15524                ArrayList<OnLayoutChangeListener> listenersCopy =
15525                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
15526                int numListeners = listenersCopy.size();
15527                for (int i = 0; i < numListeners; ++i) {
15528                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
15529                }
15530            }
15531        }
15532
15533        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
15534        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
15535    }
15536
15537    /**
15538     * Called from layout when this view should
15539     * assign a size and position to each of its children.
15540     *
15541     * Derived classes with children should override
15542     * this method and call layout on each of
15543     * their children.
15544     * @param changed This is a new size or position for this view
15545     * @param left Left position, relative to parent
15546     * @param top Top position, relative to parent
15547     * @param right Right position, relative to parent
15548     * @param bottom Bottom position, relative to parent
15549     */
15550    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
15551    }
15552
15553    /**
15554     * Assign a size and position to this view.
15555     *
15556     * This is called from layout.
15557     *
15558     * @param left Left position, relative to parent
15559     * @param top Top position, relative to parent
15560     * @param right Right position, relative to parent
15561     * @param bottom Bottom position, relative to parent
15562     * @return true if the new size and position are different than the
15563     *         previous ones
15564     * {@hide}
15565     */
15566    protected boolean setFrame(int left, int top, int right, int bottom) {
15567        boolean changed = false;
15568
15569        if (DBG) {
15570            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
15571                    + right + "," + bottom + ")");
15572        }
15573
15574        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
15575            changed = true;
15576
15577            // Remember our drawn bit
15578            int drawn = mPrivateFlags & PFLAG_DRAWN;
15579
15580            int oldWidth = mRight - mLeft;
15581            int oldHeight = mBottom - mTop;
15582            int newWidth = right - left;
15583            int newHeight = bottom - top;
15584            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
15585
15586            // Invalidate our old position
15587            invalidate(sizeChanged);
15588
15589            mLeft = left;
15590            mTop = top;
15591            mRight = right;
15592            mBottom = bottom;
15593            if (mDisplayList != null) {
15594                mDisplayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
15595            }
15596
15597            mPrivateFlags |= PFLAG_HAS_BOUNDS;
15598
15599
15600            if (sizeChanged) {
15601                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
15602                    // A change in dimension means an auto-centered pivot point changes, too
15603                    if (mTransformationInfo != null) {
15604                        mTransformationInfo.mMatrixDirty = true;
15605                    }
15606                }
15607                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
15608            }
15609
15610            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
15611                // If we are visible, force the DRAWN bit to on so that
15612                // this invalidate will go through (at least to our parent).
15613                // This is because someone may have invalidated this view
15614                // before this call to setFrame came in, thereby clearing
15615                // the DRAWN bit.
15616                mPrivateFlags |= PFLAG_DRAWN;
15617                invalidate(sizeChanged);
15618                // parent display list may need to be recreated based on a change in the bounds
15619                // of any child
15620                invalidateParentCaches();
15621            }
15622
15623            // Reset drawn bit to original value (invalidate turns it off)
15624            mPrivateFlags |= drawn;
15625
15626            mBackgroundSizeChanged = true;
15627
15628            notifySubtreeAccessibilityStateChangedIfNeeded();
15629        }
15630        return changed;
15631    }
15632
15633    private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
15634        onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
15635        if (mOverlay != null) {
15636            mOverlay.getOverlayView().setRight(newWidth);
15637            mOverlay.getOverlayView().setBottom(newHeight);
15638        }
15639    }
15640
15641    /**
15642     * Finalize inflating a view from XML.  This is called as the last phase
15643     * of inflation, after all child views have been added.
15644     *
15645     * <p>Even if the subclass overrides onFinishInflate, they should always be
15646     * sure to call the super method, so that we get called.
15647     */
15648    protected void onFinishInflate() {
15649    }
15650
15651    /**
15652     * Returns the resources associated with this view.
15653     *
15654     * @return Resources object.
15655     */
15656    public Resources getResources() {
15657        return mResources;
15658    }
15659
15660    /**
15661     * Invalidates the specified Drawable.
15662     *
15663     * @param drawable the drawable to invalidate
15664     */
15665    @Override
15666    public void invalidateDrawable(Drawable drawable) {
15667        if (verifyDrawable(drawable)) {
15668            final Rect dirty = drawable.getDirtyBounds();
15669            final int scrollX = mScrollX;
15670            final int scrollY = mScrollY;
15671
15672            invalidate(dirty.left + scrollX, dirty.top + scrollY,
15673                    dirty.right + scrollX, dirty.bottom + scrollY);
15674        }
15675    }
15676
15677    /**
15678     * Schedules an action on a drawable to occur at a specified time.
15679     *
15680     * @param who the recipient of the action
15681     * @param what the action to run on the drawable
15682     * @param when the time at which the action must occur. Uses the
15683     *        {@link SystemClock#uptimeMillis} timebase.
15684     */
15685    @Override
15686    public void scheduleDrawable(Drawable who, Runnable what, long when) {
15687        if (verifyDrawable(who) && what != null) {
15688            final long delay = when - SystemClock.uptimeMillis();
15689            if (mAttachInfo != null) {
15690                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
15691                        Choreographer.CALLBACK_ANIMATION, what, who,
15692                        Choreographer.subtractFrameDelay(delay));
15693            } else {
15694                ViewRootImpl.getRunQueue().postDelayed(what, delay);
15695            }
15696        }
15697    }
15698
15699    /**
15700     * Cancels a scheduled action on a drawable.
15701     *
15702     * @param who the recipient of the action
15703     * @param what the action to cancel
15704     */
15705    @Override
15706    public void unscheduleDrawable(Drawable who, Runnable what) {
15707        if (verifyDrawable(who) && what != null) {
15708            if (mAttachInfo != null) {
15709                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
15710                        Choreographer.CALLBACK_ANIMATION, what, who);
15711            }
15712            ViewRootImpl.getRunQueue().removeCallbacks(what);
15713        }
15714    }
15715
15716    /**
15717     * Unschedule any events associated with the given Drawable.  This can be
15718     * used when selecting a new Drawable into a view, so that the previous
15719     * one is completely unscheduled.
15720     *
15721     * @param who The Drawable to unschedule.
15722     *
15723     * @see #drawableStateChanged
15724     */
15725    public void unscheduleDrawable(Drawable who) {
15726        if (mAttachInfo != null && who != null) {
15727            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
15728                    Choreographer.CALLBACK_ANIMATION, null, who);
15729        }
15730    }
15731
15732    /**
15733     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
15734     * that the View directionality can and will be resolved before its Drawables.
15735     *
15736     * Will call {@link View#onResolveDrawables} when resolution is done.
15737     *
15738     * @hide
15739     */
15740    protected void resolveDrawables() {
15741        // Drawables resolution may need to happen before resolving the layout direction (which is
15742        // done only during the measure() call).
15743        // If the layout direction is not resolved yet, we cannot resolve the Drawables except in
15744        // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT.
15745        // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or
15746        // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout
15747        // direction to be resolved as its resolved value will be the same as its raw value.
15748        if (!isLayoutDirectionResolved() &&
15749                getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) {
15750            return;
15751        }
15752
15753        final int layoutDirection = isLayoutDirectionResolved() ?
15754                getLayoutDirection() : getRawLayoutDirection();
15755
15756        if (mBackground != null) {
15757            mBackground.setLayoutDirection(layoutDirection);
15758        }
15759        mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
15760        onResolveDrawables(layoutDirection);
15761    }
15762
15763    /**
15764     * Called when layout direction has been resolved.
15765     *
15766     * The default implementation does nothing.
15767     *
15768     * @param layoutDirection The resolved layout direction.
15769     *
15770     * @see #LAYOUT_DIRECTION_LTR
15771     * @see #LAYOUT_DIRECTION_RTL
15772     *
15773     * @hide
15774     */
15775    public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) {
15776    }
15777
15778    /**
15779     * @hide
15780     */
15781    protected void resetResolvedDrawables() {
15782        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
15783    }
15784
15785    private boolean isDrawablesResolved() {
15786        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
15787    }
15788
15789    /**
15790     * If your view subclass is displaying its own Drawable objects, it should
15791     * override this function and return true for any Drawable it is
15792     * displaying.  This allows animations for those drawables to be
15793     * scheduled.
15794     *
15795     * <p>Be sure to call through to the super class when overriding this
15796     * function.
15797     *
15798     * @param who The Drawable to verify.  Return true if it is one you are
15799     *            displaying, else return the result of calling through to the
15800     *            super class.
15801     *
15802     * @return boolean If true than the Drawable is being displayed in the
15803     *         view; else false and it is not allowed to animate.
15804     *
15805     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
15806     * @see #drawableStateChanged()
15807     */
15808    protected boolean verifyDrawable(Drawable who) {
15809        return who == mBackground;
15810    }
15811
15812    /**
15813     * This function is called whenever the state of the view changes in such
15814     * a way that it impacts the state of drawables being shown.
15815     *
15816     * <p>Be sure to call through to the superclass when overriding this
15817     * function.
15818     *
15819     * @see Drawable#setState(int[])
15820     */
15821    protected void drawableStateChanged() {
15822        final Drawable d = mBackground;
15823        if (d != null && d.isStateful()) {
15824            d.setState(getDrawableState());
15825        }
15826    }
15827
15828    /**
15829     * Call this to force a view to update its drawable state. This will cause
15830     * drawableStateChanged to be called on this view. Views that are interested
15831     * in the new state should call getDrawableState.
15832     *
15833     * @see #drawableStateChanged
15834     * @see #getDrawableState
15835     */
15836    public void refreshDrawableState() {
15837        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
15838        drawableStateChanged();
15839
15840        ViewParent parent = mParent;
15841        if (parent != null) {
15842            parent.childDrawableStateChanged(this);
15843        }
15844    }
15845
15846    /**
15847     * Return an array of resource IDs of the drawable states representing the
15848     * current state of the view.
15849     *
15850     * @return The current drawable state
15851     *
15852     * @see Drawable#setState(int[])
15853     * @see #drawableStateChanged()
15854     * @see #onCreateDrawableState(int)
15855     */
15856    public final int[] getDrawableState() {
15857        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
15858            return mDrawableState;
15859        } else {
15860            mDrawableState = onCreateDrawableState(0);
15861            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
15862            return mDrawableState;
15863        }
15864    }
15865
15866    /**
15867     * Generate the new {@link android.graphics.drawable.Drawable} state for
15868     * this view. This is called by the view
15869     * system when the cached Drawable state is determined to be invalid.  To
15870     * retrieve the current state, you should use {@link #getDrawableState}.
15871     *
15872     * @param extraSpace if non-zero, this is the number of extra entries you
15873     * would like in the returned array in which you can place your own
15874     * states.
15875     *
15876     * @return Returns an array holding the current {@link Drawable} state of
15877     * the view.
15878     *
15879     * @see #mergeDrawableStates(int[], int[])
15880     */
15881    protected int[] onCreateDrawableState(int extraSpace) {
15882        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
15883                mParent instanceof View) {
15884            return ((View) mParent).onCreateDrawableState(extraSpace);
15885        }
15886
15887        int[] drawableState;
15888
15889        int privateFlags = mPrivateFlags;
15890
15891        int viewStateIndex = 0;
15892        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
15893        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
15894        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
15895        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
15896        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
15897        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
15898        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
15899                HardwareRenderer.isAvailable()) {
15900            // This is set if HW acceleration is requested, even if the current
15901            // process doesn't allow it.  This is just to allow app preview
15902            // windows to better match their app.
15903            viewStateIndex |= VIEW_STATE_ACCELERATED;
15904        }
15905        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
15906
15907        final int privateFlags2 = mPrivateFlags2;
15908        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
15909        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
15910
15911        drawableState = VIEW_STATE_SETS[viewStateIndex];
15912
15913        //noinspection ConstantIfStatement
15914        if (false) {
15915            Log.i("View", "drawableStateIndex=" + viewStateIndex);
15916            Log.i("View", toString()
15917                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
15918                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
15919                    + " fo=" + hasFocus()
15920                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
15921                    + " wf=" + hasWindowFocus()
15922                    + ": " + Arrays.toString(drawableState));
15923        }
15924
15925        if (extraSpace == 0) {
15926            return drawableState;
15927        }
15928
15929        final int[] fullState;
15930        if (drawableState != null) {
15931            fullState = new int[drawableState.length + extraSpace];
15932            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
15933        } else {
15934            fullState = new int[extraSpace];
15935        }
15936
15937        return fullState;
15938    }
15939
15940    /**
15941     * Merge your own state values in <var>additionalState</var> into the base
15942     * state values <var>baseState</var> that were returned by
15943     * {@link #onCreateDrawableState(int)}.
15944     *
15945     * @param baseState The base state values returned by
15946     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
15947     * own additional state values.
15948     *
15949     * @param additionalState The additional state values you would like
15950     * added to <var>baseState</var>; this array is not modified.
15951     *
15952     * @return As a convenience, the <var>baseState</var> array you originally
15953     * passed into the function is returned.
15954     *
15955     * @see #onCreateDrawableState(int)
15956     */
15957    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
15958        final int N = baseState.length;
15959        int i = N - 1;
15960        while (i >= 0 && baseState[i] == 0) {
15961            i--;
15962        }
15963        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
15964        return baseState;
15965    }
15966
15967    /**
15968     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
15969     * on all Drawable objects associated with this view.
15970     */
15971    public void jumpDrawablesToCurrentState() {
15972        if (mBackground != null) {
15973            mBackground.jumpToCurrentState();
15974        }
15975    }
15976
15977    /**
15978     * Sets the background color for this view.
15979     * @param color the color of the background
15980     */
15981    @RemotableViewMethod
15982    public void setBackgroundColor(int color) {
15983        if (mBackground instanceof ColorDrawable) {
15984            ((ColorDrawable) mBackground.mutate()).setColor(color);
15985            computeOpaqueFlags();
15986            mBackgroundResource = 0;
15987        } else {
15988            setBackground(new ColorDrawable(color));
15989        }
15990    }
15991
15992    /**
15993     * Set the background to a given resource. The resource should refer to
15994     * a Drawable object or 0 to remove the background.
15995     * @param resid The identifier of the resource.
15996     *
15997     * @attr ref android.R.styleable#View_background
15998     */
15999    @RemotableViewMethod
16000    public void setBackgroundResource(int resid) {
16001        if (resid != 0 && resid == mBackgroundResource) {
16002            return;
16003        }
16004
16005        Drawable d= null;
16006        if (resid != 0) {
16007            d = mContext.getDrawable(resid);
16008        }
16009        setBackground(d);
16010
16011        mBackgroundResource = resid;
16012    }
16013
16014    /**
16015     * Set the background to a given Drawable, or remove the background. If the
16016     * background has padding, this View's padding is set to the background's
16017     * padding. However, when a background is removed, this View's padding isn't
16018     * touched. If setting the padding is desired, please use
16019     * {@link #setPadding(int, int, int, int)}.
16020     *
16021     * @param background The Drawable to use as the background, or null to remove the
16022     *        background
16023     */
16024    public void setBackground(Drawable background) {
16025        //noinspection deprecation
16026        setBackgroundDrawable(background);
16027    }
16028
16029    /**
16030     * @deprecated use {@link #setBackground(Drawable)} instead
16031     */
16032    @Deprecated
16033    public void setBackgroundDrawable(Drawable background) {
16034        computeOpaqueFlags();
16035
16036        if (background == mBackground) {
16037            return;
16038        }
16039
16040        boolean requestLayout = false;
16041
16042        mBackgroundResource = 0;
16043
16044        /*
16045         * Regardless of whether we're setting a new background or not, we want
16046         * to clear the previous drawable.
16047         */
16048        if (mBackground != null) {
16049            mBackground.setCallback(null);
16050            unscheduleDrawable(mBackground);
16051        }
16052
16053        if (background != null) {
16054            Rect padding = sThreadLocal.get();
16055            if (padding == null) {
16056                padding = new Rect();
16057                sThreadLocal.set(padding);
16058            }
16059            resetResolvedDrawables();
16060            background.setLayoutDirection(getLayoutDirection());
16061            if (background.getPadding(padding)) {
16062                resetResolvedPadding();
16063                switch (background.getLayoutDirection()) {
16064                    case LAYOUT_DIRECTION_RTL:
16065                        mUserPaddingLeftInitial = padding.right;
16066                        mUserPaddingRightInitial = padding.left;
16067                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
16068                        break;
16069                    case LAYOUT_DIRECTION_LTR:
16070                    default:
16071                        mUserPaddingLeftInitial = padding.left;
16072                        mUserPaddingRightInitial = padding.right;
16073                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
16074                }
16075                mLeftPaddingDefined = false;
16076                mRightPaddingDefined = false;
16077            }
16078
16079            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
16080            // if it has a different minimum size, we should layout again
16081            if (mBackground == null || mBackground.getMinimumHeight() != background.getMinimumHeight() ||
16082                    mBackground.getMinimumWidth() != background.getMinimumWidth()) {
16083                requestLayout = true;
16084            }
16085
16086            background.setCallback(this);
16087            if (background.isStateful()) {
16088                background.setState(getDrawableState());
16089            }
16090            background.setVisible(getVisibility() == VISIBLE, false);
16091            mBackground = background;
16092
16093            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
16094                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
16095                mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
16096                requestLayout = true;
16097            }
16098        } else {
16099            /* Remove the background */
16100            mBackground = null;
16101
16102            if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) {
16103                /*
16104                 * This view ONLY drew the background before and we're removing
16105                 * the background, so now it won't draw anything
16106                 * (hence we SKIP_DRAW)
16107                 */
16108                mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND;
16109                mPrivateFlags |= PFLAG_SKIP_DRAW;
16110            }
16111
16112            /*
16113             * When the background is set, we try to apply its padding to this
16114             * View. When the background is removed, we don't touch this View's
16115             * padding. This is noted in the Javadocs. Hence, we don't need to
16116             * requestLayout(), the invalidate() below is sufficient.
16117             */
16118
16119            // The old background's minimum size could have affected this
16120            // View's layout, so let's requestLayout
16121            requestLayout = true;
16122        }
16123
16124        computeOpaqueFlags();
16125
16126        if (requestLayout) {
16127            requestLayout();
16128        }
16129
16130        mBackgroundSizeChanged = true;
16131        invalidate(true);
16132    }
16133
16134    /**
16135     * Gets the background drawable
16136     *
16137     * @return The drawable used as the background for this view, if any.
16138     *
16139     * @see #setBackground(Drawable)
16140     *
16141     * @attr ref android.R.styleable#View_background
16142     */
16143    public Drawable getBackground() {
16144        return mBackground;
16145    }
16146
16147    /**
16148     * Sets the padding. The view may add on the space required to display
16149     * the scrollbars, depending on the style and visibility of the scrollbars.
16150     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
16151     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
16152     * from the values set in this call.
16153     *
16154     * @attr ref android.R.styleable#View_padding
16155     * @attr ref android.R.styleable#View_paddingBottom
16156     * @attr ref android.R.styleable#View_paddingLeft
16157     * @attr ref android.R.styleable#View_paddingRight
16158     * @attr ref android.R.styleable#View_paddingTop
16159     * @param left the left padding in pixels
16160     * @param top the top padding in pixels
16161     * @param right the right padding in pixels
16162     * @param bottom the bottom padding in pixels
16163     */
16164    public void setPadding(int left, int top, int right, int bottom) {
16165        resetResolvedPadding();
16166
16167        mUserPaddingStart = UNDEFINED_PADDING;
16168        mUserPaddingEnd = UNDEFINED_PADDING;
16169
16170        mUserPaddingLeftInitial = left;
16171        mUserPaddingRightInitial = right;
16172
16173        mLeftPaddingDefined = true;
16174        mRightPaddingDefined = true;
16175
16176        internalSetPadding(left, top, right, bottom);
16177    }
16178
16179    /**
16180     * @hide
16181     */
16182    protected void internalSetPadding(int left, int top, int right, int bottom) {
16183        mUserPaddingLeft = left;
16184        mUserPaddingRight = right;
16185        mUserPaddingBottom = bottom;
16186
16187        final int viewFlags = mViewFlags;
16188        boolean changed = false;
16189
16190        // Common case is there are no scroll bars.
16191        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
16192            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
16193                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
16194                        ? 0 : getVerticalScrollbarWidth();
16195                switch (mVerticalScrollbarPosition) {
16196                    case SCROLLBAR_POSITION_DEFAULT:
16197                        if (isLayoutRtl()) {
16198                            left += offset;
16199                        } else {
16200                            right += offset;
16201                        }
16202                        break;
16203                    case SCROLLBAR_POSITION_RIGHT:
16204                        right += offset;
16205                        break;
16206                    case SCROLLBAR_POSITION_LEFT:
16207                        left += offset;
16208                        break;
16209                }
16210            }
16211            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
16212                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
16213                        ? 0 : getHorizontalScrollbarHeight();
16214            }
16215        }
16216
16217        if (mPaddingLeft != left) {
16218            changed = true;
16219            mPaddingLeft = left;
16220        }
16221        if (mPaddingTop != top) {
16222            changed = true;
16223            mPaddingTop = top;
16224        }
16225        if (mPaddingRight != right) {
16226            changed = true;
16227            mPaddingRight = right;
16228        }
16229        if (mPaddingBottom != bottom) {
16230            changed = true;
16231            mPaddingBottom = bottom;
16232        }
16233
16234        if (changed) {
16235            requestLayout();
16236        }
16237    }
16238
16239    /**
16240     * Sets the relative padding. The view may add on the space required to display
16241     * the scrollbars, depending on the style and visibility of the scrollbars.
16242     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
16243     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
16244     * from the values set in this call.
16245     *
16246     * @attr ref android.R.styleable#View_padding
16247     * @attr ref android.R.styleable#View_paddingBottom
16248     * @attr ref android.R.styleable#View_paddingStart
16249     * @attr ref android.R.styleable#View_paddingEnd
16250     * @attr ref android.R.styleable#View_paddingTop
16251     * @param start the start padding in pixels
16252     * @param top the top padding in pixels
16253     * @param end the end padding in pixels
16254     * @param bottom the bottom padding in pixels
16255     */
16256    public void setPaddingRelative(int start, int top, int end, int bottom) {
16257        resetResolvedPadding();
16258
16259        mUserPaddingStart = start;
16260        mUserPaddingEnd = end;
16261        mLeftPaddingDefined = true;
16262        mRightPaddingDefined = true;
16263
16264        switch(getLayoutDirection()) {
16265            case LAYOUT_DIRECTION_RTL:
16266                mUserPaddingLeftInitial = end;
16267                mUserPaddingRightInitial = start;
16268                internalSetPadding(end, top, start, bottom);
16269                break;
16270            case LAYOUT_DIRECTION_LTR:
16271            default:
16272                mUserPaddingLeftInitial = start;
16273                mUserPaddingRightInitial = end;
16274                internalSetPadding(start, top, end, bottom);
16275        }
16276    }
16277
16278    /**
16279     * Returns the top padding of this view.
16280     *
16281     * @return the top padding in pixels
16282     */
16283    public int getPaddingTop() {
16284        return mPaddingTop;
16285    }
16286
16287    /**
16288     * Returns the bottom padding of this view. If there are inset and enabled
16289     * scrollbars, this value may include the space required to display the
16290     * scrollbars as well.
16291     *
16292     * @return the bottom padding in pixels
16293     */
16294    public int getPaddingBottom() {
16295        return mPaddingBottom;
16296    }
16297
16298    /**
16299     * Returns the left padding of this view. If there are inset and enabled
16300     * scrollbars, this value may include the space required to display the
16301     * scrollbars as well.
16302     *
16303     * @return the left padding in pixels
16304     */
16305    public int getPaddingLeft() {
16306        if (!isPaddingResolved()) {
16307            resolvePadding();
16308        }
16309        return mPaddingLeft;
16310    }
16311
16312    /**
16313     * Returns the start padding of this view depending on its resolved layout direction.
16314     * If there are inset and enabled scrollbars, this value may include the space
16315     * required to display the scrollbars as well.
16316     *
16317     * @return the start padding in pixels
16318     */
16319    public int getPaddingStart() {
16320        if (!isPaddingResolved()) {
16321            resolvePadding();
16322        }
16323        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
16324                mPaddingRight : mPaddingLeft;
16325    }
16326
16327    /**
16328     * Returns the right padding of this view. If there are inset and enabled
16329     * scrollbars, this value may include the space required to display the
16330     * scrollbars as well.
16331     *
16332     * @return the right padding in pixels
16333     */
16334    public int getPaddingRight() {
16335        if (!isPaddingResolved()) {
16336            resolvePadding();
16337        }
16338        return mPaddingRight;
16339    }
16340
16341    /**
16342     * Returns the end padding of this view depending on its resolved layout direction.
16343     * If there are inset and enabled scrollbars, this value may include the space
16344     * required to display the scrollbars as well.
16345     *
16346     * @return the end padding in pixels
16347     */
16348    public int getPaddingEnd() {
16349        if (!isPaddingResolved()) {
16350            resolvePadding();
16351        }
16352        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
16353                mPaddingLeft : mPaddingRight;
16354    }
16355
16356    /**
16357     * Return if the padding as been set thru relative values
16358     * {@link #setPaddingRelative(int, int, int, int)} or thru
16359     * @attr ref android.R.styleable#View_paddingStart or
16360     * @attr ref android.R.styleable#View_paddingEnd
16361     *
16362     * @return true if the padding is relative or false if it is not.
16363     */
16364    public boolean isPaddingRelative() {
16365        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
16366    }
16367
16368    Insets computeOpticalInsets() {
16369        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
16370    }
16371
16372    /**
16373     * @hide
16374     */
16375    public void resetPaddingToInitialValues() {
16376        if (isRtlCompatibilityMode()) {
16377            mPaddingLeft = mUserPaddingLeftInitial;
16378            mPaddingRight = mUserPaddingRightInitial;
16379            return;
16380        }
16381        if (isLayoutRtl()) {
16382            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
16383            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
16384        } else {
16385            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
16386            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
16387        }
16388    }
16389
16390    /**
16391     * @hide
16392     */
16393    public Insets getOpticalInsets() {
16394        if (mLayoutInsets == null) {
16395            mLayoutInsets = computeOpticalInsets();
16396        }
16397        return mLayoutInsets;
16398    }
16399
16400    /**
16401     * Changes the selection state of this view. A view can be selected or not.
16402     * Note that selection is not the same as focus. Views are typically
16403     * selected in the context of an AdapterView like ListView or GridView;
16404     * the selected view is the view that is highlighted.
16405     *
16406     * @param selected true if the view must be selected, false otherwise
16407     */
16408    public void setSelected(boolean selected) {
16409        //noinspection DoubleNegation
16410        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
16411            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
16412            if (!selected) resetPressedState();
16413            invalidate(true);
16414            refreshDrawableState();
16415            dispatchSetSelected(selected);
16416            notifyViewAccessibilityStateChangedIfNeeded(
16417                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
16418        }
16419    }
16420
16421    /**
16422     * Dispatch setSelected to all of this View's children.
16423     *
16424     * @see #setSelected(boolean)
16425     *
16426     * @param selected The new selected state
16427     */
16428    protected void dispatchSetSelected(boolean selected) {
16429    }
16430
16431    /**
16432     * Indicates the selection state of this view.
16433     *
16434     * @return true if the view is selected, false otherwise
16435     */
16436    @ViewDebug.ExportedProperty
16437    public boolean isSelected() {
16438        return (mPrivateFlags & PFLAG_SELECTED) != 0;
16439    }
16440
16441    /**
16442     * Changes the activated state of this view. A view can be activated or not.
16443     * Note that activation is not the same as selection.  Selection is
16444     * a transient property, representing the view (hierarchy) the user is
16445     * currently interacting with.  Activation is a longer-term state that the
16446     * user can move views in and out of.  For example, in a list view with
16447     * single or multiple selection enabled, the views in the current selection
16448     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
16449     * here.)  The activated state is propagated down to children of the view it
16450     * is set on.
16451     *
16452     * @param activated true if the view must be activated, false otherwise
16453     */
16454    public void setActivated(boolean activated) {
16455        //noinspection DoubleNegation
16456        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
16457            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
16458            invalidate(true);
16459            refreshDrawableState();
16460            dispatchSetActivated(activated);
16461        }
16462    }
16463
16464    /**
16465     * Dispatch setActivated to all of this View's children.
16466     *
16467     * @see #setActivated(boolean)
16468     *
16469     * @param activated The new activated state
16470     */
16471    protected void dispatchSetActivated(boolean activated) {
16472    }
16473
16474    /**
16475     * Indicates the activation state of this view.
16476     *
16477     * @return true if the view is activated, false otherwise
16478     */
16479    @ViewDebug.ExportedProperty
16480    public boolean isActivated() {
16481        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
16482    }
16483
16484    /**
16485     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
16486     * observer can be used to get notifications when global events, like
16487     * layout, happen.
16488     *
16489     * The returned ViewTreeObserver observer is not guaranteed to remain
16490     * valid for the lifetime of this View. If the caller of this method keeps
16491     * a long-lived reference to ViewTreeObserver, it should always check for
16492     * the return value of {@link ViewTreeObserver#isAlive()}.
16493     *
16494     * @return The ViewTreeObserver for this view's hierarchy.
16495     */
16496    public ViewTreeObserver getViewTreeObserver() {
16497        if (mAttachInfo != null) {
16498            return mAttachInfo.mTreeObserver;
16499        }
16500        if (mFloatingTreeObserver == null) {
16501            mFloatingTreeObserver = new ViewTreeObserver();
16502        }
16503        return mFloatingTreeObserver;
16504    }
16505
16506    /**
16507     * <p>Finds the topmost view in the current view hierarchy.</p>
16508     *
16509     * @return the topmost view containing this view
16510     */
16511    public View getRootView() {
16512        if (mAttachInfo != null) {
16513            final View v = mAttachInfo.mRootView;
16514            if (v != null) {
16515                return v;
16516            }
16517        }
16518
16519        View parent = this;
16520
16521        while (parent.mParent != null && parent.mParent instanceof View) {
16522            parent = (View) parent.mParent;
16523        }
16524
16525        return parent;
16526    }
16527
16528    /**
16529     * Transforms a motion event from view-local coordinates to on-screen
16530     * coordinates.
16531     *
16532     * @param ev the view-local motion event
16533     * @return false if the transformation could not be applied
16534     * @hide
16535     */
16536    public boolean toGlobalMotionEvent(MotionEvent ev) {
16537        final AttachInfo info = mAttachInfo;
16538        if (info == null) {
16539            return false;
16540        }
16541
16542        final Matrix m = info.mTmpMatrix;
16543        m.set(Matrix.IDENTITY_MATRIX);
16544        transformMatrixToGlobal(m);
16545        ev.transform(m);
16546        return true;
16547    }
16548
16549    /**
16550     * Transforms a motion event from on-screen coordinates to view-local
16551     * coordinates.
16552     *
16553     * @param ev the on-screen motion event
16554     * @return false if the transformation could not be applied
16555     * @hide
16556     */
16557    public boolean toLocalMotionEvent(MotionEvent ev) {
16558        final AttachInfo info = mAttachInfo;
16559        if (info == null) {
16560            return false;
16561        }
16562
16563        final Matrix m = info.mTmpMatrix;
16564        m.set(Matrix.IDENTITY_MATRIX);
16565        transformMatrixToLocal(m);
16566        ev.transform(m);
16567        return true;
16568    }
16569
16570    /**
16571     * Modifies the input matrix such that it maps view-local coordinates to
16572     * on-screen coordinates.
16573     *
16574     * @param m input matrix to modify
16575     */
16576    void transformMatrixToGlobal(Matrix m) {
16577        final ViewParent parent = mParent;
16578        if (parent instanceof View) {
16579            final View vp = (View) parent;
16580            vp.transformMatrixToGlobal(m);
16581            m.postTranslate(-vp.mScrollX, -vp.mScrollY);
16582        } else if (parent instanceof ViewRootImpl) {
16583            final ViewRootImpl vr = (ViewRootImpl) parent;
16584            vr.transformMatrixToGlobal(m);
16585            m.postTranslate(0, -vr.mCurScrollY);
16586        }
16587
16588        m.postTranslate(mLeft, mTop);
16589
16590        if (!hasIdentityMatrix()) {
16591            m.postConcat(getMatrix());
16592        }
16593    }
16594
16595    /**
16596     * Modifies the input matrix such that it maps on-screen coordinates to
16597     * view-local coordinates.
16598     *
16599     * @param m input matrix to modify
16600     */
16601    void transformMatrixToLocal(Matrix m) {
16602        final ViewParent parent = mParent;
16603        if (parent instanceof View) {
16604            final View vp = (View) parent;
16605            vp.transformMatrixToLocal(m);
16606            m.preTranslate(vp.mScrollX, vp.mScrollY);
16607        } else if (parent instanceof ViewRootImpl) {
16608            final ViewRootImpl vr = (ViewRootImpl) parent;
16609            vr.transformMatrixToLocal(m);
16610            m.preTranslate(0, vr.mCurScrollY);
16611        }
16612
16613        m.preTranslate(-mLeft, -mTop);
16614
16615        if (!hasIdentityMatrix()) {
16616            m.preConcat(getInverseMatrix());
16617        }
16618    }
16619
16620    /**
16621     * <p>Computes the coordinates of this view on the screen. The argument
16622     * must be an array of two integers. After the method returns, the array
16623     * contains the x and y location in that order.</p>
16624     *
16625     * @param location an array of two integers in which to hold the coordinates
16626     */
16627    public void getLocationOnScreen(int[] location) {
16628        getLocationInWindow(location);
16629
16630        final AttachInfo info = mAttachInfo;
16631        if (info != null) {
16632            location[0] += info.mWindowLeft;
16633            location[1] += info.mWindowTop;
16634        }
16635    }
16636
16637    /**
16638     * <p>Computes the coordinates of this view in its window. 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 getLocationInWindow(int[] location) {
16645        if (location == null || location.length < 2) {
16646            throw new IllegalArgumentException("location must be an array of two integers");
16647        }
16648
16649        if (mAttachInfo == null) {
16650            // When the view is not attached to a window, this method does not make sense
16651            location[0] = location[1] = 0;
16652            return;
16653        }
16654
16655        float[] position = mAttachInfo.mTmpTransformLocation;
16656        position[0] = position[1] = 0.0f;
16657
16658        if (!hasIdentityMatrix()) {
16659            getMatrix().mapPoints(position);
16660        }
16661
16662        position[0] += mLeft;
16663        position[1] += mTop;
16664
16665        ViewParent viewParent = mParent;
16666        while (viewParent instanceof View) {
16667            final View view = (View) viewParent;
16668
16669            position[0] -= view.mScrollX;
16670            position[1] -= view.mScrollY;
16671
16672            if (!view.hasIdentityMatrix()) {
16673                view.getMatrix().mapPoints(position);
16674            }
16675
16676            position[0] += view.mLeft;
16677            position[1] += view.mTop;
16678
16679            viewParent = view.mParent;
16680         }
16681
16682        if (viewParent instanceof ViewRootImpl) {
16683            // *cough*
16684            final ViewRootImpl vr = (ViewRootImpl) viewParent;
16685            position[1] -= vr.mCurScrollY;
16686        }
16687
16688        location[0] = (int) (position[0] + 0.5f);
16689        location[1] = (int) (position[1] + 0.5f);
16690    }
16691
16692    /**
16693     * {@hide}
16694     * @param id the id of the view to be found
16695     * @return the view of the specified id, null if cannot be found
16696     */
16697    protected View findViewTraversal(int id) {
16698        if (id == mID) {
16699            return this;
16700        }
16701        return null;
16702    }
16703
16704    /**
16705     * {@hide}
16706     * @param tag the tag of the view to be found
16707     * @return the view of specified tag, null if cannot be found
16708     */
16709    protected View findViewWithTagTraversal(Object tag) {
16710        if (tag != null && tag.equals(mTag)) {
16711            return this;
16712        }
16713        return null;
16714    }
16715
16716    /**
16717     * {@hide}
16718     * @param predicate The predicate to evaluate.
16719     * @param childToSkip If not null, ignores this child during the recursive traversal.
16720     * @return The first view that matches the predicate or null.
16721     */
16722    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
16723        if (predicate.apply(this)) {
16724            return this;
16725        }
16726        return null;
16727    }
16728
16729    /**
16730     * Look for a child view with the given id.  If this view has the given
16731     * id, return this view.
16732     *
16733     * @param id The id to search for.
16734     * @return The view that has the given id in the hierarchy or null
16735     */
16736    public final View findViewById(int id) {
16737        if (id < 0) {
16738            return null;
16739        }
16740        return findViewTraversal(id);
16741    }
16742
16743    /**
16744     * Finds a view by its unuque and stable accessibility id.
16745     *
16746     * @param accessibilityId The searched accessibility id.
16747     * @return The found view.
16748     */
16749    final View findViewByAccessibilityId(int accessibilityId) {
16750        if (accessibilityId < 0) {
16751            return null;
16752        }
16753        return findViewByAccessibilityIdTraversal(accessibilityId);
16754    }
16755
16756    /**
16757     * Performs the traversal to find a view by its unuque and stable accessibility id.
16758     *
16759     * <strong>Note:</strong>This method does not stop at the root namespace
16760     * boundary since the user can touch the screen at an arbitrary location
16761     * potentially crossing the root namespace bounday which will send an
16762     * accessibility event to accessibility services and they should be able
16763     * to obtain the event source. Also accessibility ids are guaranteed to be
16764     * unique in the window.
16765     *
16766     * @param accessibilityId The accessibility id.
16767     * @return The found view.
16768     *
16769     * @hide
16770     */
16771    public View findViewByAccessibilityIdTraversal(int accessibilityId) {
16772        if (getAccessibilityViewId() == accessibilityId) {
16773            return this;
16774        }
16775        return null;
16776    }
16777
16778    /**
16779     * Look for a child view with the given tag.  If this view has the given
16780     * tag, return this view.
16781     *
16782     * @param tag The tag to search for, using "tag.equals(getTag())".
16783     * @return The View that has the given tag in the hierarchy or null
16784     */
16785    public final View findViewWithTag(Object tag) {
16786        if (tag == null) {
16787            return null;
16788        }
16789        return findViewWithTagTraversal(tag);
16790    }
16791
16792    /**
16793     * {@hide}
16794     * Look for a child view that matches the specified predicate.
16795     * If this view matches the predicate, return this view.
16796     *
16797     * @param predicate The predicate to evaluate.
16798     * @return The first view that matches the predicate or null.
16799     */
16800    public final View findViewByPredicate(Predicate<View> predicate) {
16801        return findViewByPredicateTraversal(predicate, null);
16802    }
16803
16804    /**
16805     * {@hide}
16806     * Look for a child view that matches the specified predicate,
16807     * starting with the specified view and its descendents and then
16808     * recusively searching the ancestors and siblings of that view
16809     * until this view is reached.
16810     *
16811     * This method is useful in cases where the predicate does not match
16812     * a single unique view (perhaps multiple views use the same id)
16813     * and we are trying to find the view that is "closest" in scope to the
16814     * starting view.
16815     *
16816     * @param start The view to start from.
16817     * @param predicate The predicate to evaluate.
16818     * @return The first view that matches the predicate or null.
16819     */
16820    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
16821        View childToSkip = null;
16822        for (;;) {
16823            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
16824            if (view != null || start == this) {
16825                return view;
16826            }
16827
16828            ViewParent parent = start.getParent();
16829            if (parent == null || !(parent instanceof View)) {
16830                return null;
16831            }
16832
16833            childToSkip = start;
16834            start = (View) parent;
16835        }
16836    }
16837
16838    /**
16839     * Sets the identifier for this view. The identifier does not have to be
16840     * unique in this view's hierarchy. The identifier should be a positive
16841     * number.
16842     *
16843     * @see #NO_ID
16844     * @see #getId()
16845     * @see #findViewById(int)
16846     *
16847     * @param id a number used to identify the view
16848     *
16849     * @attr ref android.R.styleable#View_id
16850     */
16851    public void setId(int id) {
16852        mID = id;
16853        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
16854            mID = generateViewId();
16855        }
16856    }
16857
16858    /**
16859     * {@hide}
16860     *
16861     * @param isRoot true if the view belongs to the root namespace, false
16862     *        otherwise
16863     */
16864    public void setIsRootNamespace(boolean isRoot) {
16865        if (isRoot) {
16866            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
16867        } else {
16868            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
16869        }
16870    }
16871
16872    /**
16873     * {@hide}
16874     *
16875     * @return true if the view belongs to the root namespace, false otherwise
16876     */
16877    public boolean isRootNamespace() {
16878        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
16879    }
16880
16881    /**
16882     * Returns this view's identifier.
16883     *
16884     * @return a positive integer used to identify the view or {@link #NO_ID}
16885     *         if the view has no ID
16886     *
16887     * @see #setId(int)
16888     * @see #findViewById(int)
16889     * @attr ref android.R.styleable#View_id
16890     */
16891    @ViewDebug.CapturedViewProperty
16892    public int getId() {
16893        return mID;
16894    }
16895
16896    /**
16897     * Returns this view's tag.
16898     *
16899     * @return the Object stored in this view as a tag, or {@code null} if not
16900     *         set
16901     *
16902     * @see #setTag(Object)
16903     * @see #getTag(int)
16904     */
16905    @ViewDebug.ExportedProperty
16906    public Object getTag() {
16907        return mTag;
16908    }
16909
16910    /**
16911     * Sets the tag associated with this view. A tag can be used to mark
16912     * a view in its hierarchy and does not have to be unique within the
16913     * hierarchy. Tags can also be used to store data within a view without
16914     * resorting to another data structure.
16915     *
16916     * @param tag an Object to tag the view with
16917     *
16918     * @see #getTag()
16919     * @see #setTag(int, Object)
16920     */
16921    public void setTag(final Object tag) {
16922        mTag = tag;
16923    }
16924
16925    /**
16926     * Returns the tag associated with this view and the specified key.
16927     *
16928     * @param key The key identifying the tag
16929     *
16930     * @return the Object stored in this view as a tag, or {@code null} if not
16931     *         set
16932     *
16933     * @see #setTag(int, Object)
16934     * @see #getTag()
16935     */
16936    public Object getTag(int key) {
16937        if (mKeyedTags != null) return mKeyedTags.get(key);
16938        return null;
16939    }
16940
16941    /**
16942     * Sets a tag associated with this view and a key. A tag can be used
16943     * to mark a view in its hierarchy and does not have to be unique within
16944     * the hierarchy. Tags can also be used to store data within a view
16945     * without resorting to another data structure.
16946     *
16947     * The specified key should be an id declared in the resources of the
16948     * application to ensure it is unique (see the <a
16949     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
16950     * Keys identified as belonging to
16951     * the Android framework or not associated with any package will cause
16952     * an {@link IllegalArgumentException} to be thrown.
16953     *
16954     * @param key The key identifying the tag
16955     * @param tag An Object to tag the view with
16956     *
16957     * @throws IllegalArgumentException If they specified key is not valid
16958     *
16959     * @see #setTag(Object)
16960     * @see #getTag(int)
16961     */
16962    public void setTag(int key, final Object tag) {
16963        // If the package id is 0x00 or 0x01, it's either an undefined package
16964        // or a framework id
16965        if ((key >>> 24) < 2) {
16966            throw new IllegalArgumentException("The key must be an application-specific "
16967                    + "resource id.");
16968        }
16969
16970        setKeyedTag(key, tag);
16971    }
16972
16973    /**
16974     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
16975     * framework id.
16976     *
16977     * @hide
16978     */
16979    public void setTagInternal(int key, Object tag) {
16980        if ((key >>> 24) != 0x1) {
16981            throw new IllegalArgumentException("The key must be a framework-specific "
16982                    + "resource id.");
16983        }
16984
16985        setKeyedTag(key, tag);
16986    }
16987
16988    private void setKeyedTag(int key, Object tag) {
16989        if (mKeyedTags == null) {
16990            mKeyedTags = new SparseArray<Object>(2);
16991        }
16992
16993        mKeyedTags.put(key, tag);
16994    }
16995
16996    /**
16997     * Prints information about this view in the log output, with the tag
16998     * {@link #VIEW_LOG_TAG}.
16999     *
17000     * @hide
17001     */
17002    public void debug() {
17003        debug(0);
17004    }
17005
17006    /**
17007     * Prints information about this view in the log output, with the tag
17008     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
17009     * indentation defined by the <code>depth</code>.
17010     *
17011     * @param depth the indentation level
17012     *
17013     * @hide
17014     */
17015    protected void debug(int depth) {
17016        String output = debugIndent(depth - 1);
17017
17018        output += "+ " + this;
17019        int id = getId();
17020        if (id != -1) {
17021            output += " (id=" + id + ")";
17022        }
17023        Object tag = getTag();
17024        if (tag != null) {
17025            output += " (tag=" + tag + ")";
17026        }
17027        Log.d(VIEW_LOG_TAG, output);
17028
17029        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
17030            output = debugIndent(depth) + " FOCUSED";
17031            Log.d(VIEW_LOG_TAG, output);
17032        }
17033
17034        output = debugIndent(depth);
17035        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
17036                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
17037                + "} ";
17038        Log.d(VIEW_LOG_TAG, output);
17039
17040        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
17041                || mPaddingBottom != 0) {
17042            output = debugIndent(depth);
17043            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
17044                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
17045            Log.d(VIEW_LOG_TAG, output);
17046        }
17047
17048        output = debugIndent(depth);
17049        output += "mMeasureWidth=" + mMeasuredWidth +
17050                " mMeasureHeight=" + mMeasuredHeight;
17051        Log.d(VIEW_LOG_TAG, output);
17052
17053        output = debugIndent(depth);
17054        if (mLayoutParams == null) {
17055            output += "BAD! no layout params";
17056        } else {
17057            output = mLayoutParams.debug(output);
17058        }
17059        Log.d(VIEW_LOG_TAG, output);
17060
17061        output = debugIndent(depth);
17062        output += "flags={";
17063        output += View.printFlags(mViewFlags);
17064        output += "}";
17065        Log.d(VIEW_LOG_TAG, output);
17066
17067        output = debugIndent(depth);
17068        output += "privateFlags={";
17069        output += View.printPrivateFlags(mPrivateFlags);
17070        output += "}";
17071        Log.d(VIEW_LOG_TAG, output);
17072    }
17073
17074    /**
17075     * Creates a string of whitespaces used for indentation.
17076     *
17077     * @param depth the indentation level
17078     * @return a String containing (depth * 2 + 3) * 2 white spaces
17079     *
17080     * @hide
17081     */
17082    protected static String debugIndent(int depth) {
17083        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
17084        for (int i = 0; i < (depth * 2) + 3; i++) {
17085            spaces.append(' ').append(' ');
17086        }
17087        return spaces.toString();
17088    }
17089
17090    /**
17091     * <p>Return the offset of the widget's text baseline from the widget's top
17092     * boundary. If this widget does not support baseline alignment, this
17093     * method returns -1. </p>
17094     *
17095     * @return the offset of the baseline within the widget's bounds or -1
17096     *         if baseline alignment is not supported
17097     */
17098    @ViewDebug.ExportedProperty(category = "layout")
17099    public int getBaseline() {
17100        return -1;
17101    }
17102
17103    /**
17104     * Returns whether the view hierarchy is currently undergoing a layout pass. This
17105     * information is useful to avoid situations such as calling {@link #requestLayout()} during
17106     * a layout pass.
17107     *
17108     * @return whether the view hierarchy is currently undergoing a layout pass
17109     */
17110    public boolean isInLayout() {
17111        ViewRootImpl viewRoot = getViewRootImpl();
17112        return (viewRoot != null && viewRoot.isInLayout());
17113    }
17114
17115    /**
17116     * Call this when something has changed which has invalidated the
17117     * layout of this view. This will schedule a layout pass of the view
17118     * tree. This should not be called while the view hierarchy is currently in a layout
17119     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
17120     * end of the current layout pass (and then layout will run again) or after the current
17121     * frame is drawn and the next layout occurs.
17122     *
17123     * <p>Subclasses which override this method should call the superclass method to
17124     * handle possible request-during-layout errors correctly.</p>
17125     */
17126    public void requestLayout() {
17127        if (mMeasureCache != null) mMeasureCache.clear();
17128
17129        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
17130            // Only trigger request-during-layout logic if this is the view requesting it,
17131            // not the views in its parent hierarchy
17132            ViewRootImpl viewRoot = getViewRootImpl();
17133            if (viewRoot != null && viewRoot.isInLayout()) {
17134                if (!viewRoot.requestLayoutDuringLayout(this)) {
17135                    return;
17136                }
17137            }
17138            mAttachInfo.mViewRequestingLayout = this;
17139        }
17140
17141        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
17142        mPrivateFlags |= PFLAG_INVALIDATED;
17143
17144        if (mParent != null && !mParent.isLayoutRequested()) {
17145            mParent.requestLayout();
17146        }
17147        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
17148            mAttachInfo.mViewRequestingLayout = null;
17149        }
17150    }
17151
17152    /**
17153     * Forces this view to be laid out during the next layout pass.
17154     * This method does not call requestLayout() or forceLayout()
17155     * on the parent.
17156     */
17157    public void forceLayout() {
17158        if (mMeasureCache != null) mMeasureCache.clear();
17159
17160        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
17161        mPrivateFlags |= PFLAG_INVALIDATED;
17162    }
17163
17164    /**
17165     * <p>
17166     * This is called to find out how big a view should be. The parent
17167     * supplies constraint information in the width and height parameters.
17168     * </p>
17169     *
17170     * <p>
17171     * The actual measurement work of a view is performed in
17172     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
17173     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
17174     * </p>
17175     *
17176     *
17177     * @param widthMeasureSpec Horizontal space requirements as imposed by the
17178     *        parent
17179     * @param heightMeasureSpec Vertical space requirements as imposed by the
17180     *        parent
17181     *
17182     * @see #onMeasure(int, int)
17183     */
17184    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
17185        boolean optical = isLayoutModeOptical(this);
17186        if (optical != isLayoutModeOptical(mParent)) {
17187            Insets insets = getOpticalInsets();
17188            int oWidth  = insets.left + insets.right;
17189            int oHeight = insets.top  + insets.bottom;
17190            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
17191            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
17192        }
17193
17194        // Suppress sign extension for the low bytes
17195        long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
17196        if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
17197
17198        if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ||
17199                widthMeasureSpec != mOldWidthMeasureSpec ||
17200                heightMeasureSpec != mOldHeightMeasureSpec) {
17201
17202            // first clears the measured dimension flag
17203            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
17204
17205            resolveRtlPropertiesIfNeeded();
17206
17207            int cacheIndex = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ? -1 :
17208                    mMeasureCache.indexOfKey(key);
17209            if (cacheIndex < 0 || sIgnoreMeasureCache) {
17210                // measure ourselves, this should set the measured dimension flag back
17211                onMeasure(widthMeasureSpec, heightMeasureSpec);
17212                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
17213            } else {
17214                long value = mMeasureCache.valueAt(cacheIndex);
17215                // Casting a long to int drops the high 32 bits, no mask needed
17216                setMeasuredDimension((int) (value >> 32), (int) value);
17217                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
17218            }
17219
17220            // flag not set, setMeasuredDimension() was not invoked, we raise
17221            // an exception to warn the developer
17222            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
17223                throw new IllegalStateException("onMeasure() did not set the"
17224                        + " measured dimension by calling"
17225                        + " setMeasuredDimension()");
17226            }
17227
17228            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
17229        }
17230
17231        mOldWidthMeasureSpec = widthMeasureSpec;
17232        mOldHeightMeasureSpec = heightMeasureSpec;
17233
17234        mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
17235                (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
17236    }
17237
17238    /**
17239     * <p>
17240     * Measure the view and its content to determine the measured width and the
17241     * measured height. This method is invoked by {@link #measure(int, int)} and
17242     * should be overriden by subclasses to provide accurate and efficient
17243     * measurement of their contents.
17244     * </p>
17245     *
17246     * <p>
17247     * <strong>CONTRACT:</strong> When overriding this method, you
17248     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
17249     * measured width and height of this view. Failure to do so will trigger an
17250     * <code>IllegalStateException</code>, thrown by
17251     * {@link #measure(int, int)}. Calling the superclass'
17252     * {@link #onMeasure(int, int)} is a valid use.
17253     * </p>
17254     *
17255     * <p>
17256     * The base class implementation of measure defaults to the background size,
17257     * unless a larger size is allowed by the MeasureSpec. Subclasses should
17258     * override {@link #onMeasure(int, int)} to provide better measurements of
17259     * their content.
17260     * </p>
17261     *
17262     * <p>
17263     * If this method is overridden, it is the subclass's responsibility to make
17264     * sure the measured height and width are at least the view's minimum height
17265     * and width ({@link #getSuggestedMinimumHeight()} and
17266     * {@link #getSuggestedMinimumWidth()}).
17267     * </p>
17268     *
17269     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
17270     *                         The requirements are encoded with
17271     *                         {@link android.view.View.MeasureSpec}.
17272     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
17273     *                         The requirements are encoded with
17274     *                         {@link android.view.View.MeasureSpec}.
17275     *
17276     * @see #getMeasuredWidth()
17277     * @see #getMeasuredHeight()
17278     * @see #setMeasuredDimension(int, int)
17279     * @see #getSuggestedMinimumHeight()
17280     * @see #getSuggestedMinimumWidth()
17281     * @see android.view.View.MeasureSpec#getMode(int)
17282     * @see android.view.View.MeasureSpec#getSize(int)
17283     */
17284    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
17285        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
17286                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
17287    }
17288
17289    /**
17290     * <p>This method must be called by {@link #onMeasure(int, int)} to store the
17291     * measured width and measured height. Failing to do so will trigger an
17292     * exception at measurement time.</p>
17293     *
17294     * @param measuredWidth The measured width of this view.  May be a complex
17295     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17296     * {@link #MEASURED_STATE_TOO_SMALL}.
17297     * @param measuredHeight The measured height of this view.  May be a complex
17298     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17299     * {@link #MEASURED_STATE_TOO_SMALL}.
17300     */
17301    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
17302        boolean optical = isLayoutModeOptical(this);
17303        if (optical != isLayoutModeOptical(mParent)) {
17304            Insets insets = getOpticalInsets();
17305            int opticalWidth  = insets.left + insets.right;
17306            int opticalHeight = insets.top  + insets.bottom;
17307
17308            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
17309            measuredHeight += optical ? opticalHeight : -opticalHeight;
17310        }
17311        mMeasuredWidth = measuredWidth;
17312        mMeasuredHeight = measuredHeight;
17313
17314        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
17315    }
17316
17317    /**
17318     * Merge two states as returned by {@link #getMeasuredState()}.
17319     * @param curState The current state as returned from a view or the result
17320     * of combining multiple views.
17321     * @param newState The new view state to combine.
17322     * @return Returns a new integer reflecting the combination of the two
17323     * states.
17324     */
17325    public static int combineMeasuredStates(int curState, int newState) {
17326        return curState | newState;
17327    }
17328
17329    /**
17330     * Version of {@link #resolveSizeAndState(int, int, int)}
17331     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
17332     */
17333    public static int resolveSize(int size, int measureSpec) {
17334        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
17335    }
17336
17337    /**
17338     * Utility to reconcile a desired size and state, with constraints imposed
17339     * by a MeasureSpec.  Will take the desired size, unless a different size
17340     * is imposed by the constraints.  The returned value is a compound integer,
17341     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
17342     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
17343     * size is smaller than the size the view wants to be.
17344     *
17345     * @param size How big the view wants to be
17346     * @param measureSpec Constraints imposed by the parent
17347     * @return Size information bit mask as defined by
17348     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
17349     */
17350    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
17351        int result = size;
17352        int specMode = MeasureSpec.getMode(measureSpec);
17353        int specSize =  MeasureSpec.getSize(measureSpec);
17354        switch (specMode) {
17355        case MeasureSpec.UNSPECIFIED:
17356            result = size;
17357            break;
17358        case MeasureSpec.AT_MOST:
17359            if (specSize < size) {
17360                result = specSize | MEASURED_STATE_TOO_SMALL;
17361            } else {
17362                result = size;
17363            }
17364            break;
17365        case MeasureSpec.EXACTLY:
17366            result = specSize;
17367            break;
17368        }
17369        return result | (childMeasuredState&MEASURED_STATE_MASK);
17370    }
17371
17372    /**
17373     * Utility to return a default size. Uses the supplied size if the
17374     * MeasureSpec imposed no constraints. Will get larger if allowed
17375     * by the MeasureSpec.
17376     *
17377     * @param size Default size for this view
17378     * @param measureSpec Constraints imposed by the parent
17379     * @return The size this view should be.
17380     */
17381    public static int getDefaultSize(int size, int measureSpec) {
17382        int result = size;
17383        int specMode = MeasureSpec.getMode(measureSpec);
17384        int specSize = MeasureSpec.getSize(measureSpec);
17385
17386        switch (specMode) {
17387        case MeasureSpec.UNSPECIFIED:
17388            result = size;
17389            break;
17390        case MeasureSpec.AT_MOST:
17391        case MeasureSpec.EXACTLY:
17392            result = specSize;
17393            break;
17394        }
17395        return result;
17396    }
17397
17398    /**
17399     * Returns the suggested minimum height that the view should use. This
17400     * returns the maximum of the view's minimum height
17401     * and the background's minimum height
17402     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
17403     * <p>
17404     * When being used in {@link #onMeasure(int, int)}, the caller should still
17405     * ensure the returned height is within the requirements of the parent.
17406     *
17407     * @return The suggested minimum height of the view.
17408     */
17409    protected int getSuggestedMinimumHeight() {
17410        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
17411
17412    }
17413
17414    /**
17415     * Returns the suggested minimum width that the view should use. This
17416     * returns the maximum of the view's minimum width)
17417     * and the background's minimum width
17418     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
17419     * <p>
17420     * When being used in {@link #onMeasure(int, int)}, the caller should still
17421     * ensure the returned width is within the requirements of the parent.
17422     *
17423     * @return The suggested minimum width of the view.
17424     */
17425    protected int getSuggestedMinimumWidth() {
17426        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
17427    }
17428
17429    /**
17430     * Returns the minimum height of the view.
17431     *
17432     * @return the minimum height the view will try to be.
17433     *
17434     * @see #setMinimumHeight(int)
17435     *
17436     * @attr ref android.R.styleable#View_minHeight
17437     */
17438    public int getMinimumHeight() {
17439        return mMinHeight;
17440    }
17441
17442    /**
17443     * Sets the minimum height of the view. It is not guaranteed the view will
17444     * be able to achieve this minimum height (for example, if its parent layout
17445     * constrains it with less available height).
17446     *
17447     * @param minHeight The minimum height the view will try to be.
17448     *
17449     * @see #getMinimumHeight()
17450     *
17451     * @attr ref android.R.styleable#View_minHeight
17452     */
17453    public void setMinimumHeight(int minHeight) {
17454        mMinHeight = minHeight;
17455        requestLayout();
17456    }
17457
17458    /**
17459     * Returns the minimum width of the view.
17460     *
17461     * @return the minimum width the view will try to be.
17462     *
17463     * @see #setMinimumWidth(int)
17464     *
17465     * @attr ref android.R.styleable#View_minWidth
17466     */
17467    public int getMinimumWidth() {
17468        return mMinWidth;
17469    }
17470
17471    /**
17472     * Sets the minimum width of the view. It is not guaranteed the view will
17473     * be able to achieve this minimum width (for example, if its parent layout
17474     * constrains it with less available width).
17475     *
17476     * @param minWidth The minimum width the view will try to be.
17477     *
17478     * @see #getMinimumWidth()
17479     *
17480     * @attr ref android.R.styleable#View_minWidth
17481     */
17482    public void setMinimumWidth(int minWidth) {
17483        mMinWidth = minWidth;
17484        requestLayout();
17485
17486    }
17487
17488    /**
17489     * Get the animation currently associated with this view.
17490     *
17491     * @return The animation that is currently playing or
17492     *         scheduled to play for this view.
17493     */
17494    public Animation getAnimation() {
17495        return mCurrentAnimation;
17496    }
17497
17498    /**
17499     * Start the specified animation now.
17500     *
17501     * @param animation the animation to start now
17502     */
17503    public void startAnimation(Animation animation) {
17504        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
17505        setAnimation(animation);
17506        invalidateParentCaches();
17507        invalidate(true);
17508    }
17509
17510    /**
17511     * Cancels any animations for this view.
17512     */
17513    public void clearAnimation() {
17514        if (mCurrentAnimation != null) {
17515            mCurrentAnimation.detach();
17516        }
17517        mCurrentAnimation = null;
17518        invalidateParentIfNeeded();
17519    }
17520
17521    /**
17522     * Sets the next animation to play for this view.
17523     * If you want the animation to play immediately, use
17524     * {@link #startAnimation(android.view.animation.Animation)} instead.
17525     * This method provides allows fine-grained
17526     * control over the start time and invalidation, but you
17527     * must make sure that 1) the animation has a start time set, and
17528     * 2) the view's parent (which controls animations on its children)
17529     * will be invalidated when the animation is supposed to
17530     * start.
17531     *
17532     * @param animation The next animation, or null.
17533     */
17534    public void setAnimation(Animation animation) {
17535        mCurrentAnimation = animation;
17536
17537        if (animation != null) {
17538            // If the screen is off assume the animation start time is now instead of
17539            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
17540            // would cause the animation to start when the screen turns back on
17541            if (mAttachInfo != null && !mAttachInfo.mScreenOn &&
17542                    animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
17543                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
17544            }
17545            animation.reset();
17546        }
17547    }
17548
17549    /**
17550     * Invoked by a parent ViewGroup to notify the start of the animation
17551     * currently associated with this view. If you override this method,
17552     * always call super.onAnimationStart();
17553     *
17554     * @see #setAnimation(android.view.animation.Animation)
17555     * @see #getAnimation()
17556     */
17557    protected void onAnimationStart() {
17558        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
17559    }
17560
17561    /**
17562     * Invoked by a parent ViewGroup to notify the end of the animation
17563     * currently associated with this view. If you override this method,
17564     * always call super.onAnimationEnd();
17565     *
17566     * @see #setAnimation(android.view.animation.Animation)
17567     * @see #getAnimation()
17568     */
17569    protected void onAnimationEnd() {
17570        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
17571    }
17572
17573    /**
17574     * Invoked if there is a Transform that involves alpha. Subclass that can
17575     * draw themselves with the specified alpha should return true, and then
17576     * respect that alpha when their onDraw() is called. If this returns false
17577     * then the view may be redirected to draw into an offscreen buffer to
17578     * fulfill the request, which will look fine, but may be slower than if the
17579     * subclass handles it internally. The default implementation returns false.
17580     *
17581     * @param alpha The alpha (0..255) to apply to the view's drawing
17582     * @return true if the view can draw with the specified alpha.
17583     */
17584    protected boolean onSetAlpha(int alpha) {
17585        return false;
17586    }
17587
17588    /**
17589     * This is used by the RootView to perform an optimization when
17590     * the view hierarchy contains one or several SurfaceView.
17591     * SurfaceView is always considered transparent, but its children are not,
17592     * therefore all View objects remove themselves from the global transparent
17593     * region (passed as a parameter to this function).
17594     *
17595     * @param region The transparent region for this ViewAncestor (window).
17596     *
17597     * @return Returns true if the effective visibility of the view at this
17598     * point is opaque, regardless of the transparent region; returns false
17599     * if it is possible for underlying windows to be seen behind the view.
17600     *
17601     * {@hide}
17602     */
17603    public boolean gatherTransparentRegion(Region region) {
17604        final AttachInfo attachInfo = mAttachInfo;
17605        if (region != null && attachInfo != null) {
17606            final int pflags = mPrivateFlags;
17607            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
17608                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
17609                // remove it from the transparent region.
17610                final int[] location = attachInfo.mTransparentLocation;
17611                getLocationInWindow(location);
17612                region.op(location[0], location[1], location[0] + mRight - mLeft,
17613                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
17614            } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) {
17615                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
17616                // exists, so we remove the background drawable's non-transparent
17617                // parts from this transparent region.
17618                applyDrawableToTransparentRegion(mBackground, region);
17619            }
17620        }
17621        return true;
17622    }
17623
17624    /**
17625     * Play a sound effect for this view.
17626     *
17627     * <p>The framework will play sound effects for some built in actions, such as
17628     * clicking, but you may wish to play these effects in your widget,
17629     * for instance, for internal navigation.
17630     *
17631     * <p>The sound effect will only be played if sound effects are enabled by the user, and
17632     * {@link #isSoundEffectsEnabled()} is true.
17633     *
17634     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
17635     */
17636    public void playSoundEffect(int soundConstant) {
17637        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
17638            return;
17639        }
17640        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
17641    }
17642
17643    /**
17644     * BZZZTT!!1!
17645     *
17646     * <p>Provide haptic feedback to the user for this view.
17647     *
17648     * <p>The framework will provide haptic feedback for some built in actions,
17649     * such as long presses, but you may wish to provide feedback for your
17650     * own widget.
17651     *
17652     * <p>The feedback will only be performed if
17653     * {@link #isHapticFeedbackEnabled()} is true.
17654     *
17655     * @param feedbackConstant One of the constants defined in
17656     * {@link HapticFeedbackConstants}
17657     */
17658    public boolean performHapticFeedback(int feedbackConstant) {
17659        return performHapticFeedback(feedbackConstant, 0);
17660    }
17661
17662    /**
17663     * BZZZTT!!1!
17664     *
17665     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
17666     *
17667     * @param feedbackConstant One of the constants defined in
17668     * {@link HapticFeedbackConstants}
17669     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
17670     */
17671    public boolean performHapticFeedback(int feedbackConstant, int flags) {
17672        if (mAttachInfo == null) {
17673            return false;
17674        }
17675        //noinspection SimplifiableIfStatement
17676        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
17677                && !isHapticFeedbackEnabled()) {
17678            return false;
17679        }
17680        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
17681                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
17682    }
17683
17684    /**
17685     * Request that the visibility of the status bar or other screen/window
17686     * decorations be changed.
17687     *
17688     * <p>This method is used to put the over device UI into temporary modes
17689     * where the user's attention is focused more on the application content,
17690     * by dimming or hiding surrounding system affordances.  This is typically
17691     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
17692     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
17693     * to be placed behind the action bar (and with these flags other system
17694     * affordances) so that smooth transitions between hiding and showing them
17695     * can be done.
17696     *
17697     * <p>Two representative examples of the use of system UI visibility is
17698     * implementing a content browsing application (like a magazine reader)
17699     * and a video playing application.
17700     *
17701     * <p>The first code shows a typical implementation of a View in a content
17702     * browsing application.  In this implementation, the application goes
17703     * into a content-oriented mode by hiding the status bar and action bar,
17704     * and putting the navigation elements into lights out mode.  The user can
17705     * then interact with content while in this mode.  Such an application should
17706     * provide an easy way for the user to toggle out of the mode (such as to
17707     * check information in the status bar or access notifications).  In the
17708     * implementation here, this is done simply by tapping on the content.
17709     *
17710     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
17711     *      content}
17712     *
17713     * <p>This second code sample shows a typical implementation of a View
17714     * in a video playing application.  In this situation, while the video is
17715     * playing the application would like to go into a complete full-screen mode,
17716     * to use as much of the display as possible for the video.  When in this state
17717     * the user can not interact with the application; the system intercepts
17718     * touching on the screen to pop the UI out of full screen mode.  See
17719     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
17720     *
17721     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
17722     *      content}
17723     *
17724     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
17725     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
17726     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
17727     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
17728     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
17729     */
17730    public void setSystemUiVisibility(int visibility) {
17731        if (visibility != mSystemUiVisibility) {
17732            mSystemUiVisibility = visibility;
17733            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
17734                mParent.recomputeViewAttributes(this);
17735            }
17736        }
17737    }
17738
17739    /**
17740     * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested.
17741     * @return  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 int getSystemUiVisibility() {
17748        return mSystemUiVisibility;
17749    }
17750
17751    /**
17752     * Returns the current system UI visibility that is currently set for
17753     * the entire window.  This is the combination of the
17754     * {@link #setSystemUiVisibility(int)} values supplied by all of the
17755     * views in the window.
17756     */
17757    public int getWindowSystemUiVisibility() {
17758        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
17759    }
17760
17761    /**
17762     * Override to find out when the window's requested system UI visibility
17763     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
17764     * This is different from the callbacks received through
17765     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
17766     * in that this is only telling you about the local request of the window,
17767     * not the actual values applied by the system.
17768     */
17769    public void onWindowSystemUiVisibilityChanged(int visible) {
17770    }
17771
17772    /**
17773     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
17774     * the view hierarchy.
17775     */
17776    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
17777        onWindowSystemUiVisibilityChanged(visible);
17778    }
17779
17780    /**
17781     * Set a listener to receive callbacks when the visibility of the system bar changes.
17782     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
17783     */
17784    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
17785        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
17786        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
17787            mParent.recomputeViewAttributes(this);
17788        }
17789    }
17790
17791    /**
17792     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
17793     * the view hierarchy.
17794     */
17795    public void dispatchSystemUiVisibilityChanged(int visibility) {
17796        ListenerInfo li = mListenerInfo;
17797        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
17798            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
17799                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
17800        }
17801    }
17802
17803    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
17804        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
17805        if (val != mSystemUiVisibility) {
17806            setSystemUiVisibility(val);
17807            return true;
17808        }
17809        return false;
17810    }
17811
17812    /** @hide */
17813    public void setDisabledSystemUiVisibility(int flags) {
17814        if (mAttachInfo != null) {
17815            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
17816                mAttachInfo.mDisabledSystemUiVisibility = flags;
17817                if (mParent != null) {
17818                    mParent.recomputeViewAttributes(this);
17819                }
17820            }
17821        }
17822    }
17823
17824    /**
17825     * Creates an image that the system displays during the drag and drop
17826     * operation. This is called a &quot;drag shadow&quot;. The default implementation
17827     * for a DragShadowBuilder based on a View returns an image that has exactly the same
17828     * appearance as the given View. The default also positions the center of the drag shadow
17829     * directly under the touch point. If no View is provided (the constructor with no parameters
17830     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
17831     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
17832     * default is an invisible drag shadow.
17833     * <p>
17834     * You are not required to use the View you provide to the constructor as the basis of the
17835     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
17836     * anything you want as the drag shadow.
17837     * </p>
17838     * <p>
17839     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
17840     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
17841     *  size and position of the drag shadow. It uses this data to construct a
17842     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
17843     *  so that your application can draw the shadow image in the Canvas.
17844     * </p>
17845     *
17846     * <div class="special reference">
17847     * <h3>Developer Guides</h3>
17848     * <p>For a guide to implementing drag and drop features, read the
17849     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
17850     * </div>
17851     */
17852    public static class DragShadowBuilder {
17853        private final WeakReference<View> mView;
17854
17855        /**
17856         * Constructs a shadow image builder based on a View. By default, the resulting drag
17857         * shadow will have the same appearance and dimensions as the View, with the touch point
17858         * over the center of the View.
17859         * @param view A View. Any View in scope can be used.
17860         */
17861        public DragShadowBuilder(View view) {
17862            mView = new WeakReference<View>(view);
17863        }
17864
17865        /**
17866         * Construct a shadow builder object with no associated View.  This
17867         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
17868         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
17869         * to supply the drag shadow's dimensions and appearance without
17870         * reference to any View object. If they are not overridden, then the result is an
17871         * invisible drag shadow.
17872         */
17873        public DragShadowBuilder() {
17874            mView = new WeakReference<View>(null);
17875        }
17876
17877        /**
17878         * Returns the View object that had been passed to the
17879         * {@link #View.DragShadowBuilder(View)}
17880         * constructor.  If that View parameter was {@code null} or if the
17881         * {@link #View.DragShadowBuilder()}
17882         * constructor was used to instantiate the builder object, this method will return
17883         * null.
17884         *
17885         * @return The View object associate with this builder object.
17886         */
17887        @SuppressWarnings({"JavadocReference"})
17888        final public View getView() {
17889            return mView.get();
17890        }
17891
17892        /**
17893         * Provides the metrics for the shadow image. These include the dimensions of
17894         * the shadow image, and the point within that shadow that should
17895         * be centered under the touch location while dragging.
17896         * <p>
17897         * The default implementation sets the dimensions of the shadow to be the
17898         * same as the dimensions of the View itself and centers the shadow under
17899         * the touch point.
17900         * </p>
17901         *
17902         * @param shadowSize A {@link android.graphics.Point} containing the width and height
17903         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
17904         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
17905         * image.
17906         *
17907         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
17908         * shadow image that should be underneath the touch point during the drag and drop
17909         * operation. Your application must set {@link android.graphics.Point#x} to the
17910         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
17911         */
17912        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
17913            final View view = mView.get();
17914            if (view != null) {
17915                shadowSize.set(view.getWidth(), view.getHeight());
17916                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
17917            } else {
17918                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
17919            }
17920        }
17921
17922        /**
17923         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
17924         * based on the dimensions it received from the
17925         * {@link #onProvideShadowMetrics(Point, Point)} callback.
17926         *
17927         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
17928         */
17929        public void onDrawShadow(Canvas canvas) {
17930            final View view = mView.get();
17931            if (view != null) {
17932                view.draw(canvas);
17933            } else {
17934                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
17935            }
17936        }
17937    }
17938
17939    /**
17940     * Starts a drag and drop operation. When your application calls this method, it passes a
17941     * {@link android.view.View.DragShadowBuilder} object to the system. The
17942     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
17943     * to get metrics for the drag shadow, and then calls the object's
17944     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
17945     * <p>
17946     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
17947     *  drag events to all the View objects in your application that are currently visible. It does
17948     *  this either by calling the View object's drag listener (an implementation of
17949     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
17950     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
17951     *  Both are passed a {@link android.view.DragEvent} object that has a
17952     *  {@link android.view.DragEvent#getAction()} value of
17953     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
17954     * </p>
17955     * <p>
17956     * Your application can invoke startDrag() on any attached View object. The View object does not
17957     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
17958     * be related to the View the user selected for dragging.
17959     * </p>
17960     * @param data A {@link android.content.ClipData} object pointing to the data to be
17961     * transferred by the drag and drop operation.
17962     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
17963     * drag shadow.
17964     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
17965     * drop operation. This Object is put into every DragEvent object sent by the system during the
17966     * current drag.
17967     * <p>
17968     * myLocalState is a lightweight mechanism for the sending information from the dragged View
17969     * to the target Views. For example, it can contain flags that differentiate between a
17970     * a copy operation and a move operation.
17971     * </p>
17972     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
17973     * so the parameter should be set to 0.
17974     * @return {@code true} if the method completes successfully, or
17975     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
17976     * do a drag, and so no drag operation is in progress.
17977     */
17978    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
17979            Object myLocalState, int flags) {
17980        if (ViewDebug.DEBUG_DRAG) {
17981            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
17982        }
17983        boolean okay = false;
17984
17985        Point shadowSize = new Point();
17986        Point shadowTouchPoint = new Point();
17987        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
17988
17989        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
17990                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
17991            throw new IllegalStateException("Drag shadow dimensions must not be negative");
17992        }
17993
17994        if (ViewDebug.DEBUG_DRAG) {
17995            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
17996                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
17997        }
17998        Surface surface = new Surface();
17999        try {
18000            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
18001                    flags, shadowSize.x, shadowSize.y, surface);
18002            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
18003                    + " surface=" + surface);
18004            if (token != null) {
18005                Canvas canvas = surface.lockCanvas(null);
18006                try {
18007                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
18008                    shadowBuilder.onDrawShadow(canvas);
18009                } finally {
18010                    surface.unlockCanvasAndPost(canvas);
18011                }
18012
18013                final ViewRootImpl root = getViewRootImpl();
18014
18015                // Cache the local state object for delivery with DragEvents
18016                root.setLocalDragState(myLocalState);
18017
18018                // repurpose 'shadowSize' for the last touch point
18019                root.getLastTouchPoint(shadowSize);
18020
18021                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
18022                        shadowSize.x, shadowSize.y,
18023                        shadowTouchPoint.x, shadowTouchPoint.y, data);
18024                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
18025
18026                // Off and running!  Release our local surface instance; the drag
18027                // shadow surface is now managed by the system process.
18028                surface.release();
18029            }
18030        } catch (Exception e) {
18031            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
18032            surface.destroy();
18033        }
18034
18035        return okay;
18036    }
18037
18038    /**
18039     * Handles drag events sent by the system following a call to
18040     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
18041     *<p>
18042     * When the system calls this method, it passes a
18043     * {@link android.view.DragEvent} object. A call to
18044     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
18045     * in DragEvent. The method uses these to determine what is happening in the drag and drop
18046     * operation.
18047     * @param event The {@link android.view.DragEvent} sent by the system.
18048     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
18049     * in DragEvent, indicating the type of drag event represented by this object.
18050     * @return {@code true} if the method was successful, otherwise {@code false}.
18051     * <p>
18052     *  The method should return {@code true} in response to an action type of
18053     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
18054     *  operation.
18055     * </p>
18056     * <p>
18057     *  The method should also return {@code true} in response to an action type of
18058     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
18059     *  {@code false} if it didn't.
18060     * </p>
18061     */
18062    public boolean onDragEvent(DragEvent event) {
18063        return false;
18064    }
18065
18066    /**
18067     * Detects if this View is enabled and has a drag event listener.
18068     * If both are true, then it calls the drag event listener with the
18069     * {@link android.view.DragEvent} it received. If the drag event listener returns
18070     * {@code true}, then dispatchDragEvent() returns {@code true}.
18071     * <p>
18072     * For all other cases, the method calls the
18073     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
18074     * method and returns its result.
18075     * </p>
18076     * <p>
18077     * This ensures that a drag event is always consumed, even if the View does not have a drag
18078     * event listener. However, if the View has a listener and the listener returns true, then
18079     * onDragEvent() is not called.
18080     * </p>
18081     */
18082    public boolean dispatchDragEvent(DragEvent event) {
18083        ListenerInfo li = mListenerInfo;
18084        //noinspection SimplifiableIfStatement
18085        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
18086                && li.mOnDragListener.onDrag(this, event)) {
18087            return true;
18088        }
18089        return onDragEvent(event);
18090    }
18091
18092    boolean canAcceptDrag() {
18093        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
18094    }
18095
18096    /**
18097     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
18098     * it is ever exposed at all.
18099     * @hide
18100     */
18101    public void onCloseSystemDialogs(String reason) {
18102    }
18103
18104    /**
18105     * Given a Drawable whose bounds have been set to draw into this view,
18106     * update a Region being computed for
18107     * {@link #gatherTransparentRegion(android.graphics.Region)} so
18108     * that any non-transparent parts of the Drawable are removed from the
18109     * given transparent region.
18110     *
18111     * @param dr The Drawable whose transparency is to be applied to the region.
18112     * @param region A Region holding the current transparency information,
18113     * where any parts of the region that are set are considered to be
18114     * transparent.  On return, this region will be modified to have the
18115     * transparency information reduced by the corresponding parts of the
18116     * Drawable that are not transparent.
18117     * {@hide}
18118     */
18119    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
18120        if (DBG) {
18121            Log.i("View", "Getting transparent region for: " + this);
18122        }
18123        final Region r = dr.getTransparentRegion();
18124        final Rect db = dr.getBounds();
18125        final AttachInfo attachInfo = mAttachInfo;
18126        if (r != null && attachInfo != null) {
18127            final int w = getRight()-getLeft();
18128            final int h = getBottom()-getTop();
18129            if (db.left > 0) {
18130                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
18131                r.op(0, 0, db.left, h, Region.Op.UNION);
18132            }
18133            if (db.right < w) {
18134                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
18135                r.op(db.right, 0, w, h, Region.Op.UNION);
18136            }
18137            if (db.top > 0) {
18138                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
18139                r.op(0, 0, w, db.top, Region.Op.UNION);
18140            }
18141            if (db.bottom < h) {
18142                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
18143                r.op(0, db.bottom, w, h, Region.Op.UNION);
18144            }
18145            final int[] location = attachInfo.mTransparentLocation;
18146            getLocationInWindow(location);
18147            r.translate(location[0], location[1]);
18148            region.op(r, Region.Op.INTERSECT);
18149        } else {
18150            region.op(db, Region.Op.DIFFERENCE);
18151        }
18152    }
18153
18154    private void checkForLongClick(int delayOffset) {
18155        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
18156            mHasPerformedLongPress = false;
18157
18158            if (mPendingCheckForLongPress == null) {
18159                mPendingCheckForLongPress = new CheckForLongPress();
18160            }
18161            mPendingCheckForLongPress.rememberWindowAttachCount();
18162            postDelayed(mPendingCheckForLongPress,
18163                    ViewConfiguration.getLongPressTimeout() - delayOffset);
18164        }
18165    }
18166
18167    /**
18168     * Inflate a view from an XML resource.  This convenience method wraps the {@link
18169     * LayoutInflater} class, which provides a full range of options for view inflation.
18170     *
18171     * @param context The Context object for your activity or application.
18172     * @param resource The resource ID to inflate
18173     * @param root A view group that will be the parent.  Used to properly inflate the
18174     * layout_* parameters.
18175     * @see LayoutInflater
18176     */
18177    public static View inflate(Context context, int resource, ViewGroup root) {
18178        LayoutInflater factory = LayoutInflater.from(context);
18179        return factory.inflate(resource, root);
18180    }
18181
18182    /**
18183     * Scroll the view with standard behavior for scrolling beyond the normal
18184     * content boundaries. Views that call this method should override
18185     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
18186     * results of an over-scroll operation.
18187     *
18188     * Views can use this method to handle any touch or fling-based scrolling.
18189     *
18190     * @param deltaX Change in X in pixels
18191     * @param deltaY Change in Y in pixels
18192     * @param scrollX Current X scroll value in pixels before applying deltaX
18193     * @param scrollY Current Y scroll value in pixels before applying deltaY
18194     * @param scrollRangeX Maximum content scroll range along the X axis
18195     * @param scrollRangeY Maximum content scroll range along the Y axis
18196     * @param maxOverScrollX Number of pixels to overscroll by in either direction
18197     *          along the X axis.
18198     * @param maxOverScrollY Number of pixels to overscroll by in either direction
18199     *          along the Y axis.
18200     * @param isTouchEvent true if this scroll operation is the result of a touch event.
18201     * @return true if scrolling was clamped to an over-scroll boundary along either
18202     *          axis, false otherwise.
18203     */
18204    @SuppressWarnings({"UnusedParameters"})
18205    protected boolean overScrollBy(int deltaX, int deltaY,
18206            int scrollX, int scrollY,
18207            int scrollRangeX, int scrollRangeY,
18208            int maxOverScrollX, int maxOverScrollY,
18209            boolean isTouchEvent) {
18210        final int overScrollMode = mOverScrollMode;
18211        final boolean canScrollHorizontal =
18212                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
18213        final boolean canScrollVertical =
18214                computeVerticalScrollRange() > computeVerticalScrollExtent();
18215        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
18216                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
18217        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
18218                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
18219
18220        int newScrollX = scrollX + deltaX;
18221        if (!overScrollHorizontal) {
18222            maxOverScrollX = 0;
18223        }
18224
18225        int newScrollY = scrollY + deltaY;
18226        if (!overScrollVertical) {
18227            maxOverScrollY = 0;
18228        }
18229
18230        // Clamp values if at the limits and record
18231        final int left = -maxOverScrollX;
18232        final int right = maxOverScrollX + scrollRangeX;
18233        final int top = -maxOverScrollY;
18234        final int bottom = maxOverScrollY + scrollRangeY;
18235
18236        boolean clampedX = false;
18237        if (newScrollX > right) {
18238            newScrollX = right;
18239            clampedX = true;
18240        } else if (newScrollX < left) {
18241            newScrollX = left;
18242            clampedX = true;
18243        }
18244
18245        boolean clampedY = false;
18246        if (newScrollY > bottom) {
18247            newScrollY = bottom;
18248            clampedY = true;
18249        } else if (newScrollY < top) {
18250            newScrollY = top;
18251            clampedY = true;
18252        }
18253
18254        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
18255
18256        return clampedX || clampedY;
18257    }
18258
18259    /**
18260     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
18261     * respond to the results of an over-scroll operation.
18262     *
18263     * @param scrollX New X scroll value in pixels
18264     * @param scrollY New Y scroll value in pixels
18265     * @param clampedX True if scrollX was clamped to an over-scroll boundary
18266     * @param clampedY True if scrollY was clamped to an over-scroll boundary
18267     */
18268    protected void onOverScrolled(int scrollX, int scrollY,
18269            boolean clampedX, boolean clampedY) {
18270        // Intentionally empty.
18271    }
18272
18273    /**
18274     * Returns the over-scroll mode for this view. The result will be
18275     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
18276     * (allow over-scrolling only if the view content is larger than the container),
18277     * or {@link #OVER_SCROLL_NEVER}.
18278     *
18279     * @return This view's over-scroll mode.
18280     */
18281    public int getOverScrollMode() {
18282        return mOverScrollMode;
18283    }
18284
18285    /**
18286     * Set the over-scroll mode for this view. Valid over-scroll modes are
18287     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
18288     * (allow over-scrolling only if the view content is larger than the container),
18289     * or {@link #OVER_SCROLL_NEVER}.
18290     *
18291     * Setting the over-scroll mode of a view will have an effect only if the
18292     * view is capable of scrolling.
18293     *
18294     * @param overScrollMode The new over-scroll mode for this view.
18295     */
18296    public void setOverScrollMode(int overScrollMode) {
18297        if (overScrollMode != OVER_SCROLL_ALWAYS &&
18298                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
18299                overScrollMode != OVER_SCROLL_NEVER) {
18300            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
18301        }
18302        mOverScrollMode = overScrollMode;
18303    }
18304
18305    /**
18306     * Gets a scale factor that determines the distance the view should scroll
18307     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
18308     * @return The vertical scroll scale factor.
18309     * @hide
18310     */
18311    protected float getVerticalScrollFactor() {
18312        if (mVerticalScrollFactor == 0) {
18313            TypedValue outValue = new TypedValue();
18314            if (!mContext.getTheme().resolveAttribute(
18315                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
18316                throw new IllegalStateException(
18317                        "Expected theme to define listPreferredItemHeight.");
18318            }
18319            mVerticalScrollFactor = outValue.getDimension(
18320                    mContext.getResources().getDisplayMetrics());
18321        }
18322        return mVerticalScrollFactor;
18323    }
18324
18325    /**
18326     * Gets a scale factor that determines the distance the view should scroll
18327     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
18328     * @return The horizontal scroll scale factor.
18329     * @hide
18330     */
18331    protected float getHorizontalScrollFactor() {
18332        // TODO: Should use something else.
18333        return getVerticalScrollFactor();
18334    }
18335
18336    /**
18337     * Return the value specifying the text direction or policy that was set with
18338     * {@link #setTextDirection(int)}.
18339     *
18340     * @return the defined text direction. It can be one of:
18341     *
18342     * {@link #TEXT_DIRECTION_INHERIT},
18343     * {@link #TEXT_DIRECTION_FIRST_STRONG}
18344     * {@link #TEXT_DIRECTION_ANY_RTL},
18345     * {@link #TEXT_DIRECTION_LTR},
18346     * {@link #TEXT_DIRECTION_RTL},
18347     * {@link #TEXT_DIRECTION_LOCALE}
18348     *
18349     * @attr ref android.R.styleable#View_textDirection
18350     *
18351     * @hide
18352     */
18353    @ViewDebug.ExportedProperty(category = "text", mapping = {
18354            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
18355            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
18356            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
18357            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
18358            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
18359            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
18360    })
18361    public int getRawTextDirection() {
18362        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
18363    }
18364
18365    /**
18366     * Set the text direction.
18367     *
18368     * @param textDirection the direction to set. Should be one of:
18369     *
18370     * {@link #TEXT_DIRECTION_INHERIT},
18371     * {@link #TEXT_DIRECTION_FIRST_STRONG}
18372     * {@link #TEXT_DIRECTION_ANY_RTL},
18373     * {@link #TEXT_DIRECTION_LTR},
18374     * {@link #TEXT_DIRECTION_RTL},
18375     * {@link #TEXT_DIRECTION_LOCALE}
18376     *
18377     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
18378     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
18379     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
18380     *
18381     * @attr ref android.R.styleable#View_textDirection
18382     */
18383    public void setTextDirection(int textDirection) {
18384        if (getRawTextDirection() != textDirection) {
18385            // Reset the current text direction and the resolved one
18386            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
18387            resetResolvedTextDirection();
18388            // Set the new text direction
18389            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
18390            // Do resolution
18391            resolveTextDirection();
18392            // Notify change
18393            onRtlPropertiesChanged(getLayoutDirection());
18394            // Refresh
18395            requestLayout();
18396            invalidate(true);
18397        }
18398    }
18399
18400    /**
18401     * Return the resolved text direction.
18402     *
18403     * @return the resolved text direction. Returns one of:
18404     *
18405     * {@link #TEXT_DIRECTION_FIRST_STRONG}
18406     * {@link #TEXT_DIRECTION_ANY_RTL},
18407     * {@link #TEXT_DIRECTION_LTR},
18408     * {@link #TEXT_DIRECTION_RTL},
18409     * {@link #TEXT_DIRECTION_LOCALE}
18410     *
18411     * @attr ref android.R.styleable#View_textDirection
18412     */
18413    @ViewDebug.ExportedProperty(category = "text", mapping = {
18414            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
18415            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
18416            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
18417            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
18418            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
18419            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
18420    })
18421    public int getTextDirection() {
18422        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
18423    }
18424
18425    /**
18426     * Resolve the text direction.
18427     *
18428     * @return true if resolution has been done, false otherwise.
18429     *
18430     * @hide
18431     */
18432    public boolean resolveTextDirection() {
18433        // Reset any previous text direction resolution
18434        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
18435
18436        if (hasRtlSupport()) {
18437            // Set resolved text direction flag depending on text direction flag
18438            final int textDirection = getRawTextDirection();
18439            switch(textDirection) {
18440                case TEXT_DIRECTION_INHERIT:
18441                    if (!canResolveTextDirection()) {
18442                        // We cannot do the resolution if there is no parent, so use the default one
18443                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18444                        // Resolution will need to happen again later
18445                        return false;
18446                    }
18447
18448                    // Parent has not yet resolved, so we still return the default
18449                    try {
18450                        if (!mParent.isTextDirectionResolved()) {
18451                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18452                            // Resolution will need to happen again later
18453                            return false;
18454                        }
18455                    } catch (AbstractMethodError e) {
18456                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18457                                " does not fully implement ViewParent", e);
18458                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED |
18459                                PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18460                        return true;
18461                    }
18462
18463                    // Set current resolved direction to the same value as the parent's one
18464                    int parentResolvedDirection;
18465                    try {
18466                        parentResolvedDirection = mParent.getTextDirection();
18467                    } catch (AbstractMethodError e) {
18468                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18469                                " does not fully implement ViewParent", e);
18470                        parentResolvedDirection = TEXT_DIRECTION_LTR;
18471                    }
18472                    switch (parentResolvedDirection) {
18473                        case TEXT_DIRECTION_FIRST_STRONG:
18474                        case TEXT_DIRECTION_ANY_RTL:
18475                        case TEXT_DIRECTION_LTR:
18476                        case TEXT_DIRECTION_RTL:
18477                        case TEXT_DIRECTION_LOCALE:
18478                            mPrivateFlags2 |=
18479                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
18480                            break;
18481                        default:
18482                            // Default resolved direction is "first strong" heuristic
18483                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18484                    }
18485                    break;
18486                case TEXT_DIRECTION_FIRST_STRONG:
18487                case TEXT_DIRECTION_ANY_RTL:
18488                case TEXT_DIRECTION_LTR:
18489                case TEXT_DIRECTION_RTL:
18490                case TEXT_DIRECTION_LOCALE:
18491                    // Resolved direction is the same as text direction
18492                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
18493                    break;
18494                default:
18495                    // Default resolved direction is "first strong" heuristic
18496                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18497            }
18498        } else {
18499            // Default resolved direction is "first strong" heuristic
18500            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18501        }
18502
18503        // Set to resolved
18504        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
18505        return true;
18506    }
18507
18508    /**
18509     * Check if text direction resolution can be done.
18510     *
18511     * @return true if text direction resolution can be done otherwise return false.
18512     */
18513    public boolean canResolveTextDirection() {
18514        switch (getRawTextDirection()) {
18515            case TEXT_DIRECTION_INHERIT:
18516                if (mParent != null) {
18517                    try {
18518                        return mParent.canResolveTextDirection();
18519                    } catch (AbstractMethodError e) {
18520                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18521                                " does not fully implement ViewParent", e);
18522                    }
18523                }
18524                return false;
18525
18526            default:
18527                return true;
18528        }
18529    }
18530
18531    /**
18532     * Reset resolved text direction. Text direction will be resolved during a call to
18533     * {@link #onMeasure(int, int)}.
18534     *
18535     * @hide
18536     */
18537    public void resetResolvedTextDirection() {
18538        // Reset any previous text direction resolution
18539        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
18540        // Set to default value
18541        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18542    }
18543
18544    /**
18545     * @return true if text direction is inherited.
18546     *
18547     * @hide
18548     */
18549    public boolean isTextDirectionInherited() {
18550        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
18551    }
18552
18553    /**
18554     * @return true if text direction is resolved.
18555     */
18556    public boolean isTextDirectionResolved() {
18557        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
18558    }
18559
18560    /**
18561     * Return the value specifying the text alignment or policy that was set with
18562     * {@link #setTextAlignment(int)}.
18563     *
18564     * @return the defined text alignment. It can be one of:
18565     *
18566     * {@link #TEXT_ALIGNMENT_INHERIT},
18567     * {@link #TEXT_ALIGNMENT_GRAVITY},
18568     * {@link #TEXT_ALIGNMENT_CENTER},
18569     * {@link #TEXT_ALIGNMENT_TEXT_START},
18570     * {@link #TEXT_ALIGNMENT_TEXT_END},
18571     * {@link #TEXT_ALIGNMENT_VIEW_START},
18572     * {@link #TEXT_ALIGNMENT_VIEW_END}
18573     *
18574     * @attr ref android.R.styleable#View_textAlignment
18575     *
18576     * @hide
18577     */
18578    @ViewDebug.ExportedProperty(category = "text", mapping = {
18579            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
18580            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
18581            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
18582            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
18583            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
18584            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
18585            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
18586    })
18587    @TextAlignment
18588    public int getRawTextAlignment() {
18589        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
18590    }
18591
18592    /**
18593     * Set the text alignment.
18594     *
18595     * @param textAlignment The text alignment to set. Should be one of
18596     *
18597     * {@link #TEXT_ALIGNMENT_INHERIT},
18598     * {@link #TEXT_ALIGNMENT_GRAVITY},
18599     * {@link #TEXT_ALIGNMENT_CENTER},
18600     * {@link #TEXT_ALIGNMENT_TEXT_START},
18601     * {@link #TEXT_ALIGNMENT_TEXT_END},
18602     * {@link #TEXT_ALIGNMENT_VIEW_START},
18603     * {@link #TEXT_ALIGNMENT_VIEW_END}
18604     *
18605     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
18606     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
18607     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
18608     *
18609     * @attr ref android.R.styleable#View_textAlignment
18610     */
18611    public void setTextAlignment(@TextAlignment int textAlignment) {
18612        if (textAlignment != getRawTextAlignment()) {
18613            // Reset the current and resolved text alignment
18614            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
18615            resetResolvedTextAlignment();
18616            // Set the new text alignment
18617            mPrivateFlags2 |=
18618                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
18619            // Do resolution
18620            resolveTextAlignment();
18621            // Notify change
18622            onRtlPropertiesChanged(getLayoutDirection());
18623            // Refresh
18624            requestLayout();
18625            invalidate(true);
18626        }
18627    }
18628
18629    /**
18630     * Return the resolved text alignment.
18631     *
18632     * @return the resolved text alignment. Returns one of:
18633     *
18634     * {@link #TEXT_ALIGNMENT_GRAVITY},
18635     * {@link #TEXT_ALIGNMENT_CENTER},
18636     * {@link #TEXT_ALIGNMENT_TEXT_START},
18637     * {@link #TEXT_ALIGNMENT_TEXT_END},
18638     * {@link #TEXT_ALIGNMENT_VIEW_START},
18639     * {@link #TEXT_ALIGNMENT_VIEW_END}
18640     *
18641     * @attr ref android.R.styleable#View_textAlignment
18642     */
18643    @ViewDebug.ExportedProperty(category = "text", mapping = {
18644            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
18645            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
18646            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
18647            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
18648            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
18649            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
18650            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
18651    })
18652    @TextAlignment
18653    public int getTextAlignment() {
18654        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
18655                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
18656    }
18657
18658    /**
18659     * Resolve the text alignment.
18660     *
18661     * @return true if resolution has been done, false otherwise.
18662     *
18663     * @hide
18664     */
18665    public boolean resolveTextAlignment() {
18666        // Reset any previous text alignment resolution
18667        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
18668
18669        if (hasRtlSupport()) {
18670            // Set resolved text alignment flag depending on text alignment flag
18671            final int textAlignment = getRawTextAlignment();
18672            switch (textAlignment) {
18673                case TEXT_ALIGNMENT_INHERIT:
18674                    // Check if we can resolve the text alignment
18675                    if (!canResolveTextAlignment()) {
18676                        // We cannot do the resolution if there is no parent so use the default
18677                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18678                        // Resolution will need to happen again later
18679                        return false;
18680                    }
18681
18682                    // Parent has not yet resolved, so we still return the default
18683                    try {
18684                        if (!mParent.isTextAlignmentResolved()) {
18685                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18686                            // Resolution will need to happen again later
18687                            return false;
18688                        }
18689                    } catch (AbstractMethodError e) {
18690                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18691                                " does not fully implement ViewParent", e);
18692                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED |
18693                                PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18694                        return true;
18695                    }
18696
18697                    int parentResolvedTextAlignment;
18698                    try {
18699                        parentResolvedTextAlignment = mParent.getTextAlignment();
18700                    } catch (AbstractMethodError e) {
18701                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18702                                " does not fully implement ViewParent", e);
18703                        parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY;
18704                    }
18705                    switch (parentResolvedTextAlignment) {
18706                        case TEXT_ALIGNMENT_GRAVITY:
18707                        case TEXT_ALIGNMENT_TEXT_START:
18708                        case TEXT_ALIGNMENT_TEXT_END:
18709                        case TEXT_ALIGNMENT_CENTER:
18710                        case TEXT_ALIGNMENT_VIEW_START:
18711                        case TEXT_ALIGNMENT_VIEW_END:
18712                            // Resolved text alignment is the same as the parent resolved
18713                            // text alignment
18714                            mPrivateFlags2 |=
18715                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
18716                            break;
18717                        default:
18718                            // Use default resolved text alignment
18719                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18720                    }
18721                    break;
18722                case TEXT_ALIGNMENT_GRAVITY:
18723                case TEXT_ALIGNMENT_TEXT_START:
18724                case TEXT_ALIGNMENT_TEXT_END:
18725                case TEXT_ALIGNMENT_CENTER:
18726                case TEXT_ALIGNMENT_VIEW_START:
18727                case TEXT_ALIGNMENT_VIEW_END:
18728                    // Resolved text alignment is the same as text alignment
18729                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
18730                    break;
18731                default:
18732                    // Use default resolved text alignment
18733                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18734            }
18735        } else {
18736            // Use default resolved text alignment
18737            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18738        }
18739
18740        // Set the resolved
18741        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
18742        return true;
18743    }
18744
18745    /**
18746     * Check if text alignment resolution can be done.
18747     *
18748     * @return true if text alignment resolution can be done otherwise return false.
18749     */
18750    public boolean canResolveTextAlignment() {
18751        switch (getRawTextAlignment()) {
18752            case TEXT_DIRECTION_INHERIT:
18753                if (mParent != null) {
18754                    try {
18755                        return mParent.canResolveTextAlignment();
18756                    } catch (AbstractMethodError e) {
18757                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18758                                " does not fully implement ViewParent", e);
18759                    }
18760                }
18761                return false;
18762
18763            default:
18764                return true;
18765        }
18766    }
18767
18768    /**
18769     * Reset resolved text alignment. Text alignment will be resolved during a call to
18770     * {@link #onMeasure(int, int)}.
18771     *
18772     * @hide
18773     */
18774    public void resetResolvedTextAlignment() {
18775        // Reset any previous text alignment resolution
18776        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
18777        // Set to default
18778        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18779    }
18780
18781    /**
18782     * @return true if text alignment is inherited.
18783     *
18784     * @hide
18785     */
18786    public boolean isTextAlignmentInherited() {
18787        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
18788    }
18789
18790    /**
18791     * @return true if text alignment is resolved.
18792     */
18793    public boolean isTextAlignmentResolved() {
18794        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
18795    }
18796
18797    /**
18798     * Generate a value suitable for use in {@link #setId(int)}.
18799     * This value will not collide with ID values generated at build time by aapt for R.id.
18800     *
18801     * @return a generated ID value
18802     */
18803    public static int generateViewId() {
18804        for (;;) {
18805            final int result = sNextGeneratedId.get();
18806            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
18807            int newValue = result + 1;
18808            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
18809            if (sNextGeneratedId.compareAndSet(result, newValue)) {
18810                return result;
18811            }
18812        }
18813    }
18814
18815    /**
18816     * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions.
18817     * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and
18818     *                           a normal View or a ViewGroup with
18819     *                           {@link android.view.ViewGroup#isTransitionGroup()} true.
18820     * @hide
18821     */
18822    public void captureTransitioningViews(List<View> transitioningViews) {
18823        if (getVisibility() == View.VISIBLE) {
18824            transitioningViews.add(this);
18825        }
18826    }
18827
18828    /**
18829     * Adds all Views that have {@link #getSharedElementName()} non-null to sharedElements.
18830     * @param sharedElements Will contain all Views in the hierarchy having a shared element name.
18831     * @hide
18832     */
18833    public void findSharedElements(Map<String, View> sharedElements) {
18834        if (getVisibility() == VISIBLE) {
18835            String sharedElementName = getSharedElementName();
18836            if (sharedElementName != null) {
18837                sharedElements.put(sharedElementName, this);
18838            }
18839        }
18840    }
18841
18842    //
18843    // Properties
18844    //
18845    /**
18846     * A Property wrapper around the <code>alpha</code> functionality handled by the
18847     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
18848     */
18849    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
18850        @Override
18851        public void setValue(View object, float value) {
18852            object.setAlpha(value);
18853        }
18854
18855        @Override
18856        public Float get(View object) {
18857            return object.getAlpha();
18858        }
18859    };
18860
18861    /**
18862     * A Property wrapper around the <code>translationX</code> functionality handled by the
18863     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
18864     */
18865    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
18866        @Override
18867        public void setValue(View object, float value) {
18868            object.setTranslationX(value);
18869        }
18870
18871                @Override
18872        public Float get(View object) {
18873            return object.getTranslationX();
18874        }
18875    };
18876
18877    /**
18878     * A Property wrapper around the <code>translationY</code> functionality handled by the
18879     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
18880     */
18881    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
18882        @Override
18883        public void setValue(View object, float value) {
18884            object.setTranslationY(value);
18885        }
18886
18887        @Override
18888        public Float get(View object) {
18889            return object.getTranslationY();
18890        }
18891    };
18892
18893    /**
18894     * A Property wrapper around the <code>translationZ</code> functionality handled by the
18895     * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods.
18896     */
18897    public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") {
18898        @Override
18899        public void setValue(View object, float value) {
18900            object.setTranslationZ(value);
18901        }
18902
18903        @Override
18904        public Float get(View object) {
18905            return object.getTranslationZ();
18906        }
18907    };
18908
18909    /**
18910     * A Property wrapper around the <code>x</code> functionality handled by the
18911     * {@link View#setX(float)} and {@link View#getX()} methods.
18912     */
18913    public static final Property<View, Float> X = new FloatProperty<View>("x") {
18914        @Override
18915        public void setValue(View object, float value) {
18916            object.setX(value);
18917        }
18918
18919        @Override
18920        public Float get(View object) {
18921            return object.getX();
18922        }
18923    };
18924
18925    /**
18926     * A Property wrapper around the <code>y</code> functionality handled by the
18927     * {@link View#setY(float)} and {@link View#getY()} methods.
18928     */
18929    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
18930        @Override
18931        public void setValue(View object, float value) {
18932            object.setY(value);
18933        }
18934
18935        @Override
18936        public Float get(View object) {
18937            return object.getY();
18938        }
18939    };
18940
18941    /**
18942     * A Property wrapper around the <code>rotation</code> functionality handled by the
18943     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
18944     */
18945    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
18946        @Override
18947        public void setValue(View object, float value) {
18948            object.setRotation(value);
18949        }
18950
18951        @Override
18952        public Float get(View object) {
18953            return object.getRotation();
18954        }
18955    };
18956
18957    /**
18958     * A Property wrapper around the <code>rotationX</code> functionality handled by the
18959     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
18960     */
18961    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
18962        @Override
18963        public void setValue(View object, float value) {
18964            object.setRotationX(value);
18965        }
18966
18967        @Override
18968        public Float get(View object) {
18969            return object.getRotationX();
18970        }
18971    };
18972
18973    /**
18974     * A Property wrapper around the <code>rotationY</code> functionality handled by the
18975     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
18976     */
18977    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
18978        @Override
18979        public void setValue(View object, float value) {
18980            object.setRotationY(value);
18981        }
18982
18983        @Override
18984        public Float get(View object) {
18985            return object.getRotationY();
18986        }
18987    };
18988
18989    /**
18990     * A Property wrapper around the <code>scaleX</code> functionality handled by the
18991     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
18992     */
18993    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
18994        @Override
18995        public void setValue(View object, float value) {
18996            object.setScaleX(value);
18997        }
18998
18999        @Override
19000        public Float get(View object) {
19001            return object.getScaleX();
19002        }
19003    };
19004
19005    /**
19006     * A Property wrapper around the <code>scaleY</code> functionality handled by the
19007     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
19008     */
19009    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
19010        @Override
19011        public void setValue(View object, float value) {
19012            object.setScaleY(value);
19013        }
19014
19015        @Override
19016        public Float get(View object) {
19017            return object.getScaleY();
19018        }
19019    };
19020
19021    /**
19022     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
19023     * Each MeasureSpec represents a requirement for either the width or the height.
19024     * A MeasureSpec is comprised of a size and a mode. There are three possible
19025     * modes:
19026     * <dl>
19027     * <dt>UNSPECIFIED</dt>
19028     * <dd>
19029     * The parent has not imposed any constraint on the child. It can be whatever size
19030     * it wants.
19031     * </dd>
19032     *
19033     * <dt>EXACTLY</dt>
19034     * <dd>
19035     * The parent has determined an exact size for the child. The child is going to be
19036     * given those bounds regardless of how big it wants to be.
19037     * </dd>
19038     *
19039     * <dt>AT_MOST</dt>
19040     * <dd>
19041     * The child can be as large as it wants up to the specified size.
19042     * </dd>
19043     * </dl>
19044     *
19045     * MeasureSpecs are implemented as ints to reduce object allocation. This class
19046     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
19047     */
19048    public static class MeasureSpec {
19049        private static final int MODE_SHIFT = 30;
19050        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
19051
19052        /**
19053         * Measure specification mode: The parent has not imposed any constraint
19054         * on the child. It can be whatever size it wants.
19055         */
19056        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
19057
19058        /**
19059         * Measure specification mode: The parent has determined an exact size
19060         * for the child. The child is going to be given those bounds regardless
19061         * of how big it wants to be.
19062         */
19063        public static final int EXACTLY     = 1 << MODE_SHIFT;
19064
19065        /**
19066         * Measure specification mode: The child can be as large as it wants up
19067         * to the specified size.
19068         */
19069        public static final int AT_MOST     = 2 << MODE_SHIFT;
19070
19071        /**
19072         * Creates a measure specification based on the supplied size and mode.
19073         *
19074         * The mode must always be one of the following:
19075         * <ul>
19076         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
19077         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
19078         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
19079         * </ul>
19080         *
19081         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
19082         * implementation was such that the order of arguments did not matter
19083         * and overflow in either value could impact the resulting MeasureSpec.
19084         * {@link android.widget.RelativeLayout} was affected by this bug.
19085         * Apps targeting API levels greater than 17 will get the fixed, more strict
19086         * behavior.</p>
19087         *
19088         * @param size the size of the measure specification
19089         * @param mode the mode of the measure specification
19090         * @return the measure specification based on size and mode
19091         */
19092        public static int makeMeasureSpec(int size, int mode) {
19093            if (sUseBrokenMakeMeasureSpec) {
19094                return size + mode;
19095            } else {
19096                return (size & ~MODE_MASK) | (mode & MODE_MASK);
19097            }
19098        }
19099
19100        /**
19101         * Extracts the mode from the supplied measure specification.
19102         *
19103         * @param measureSpec the measure specification to extract the mode from
19104         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
19105         *         {@link android.view.View.MeasureSpec#AT_MOST} or
19106         *         {@link android.view.View.MeasureSpec#EXACTLY}
19107         */
19108        public static int getMode(int measureSpec) {
19109            return (measureSpec & MODE_MASK);
19110        }
19111
19112        /**
19113         * Extracts the size from the supplied measure specification.
19114         *
19115         * @param measureSpec the measure specification to extract the size from
19116         * @return the size in pixels defined in the supplied measure specification
19117         */
19118        public static int getSize(int measureSpec) {
19119            return (measureSpec & ~MODE_MASK);
19120        }
19121
19122        static int adjust(int measureSpec, int delta) {
19123            return makeMeasureSpec(getSize(measureSpec + delta), getMode(measureSpec));
19124        }
19125
19126        /**
19127         * Returns a String representation of the specified measure
19128         * specification.
19129         *
19130         * @param measureSpec the measure specification to convert to a String
19131         * @return a String with the following format: "MeasureSpec: MODE SIZE"
19132         */
19133        public static String toString(int measureSpec) {
19134            int mode = getMode(measureSpec);
19135            int size = getSize(measureSpec);
19136
19137            StringBuilder sb = new StringBuilder("MeasureSpec: ");
19138
19139            if (mode == UNSPECIFIED)
19140                sb.append("UNSPECIFIED ");
19141            else if (mode == EXACTLY)
19142                sb.append("EXACTLY ");
19143            else if (mode == AT_MOST)
19144                sb.append("AT_MOST ");
19145            else
19146                sb.append(mode).append(" ");
19147
19148            sb.append(size);
19149            return sb.toString();
19150        }
19151    }
19152
19153    class CheckForLongPress implements Runnable {
19154
19155        private int mOriginalWindowAttachCount;
19156
19157        public void run() {
19158            if (isPressed() && (mParent != null)
19159                    && mOriginalWindowAttachCount == mWindowAttachCount) {
19160                if (performLongClick()) {
19161                    mHasPerformedLongPress = true;
19162                }
19163            }
19164        }
19165
19166        public void rememberWindowAttachCount() {
19167            mOriginalWindowAttachCount = mWindowAttachCount;
19168        }
19169    }
19170
19171    private final class CheckForTap implements Runnable {
19172        public void run() {
19173            mPrivateFlags &= ~PFLAG_PREPRESSED;
19174            setPressed(true);
19175            checkForLongClick(ViewConfiguration.getTapTimeout());
19176        }
19177    }
19178
19179    private final class PerformClick implements Runnable {
19180        public void run() {
19181            performClick();
19182        }
19183    }
19184
19185    /** @hide */
19186    public void hackTurnOffWindowResizeAnim(boolean off) {
19187        mAttachInfo.mTurnOffWindowResizeAnim = off;
19188    }
19189
19190    /**
19191     * This method returns a ViewPropertyAnimator object, which can be used to animate
19192     * specific properties on this View.
19193     *
19194     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
19195     */
19196    public ViewPropertyAnimator animate() {
19197        if (mAnimator == null) {
19198            mAnimator = new ViewPropertyAnimator(this);
19199        }
19200        return mAnimator;
19201    }
19202
19203    /**
19204     * Specifies that the shared name of the View to be shared with another Activity.
19205     * When transitioning between Activities, the name links a UI element in the starting
19206     * Activity to UI element in the called Activity. Names should be unique in the
19207     * View hierarchy.
19208     *
19209     * @param sharedElementName The cross-Activity View identifier. The called Activity will use
19210     *                 the name to match the location with a View in its layout.
19211     * @see android.app.ActivityOptions#makeSceneTransitionAnimation(android.os.Bundle)
19212     */
19213    public void setSharedElementName(String sharedElementName) {
19214        setTagInternal(com.android.internal.R.id.shared_element_name, sharedElementName);
19215    }
19216
19217    /**
19218     * Returns the shared name of the View to be shared with another Activity.
19219     * When transitioning between Activities, the name links a UI element in the starting
19220     * Activity to UI element in the called Activity. Names should be unique in the
19221     * View hierarchy.
19222     *
19223     * <p>This returns null if the View is not a shared element or the name if it is.</p>
19224     *
19225     * @return The name used for this View for cross-Activity transitions or null if
19226     * this View has not been identified as shared.
19227     */
19228    public String getSharedElementName() {
19229        return (String) getTag(com.android.internal.R.id.shared_element_name);
19230    }
19231
19232    /**
19233     * Interface definition for a callback to be invoked when a hardware key event is
19234     * dispatched to this view. The callback will be invoked before the key event is
19235     * given to the view. This is only useful for hardware keyboards; a software input
19236     * method has no obligation to trigger this listener.
19237     */
19238    public interface OnKeyListener {
19239        /**
19240         * Called when a hardware key is dispatched to a view. This allows listeners to
19241         * get a chance to respond before the target view.
19242         * <p>Key presses in software keyboards will generally NOT trigger this method,
19243         * although some may elect to do so in some situations. Do not assume a
19244         * software input method has to be key-based; even if it is, it may use key presses
19245         * in a different way than you expect, so there is no way to reliably catch soft
19246         * input key presses.
19247         *
19248         * @param v The view the key has been dispatched to.
19249         * @param keyCode The code for the physical key that was pressed
19250         * @param event The KeyEvent object containing full information about
19251         *        the event.
19252         * @return True if the listener has consumed the event, false otherwise.
19253         */
19254        boolean onKey(View v, int keyCode, KeyEvent event);
19255    }
19256
19257    /**
19258     * Interface definition for a callback to be invoked when a touch event is
19259     * dispatched to this view. The callback will be invoked before the touch
19260     * event is given to the view.
19261     */
19262    public interface OnTouchListener {
19263        /**
19264         * Called when a touch event is dispatched to a view. This allows listeners to
19265         * get a chance to respond before the target view.
19266         *
19267         * @param v The view the touch event has been dispatched to.
19268         * @param event The MotionEvent object containing full information about
19269         *        the event.
19270         * @return True if the listener has consumed the event, false otherwise.
19271         */
19272        boolean onTouch(View v, MotionEvent event);
19273    }
19274
19275    /**
19276     * Interface definition for a callback to be invoked when a hover event is
19277     * dispatched to this view. The callback will be invoked before the hover
19278     * event is given to the view.
19279     */
19280    public interface OnHoverListener {
19281        /**
19282         * Called when a hover event is dispatched to a view. This allows listeners to
19283         * get a chance to respond before the target view.
19284         *
19285         * @param v The view the hover event has been dispatched to.
19286         * @param event The MotionEvent object containing full information about
19287         *        the event.
19288         * @return True if the listener has consumed the event, false otherwise.
19289         */
19290        boolean onHover(View v, MotionEvent event);
19291    }
19292
19293    /**
19294     * Interface definition for a callback to be invoked when a generic motion event is
19295     * dispatched to this view. The callback will be invoked before the generic motion
19296     * event is given to the view.
19297     */
19298    public interface OnGenericMotionListener {
19299        /**
19300         * Called when a generic motion event is dispatched to a view. This allows listeners to
19301         * get a chance to respond before the target view.
19302         *
19303         * @param v The view the generic motion event has been dispatched to.
19304         * @param event The MotionEvent object containing full information about
19305         *        the event.
19306         * @return True if the listener has consumed the event, false otherwise.
19307         */
19308        boolean onGenericMotion(View v, MotionEvent event);
19309    }
19310
19311    /**
19312     * Interface definition for a callback to be invoked when a view has been clicked and held.
19313     */
19314    public interface OnLongClickListener {
19315        /**
19316         * Called when a view has been clicked and held.
19317         *
19318         * @param v The view that was clicked and held.
19319         *
19320         * @return true if the callback consumed the long click, false otherwise.
19321         */
19322        boolean onLongClick(View v);
19323    }
19324
19325    /**
19326     * Interface definition for a callback to be invoked when a drag is being dispatched
19327     * to this view.  The callback will be invoked before the hosting view's own
19328     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
19329     * onDrag(event) behavior, it should return 'false' from this callback.
19330     *
19331     * <div class="special reference">
19332     * <h3>Developer Guides</h3>
19333     * <p>For a guide to implementing drag and drop features, read the
19334     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
19335     * </div>
19336     */
19337    public interface OnDragListener {
19338        /**
19339         * Called when a drag event is dispatched to a view. This allows listeners
19340         * to get a chance to override base View behavior.
19341         *
19342         * @param v The View that received the drag event.
19343         * @param event The {@link android.view.DragEvent} object for the drag event.
19344         * @return {@code true} if the drag event was handled successfully, or {@code false}
19345         * if the drag event was not handled. Note that {@code false} will trigger the View
19346         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
19347         */
19348        boolean onDrag(View v, DragEvent event);
19349    }
19350
19351    /**
19352     * Interface definition for a callback to be invoked when the focus state of
19353     * a view changed.
19354     */
19355    public interface OnFocusChangeListener {
19356        /**
19357         * Called when the focus state of a view has changed.
19358         *
19359         * @param v The view whose state has changed.
19360         * @param hasFocus The new focus state of v.
19361         */
19362        void onFocusChange(View v, boolean hasFocus);
19363    }
19364
19365    /**
19366     * Interface definition for a callback to be invoked when a view is clicked.
19367     */
19368    public interface OnClickListener {
19369        /**
19370         * Called when a view has been clicked.
19371         *
19372         * @param v The view that was clicked.
19373         */
19374        void onClick(View v);
19375    }
19376
19377    /**
19378     * Interface definition for a callback to be invoked when the context menu
19379     * for this view is being built.
19380     */
19381    public interface OnCreateContextMenuListener {
19382        /**
19383         * Called when the context menu for this view is being built. It is not
19384         * safe to hold onto the menu after this method returns.
19385         *
19386         * @param menu The context menu that is being built
19387         * @param v The view for which the context menu is being built
19388         * @param menuInfo Extra information about the item for which the
19389         *            context menu should be shown. This information will vary
19390         *            depending on the class of v.
19391         */
19392        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
19393    }
19394
19395    /**
19396     * Interface definition for a callback to be invoked when the status bar changes
19397     * visibility.  This reports <strong>global</strong> changes to the system UI
19398     * state, not what the application is requesting.
19399     *
19400     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
19401     */
19402    public interface OnSystemUiVisibilityChangeListener {
19403        /**
19404         * Called when the status bar changes visibility because of a call to
19405         * {@link View#setSystemUiVisibility(int)}.
19406         *
19407         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
19408         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
19409         * This tells you the <strong>global</strong> state of these UI visibility
19410         * flags, not what your app is currently applying.
19411         */
19412        public void onSystemUiVisibilityChange(int visibility);
19413    }
19414
19415    /**
19416     * Interface definition for a callback to be invoked when this view is attached
19417     * or detached from its window.
19418     */
19419    public interface OnAttachStateChangeListener {
19420        /**
19421         * Called when the view is attached to a window.
19422         * @param v The view that was attached
19423         */
19424        public void onViewAttachedToWindow(View v);
19425        /**
19426         * Called when the view is detached from a window.
19427         * @param v The view that was detached
19428         */
19429        public void onViewDetachedFromWindow(View v);
19430    }
19431
19432    /**
19433     * Listener for applying window insets on a view in a custom way.
19434     *
19435     * <p>Apps may choose to implement this interface if they want to apply custom policy
19436     * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener
19437     * is set, its
19438     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
19439     * method will be called instead of the View's own
19440     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener
19441     * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply
19442     * the View's normal behavior as part of its own.</p>
19443     */
19444    public interface OnApplyWindowInsetsListener {
19445        /**
19446         * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set}
19447         * on a View, this listener method will be called instead of the view's own
19448         * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
19449         *
19450         * @param v The view applying window insets
19451         * @param insets The insets to apply
19452         * @return The insets supplied, minus any insets that were consumed
19453         */
19454        public WindowInsets onApplyWindowInsets(View v, WindowInsets insets);
19455    }
19456
19457    private final class UnsetPressedState implements Runnable {
19458        public void run() {
19459            setPressed(false);
19460        }
19461    }
19462
19463    /**
19464     * Base class for derived classes that want to save and restore their own
19465     * state in {@link android.view.View#onSaveInstanceState()}.
19466     */
19467    public static class BaseSavedState extends AbsSavedState {
19468        /**
19469         * Constructor used when reading from a parcel. Reads the state of the superclass.
19470         *
19471         * @param source
19472         */
19473        public BaseSavedState(Parcel source) {
19474            super(source);
19475        }
19476
19477        /**
19478         * Constructor called by derived classes when creating their SavedState objects
19479         *
19480         * @param superState The state of the superclass of this view
19481         */
19482        public BaseSavedState(Parcelable superState) {
19483            super(superState);
19484        }
19485
19486        public static final Parcelable.Creator<BaseSavedState> CREATOR =
19487                new Parcelable.Creator<BaseSavedState>() {
19488            public BaseSavedState createFromParcel(Parcel in) {
19489                return new BaseSavedState(in);
19490            }
19491
19492            public BaseSavedState[] newArray(int size) {
19493                return new BaseSavedState[size];
19494            }
19495        };
19496    }
19497
19498    /**
19499     * A set of information given to a view when it is attached to its parent
19500     * window.
19501     */
19502    static class AttachInfo {
19503        interface Callbacks {
19504            void playSoundEffect(int effectId);
19505            boolean performHapticFeedback(int effectId, boolean always);
19506        }
19507
19508        /**
19509         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
19510         * to a Handler. This class contains the target (View) to invalidate and
19511         * the coordinates of the dirty rectangle.
19512         *
19513         * For performance purposes, this class also implements a pool of up to
19514         * POOL_LIMIT objects that get reused. This reduces memory allocations
19515         * whenever possible.
19516         */
19517        static class InvalidateInfo {
19518            private static final int POOL_LIMIT = 10;
19519
19520            private static final SynchronizedPool<InvalidateInfo> sPool =
19521                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
19522
19523            View target;
19524
19525            int left;
19526            int top;
19527            int right;
19528            int bottom;
19529
19530            public static InvalidateInfo obtain() {
19531                InvalidateInfo instance = sPool.acquire();
19532                return (instance != null) ? instance : new InvalidateInfo();
19533            }
19534
19535            public void recycle() {
19536                target = null;
19537                sPool.release(this);
19538            }
19539        }
19540
19541        final IWindowSession mSession;
19542
19543        final IWindow mWindow;
19544
19545        final IBinder mWindowToken;
19546
19547        final Display mDisplay;
19548
19549        final Callbacks mRootCallbacks;
19550
19551        IWindowId mIWindowId;
19552        WindowId mWindowId;
19553
19554        /**
19555         * The top view of the hierarchy.
19556         */
19557        View mRootView;
19558
19559        IBinder mPanelParentWindowToken;
19560
19561        boolean mHardwareAccelerated;
19562        boolean mHardwareAccelerationRequested;
19563        HardwareRenderer mHardwareRenderer;
19564
19565        boolean mScreenOn;
19566
19567        /**
19568         * Scale factor used by the compatibility mode
19569         */
19570        float mApplicationScale;
19571
19572        /**
19573         * Indicates whether the application is in compatibility mode
19574         */
19575        boolean mScalingRequired;
19576
19577        /**
19578         * If set, ViewRootImpl doesn't use its lame animation for when the window resizes.
19579         */
19580        boolean mTurnOffWindowResizeAnim;
19581
19582        /**
19583         * Left position of this view's window
19584         */
19585        int mWindowLeft;
19586
19587        /**
19588         * Top position of this view's window
19589         */
19590        int mWindowTop;
19591
19592        /**
19593         * Indicates whether views need to use 32-bit drawing caches
19594         */
19595        boolean mUse32BitDrawingCache;
19596
19597        /**
19598         * For windows that are full-screen but using insets to layout inside
19599         * of the screen areas, these are the current insets to appear inside
19600         * the overscan area of the display.
19601         */
19602        final Rect mOverscanInsets = new Rect();
19603
19604        /**
19605         * For windows that are full-screen but using insets to layout inside
19606         * of the screen decorations, these are the current insets for the
19607         * content of the window.
19608         */
19609        final Rect mContentInsets = new Rect();
19610
19611        /**
19612         * For windows that are full-screen but using insets to layout inside
19613         * of the screen decorations, these are the current insets for the
19614         * actual visible parts of the window.
19615         */
19616        final Rect mVisibleInsets = new Rect();
19617
19618        /**
19619         * The internal insets given by this window.  This value is
19620         * supplied by the client (through
19621         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
19622         * be given to the window manager when changed to be used in laying
19623         * out windows behind it.
19624         */
19625        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
19626                = new ViewTreeObserver.InternalInsetsInfo();
19627
19628        /**
19629         * Set to true when mGivenInternalInsets is non-empty.
19630         */
19631        boolean mHasNonEmptyGivenInternalInsets;
19632
19633        /**
19634         * All views in the window's hierarchy that serve as scroll containers,
19635         * used to determine if the window can be resized or must be panned
19636         * to adjust for a soft input area.
19637         */
19638        final ArrayList<View> mScrollContainers = new ArrayList<View>();
19639
19640        final KeyEvent.DispatcherState mKeyDispatchState
19641                = new KeyEvent.DispatcherState();
19642
19643        /**
19644         * Indicates whether the view's window currently has the focus.
19645         */
19646        boolean mHasWindowFocus;
19647
19648        /**
19649         * The current visibility of the window.
19650         */
19651        int mWindowVisibility;
19652
19653        /**
19654         * Indicates the time at which drawing started to occur.
19655         */
19656        long mDrawingTime;
19657
19658        /**
19659         * Indicates whether or not ignoring the DIRTY_MASK flags.
19660         */
19661        boolean mIgnoreDirtyState;
19662
19663        /**
19664         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
19665         * to avoid clearing that flag prematurely.
19666         */
19667        boolean mSetIgnoreDirtyState = false;
19668
19669        /**
19670         * Indicates whether the view's window is currently in touch mode.
19671         */
19672        boolean mInTouchMode;
19673
19674        /**
19675         * Indicates that ViewAncestor should trigger a global layout change
19676         * the next time it performs a traversal
19677         */
19678        boolean mRecomputeGlobalAttributes;
19679
19680        /**
19681         * Always report new attributes at next traversal.
19682         */
19683        boolean mForceReportNewAttributes;
19684
19685        /**
19686         * Set during a traveral if any views want to keep the screen on.
19687         */
19688        boolean mKeepScreenOn;
19689
19690        /**
19691         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
19692         */
19693        int mSystemUiVisibility;
19694
19695        /**
19696         * Hack to force certain system UI visibility flags to be cleared.
19697         */
19698        int mDisabledSystemUiVisibility;
19699
19700        /**
19701         * Last global system UI visibility reported by the window manager.
19702         */
19703        int mGlobalSystemUiVisibility;
19704
19705        /**
19706         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
19707         * attached.
19708         */
19709        boolean mHasSystemUiListeners;
19710
19711        /**
19712         * Set if the window has requested to extend into the overscan region
19713         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
19714         */
19715        boolean mOverscanRequested;
19716
19717        /**
19718         * Set if the visibility of any views has changed.
19719         */
19720        boolean mViewVisibilityChanged;
19721
19722        /**
19723         * Set to true if a view has been scrolled.
19724         */
19725        boolean mViewScrollChanged;
19726
19727        /**
19728         * Global to the view hierarchy used as a temporary for dealing with
19729         * x/y points in the transparent region computations.
19730         */
19731        final int[] mTransparentLocation = new int[2];
19732
19733        /**
19734         * Global to the view hierarchy used as a temporary for dealing with
19735         * x/y points in the ViewGroup.invalidateChild implementation.
19736         */
19737        final int[] mInvalidateChildLocation = new int[2];
19738
19739
19740        /**
19741         * Global to the view hierarchy used as a temporary for dealing with
19742         * x/y location when view is transformed.
19743         */
19744        final float[] mTmpTransformLocation = new float[2];
19745
19746        /**
19747         * The view tree observer used to dispatch global events like
19748         * layout, pre-draw, touch mode change, etc.
19749         */
19750        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
19751
19752        /**
19753         * A Canvas used by the view hierarchy to perform bitmap caching.
19754         */
19755        Canvas mCanvas;
19756
19757        /**
19758         * The view root impl.
19759         */
19760        final ViewRootImpl mViewRootImpl;
19761
19762        /**
19763         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
19764         * handler can be used to pump events in the UI events queue.
19765         */
19766        final Handler mHandler;
19767
19768        /**
19769         * Temporary for use in computing invalidate rectangles while
19770         * calling up the hierarchy.
19771         */
19772        final Rect mTmpInvalRect = new Rect();
19773
19774        /**
19775         * Temporary for use in computing hit areas with transformed views
19776         */
19777        final RectF mTmpTransformRect = new RectF();
19778
19779        /**
19780         * Temporary for use in transforming invalidation rect
19781         */
19782        final Matrix mTmpMatrix = new Matrix();
19783
19784        /**
19785         * Temporary for use in transforming invalidation rect
19786         */
19787        final Transformation mTmpTransformation = new Transformation();
19788
19789        /**
19790         * Temporary list for use in collecting focusable descendents of a view.
19791         */
19792        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
19793
19794        /**
19795         * The id of the window for accessibility purposes.
19796         */
19797        int mAccessibilityWindowId = View.NO_ID;
19798
19799        /**
19800         * Flags related to accessibility processing.
19801         *
19802         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
19803         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
19804         */
19805        int mAccessibilityFetchFlags;
19806
19807        /**
19808         * The drawable for highlighting accessibility focus.
19809         */
19810        Drawable mAccessibilityFocusDrawable;
19811
19812        /**
19813         * Show where the margins, bounds and layout bounds are for each view.
19814         */
19815        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
19816
19817        /**
19818         * Point used to compute visible regions.
19819         */
19820        final Point mPoint = new Point();
19821
19822        /**
19823         * Used to track which View originated a requestLayout() call, used when
19824         * requestLayout() is called during layout.
19825         */
19826        View mViewRequestingLayout;
19827
19828        /**
19829         * Creates a new set of attachment information with the specified
19830         * events handler and thread.
19831         *
19832         * @param handler the events handler the view must use
19833         */
19834        AttachInfo(IWindowSession session, IWindow window, Display display,
19835                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
19836            mSession = session;
19837            mWindow = window;
19838            mWindowToken = window.asBinder();
19839            mDisplay = display;
19840            mViewRootImpl = viewRootImpl;
19841            mHandler = handler;
19842            mRootCallbacks = effectPlayer;
19843        }
19844    }
19845
19846    /**
19847     * <p>ScrollabilityCache holds various fields used by a View when scrolling
19848     * is supported. This avoids keeping too many unused fields in most
19849     * instances of View.</p>
19850     */
19851    private static class ScrollabilityCache implements Runnable {
19852
19853        /**
19854         * Scrollbars are not visible
19855         */
19856        public static final int OFF = 0;
19857
19858        /**
19859         * Scrollbars are visible
19860         */
19861        public static final int ON = 1;
19862
19863        /**
19864         * Scrollbars are fading away
19865         */
19866        public static final int FADING = 2;
19867
19868        public boolean fadeScrollBars;
19869
19870        public int fadingEdgeLength;
19871        public int scrollBarDefaultDelayBeforeFade;
19872        public int scrollBarFadeDuration;
19873
19874        public int scrollBarSize;
19875        public ScrollBarDrawable scrollBar;
19876        public float[] interpolatorValues;
19877        public View host;
19878
19879        public final Paint paint;
19880        public final Matrix matrix;
19881        public Shader shader;
19882
19883        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
19884
19885        private static final float[] OPAQUE = { 255 };
19886        private static final float[] TRANSPARENT = { 0.0f };
19887
19888        /**
19889         * When fading should start. This time moves into the future every time
19890         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
19891         */
19892        public long fadeStartTime;
19893
19894
19895        /**
19896         * The current state of the scrollbars: ON, OFF, or FADING
19897         */
19898        public int state = OFF;
19899
19900        private int mLastColor;
19901
19902        public ScrollabilityCache(ViewConfiguration configuration, View host) {
19903            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
19904            scrollBarSize = configuration.getScaledScrollBarSize();
19905            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
19906            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
19907
19908            paint = new Paint();
19909            matrix = new Matrix();
19910            // use use a height of 1, and then wack the matrix each time we
19911            // actually use it.
19912            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
19913            paint.setShader(shader);
19914            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
19915
19916            this.host = host;
19917        }
19918
19919        public void setFadeColor(int color) {
19920            if (color != mLastColor) {
19921                mLastColor = color;
19922
19923                if (color != 0) {
19924                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
19925                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
19926                    paint.setShader(shader);
19927                    // Restore the default transfer mode (src_over)
19928                    paint.setXfermode(null);
19929                } else {
19930                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
19931                    paint.setShader(shader);
19932                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
19933                }
19934            }
19935        }
19936
19937        public void run() {
19938            long now = AnimationUtils.currentAnimationTimeMillis();
19939            if (now >= fadeStartTime) {
19940
19941                // the animation fades the scrollbars out by changing
19942                // the opacity (alpha) from fully opaque to fully
19943                // transparent
19944                int nextFrame = (int) now;
19945                int framesCount = 0;
19946
19947                Interpolator interpolator = scrollBarInterpolator;
19948
19949                // Start opaque
19950                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
19951
19952                // End transparent
19953                nextFrame += scrollBarFadeDuration;
19954                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
19955
19956                state = FADING;
19957
19958                // Kick off the fade animation
19959                host.invalidate(true);
19960            }
19961        }
19962    }
19963
19964    /**
19965     * Resuable callback for sending
19966     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
19967     */
19968    private class SendViewScrolledAccessibilityEvent implements Runnable {
19969        public volatile boolean mIsPending;
19970
19971        public void run() {
19972            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
19973            mIsPending = false;
19974        }
19975    }
19976
19977    /**
19978     * <p>
19979     * This class represents a delegate that can be registered in a {@link View}
19980     * to enhance accessibility support via composition rather via inheritance.
19981     * It is specifically targeted to widget developers that extend basic View
19982     * classes i.e. classes in package android.view, that would like their
19983     * applications to be backwards compatible.
19984     * </p>
19985     * <div class="special reference">
19986     * <h3>Developer Guides</h3>
19987     * <p>For more information about making applications accessible, read the
19988     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
19989     * developer guide.</p>
19990     * </div>
19991     * <p>
19992     * A scenario in which a developer would like to use an accessibility delegate
19993     * is overriding a method introduced in a later API version then the minimal API
19994     * version supported by the application. For example, the method
19995     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
19996     * in API version 4 when the accessibility APIs were first introduced. If a
19997     * developer would like his application to run on API version 4 devices (assuming
19998     * all other APIs used by the application are version 4 or lower) and take advantage
19999     * of this method, instead of overriding the method which would break the application's
20000     * backwards compatibility, he can override the corresponding method in this
20001     * delegate and register the delegate in the target View if the API version of
20002     * the system is high enough i.e. the API version is same or higher to the API
20003     * version that introduced
20004     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
20005     * </p>
20006     * <p>
20007     * Here is an example implementation:
20008     * </p>
20009     * <code><pre><p>
20010     * if (Build.VERSION.SDK_INT >= 14) {
20011     *     // If the API version is equal of higher than the version in
20012     *     // which onInitializeAccessibilityNodeInfo was introduced we
20013     *     // register a delegate with a customized implementation.
20014     *     View view = findViewById(R.id.view_id);
20015     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
20016     *         public void onInitializeAccessibilityNodeInfo(View host,
20017     *                 AccessibilityNodeInfo info) {
20018     *             // Let the default implementation populate the info.
20019     *             super.onInitializeAccessibilityNodeInfo(host, info);
20020     *             // Set some other information.
20021     *             info.setEnabled(host.isEnabled());
20022     *         }
20023     *     });
20024     * }
20025     * </code></pre></p>
20026     * <p>
20027     * This delegate contains methods that correspond to the accessibility methods
20028     * in View. If a delegate has been specified the implementation in View hands
20029     * off handling to the corresponding method in this delegate. The default
20030     * implementation the delegate methods behaves exactly as the corresponding
20031     * method in View for the case of no accessibility delegate been set. Hence,
20032     * to customize the behavior of a View method, clients can override only the
20033     * corresponding delegate method without altering the behavior of the rest
20034     * accessibility related methods of the host view.
20035     * </p>
20036     */
20037    public static class AccessibilityDelegate {
20038
20039        /**
20040         * Sends an accessibility event of the given type. If accessibility is not
20041         * enabled this method has no effect.
20042         * <p>
20043         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
20044         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
20045         * been set.
20046         * </p>
20047         *
20048         * @param host The View hosting the delegate.
20049         * @param eventType The type of the event to send.
20050         *
20051         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
20052         */
20053        public void sendAccessibilityEvent(View host, int eventType) {
20054            host.sendAccessibilityEventInternal(eventType);
20055        }
20056
20057        /**
20058         * Performs the specified accessibility action on the view. For
20059         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
20060         * <p>
20061         * The default implementation behaves as
20062         * {@link View#performAccessibilityAction(int, Bundle)
20063         *  View#performAccessibilityAction(int, Bundle)} for the case of
20064         *  no accessibility delegate been set.
20065         * </p>
20066         *
20067         * @param action The action to perform.
20068         * @return Whether the action was performed.
20069         *
20070         * @see View#performAccessibilityAction(int, Bundle)
20071         *      View#performAccessibilityAction(int, Bundle)
20072         */
20073        public boolean performAccessibilityAction(View host, int action, Bundle args) {
20074            return host.performAccessibilityActionInternal(action, args);
20075        }
20076
20077        /**
20078         * Sends an accessibility event. This method behaves exactly as
20079         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
20080         * empty {@link AccessibilityEvent} and does not perform a check whether
20081         * accessibility is enabled.
20082         * <p>
20083         * The default implementation behaves as
20084         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
20085         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
20086         * the case of no accessibility delegate been set.
20087         * </p>
20088         *
20089         * @param host The View hosting the delegate.
20090         * @param event The event to send.
20091         *
20092         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
20093         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
20094         */
20095        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
20096            host.sendAccessibilityEventUncheckedInternal(event);
20097        }
20098
20099        /**
20100         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
20101         * to its children for adding their text content to the event.
20102         * <p>
20103         * The default implementation behaves as
20104         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
20105         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
20106         * the case of no accessibility delegate been set.
20107         * </p>
20108         *
20109         * @param host The View hosting the delegate.
20110         * @param event The event.
20111         * @return True if the event population was completed.
20112         *
20113         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
20114         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
20115         */
20116        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
20117            return host.dispatchPopulateAccessibilityEventInternal(event);
20118        }
20119
20120        /**
20121         * Gives a chance to the host View to populate the accessibility event with its
20122         * text content.
20123         * <p>
20124         * The default implementation behaves as
20125         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
20126         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
20127         * the case of no accessibility delegate been set.
20128         * </p>
20129         *
20130         * @param host The View hosting the delegate.
20131         * @param event The accessibility event which to populate.
20132         *
20133         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
20134         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
20135         */
20136        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
20137            host.onPopulateAccessibilityEventInternal(event);
20138        }
20139
20140        /**
20141         * Initializes an {@link AccessibilityEvent} with information about the
20142         * the host View which is the event source.
20143         * <p>
20144         * The default implementation behaves as
20145         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
20146         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
20147         * the case of no accessibility delegate been set.
20148         * </p>
20149         *
20150         * @param host The View hosting the delegate.
20151         * @param event The event to initialize.
20152         *
20153         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
20154         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
20155         */
20156        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
20157            host.onInitializeAccessibilityEventInternal(event);
20158        }
20159
20160        /**
20161         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
20162         * <p>
20163         * The default implementation behaves as
20164         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
20165         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
20166         * the case of no accessibility delegate been set.
20167         * </p>
20168         *
20169         * @param host The View hosting the delegate.
20170         * @param info The instance to initialize.
20171         *
20172         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
20173         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
20174         */
20175        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
20176            host.onInitializeAccessibilityNodeInfoInternal(info);
20177        }
20178
20179        /**
20180         * Called when a child of the host View has requested sending an
20181         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
20182         * to augment the event.
20183         * <p>
20184         * The default implementation behaves as
20185         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
20186         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
20187         * the case of no accessibility delegate been set.
20188         * </p>
20189         *
20190         * @param host The View hosting the delegate.
20191         * @param child The child which requests sending the event.
20192         * @param event The event to be sent.
20193         * @return True if the event should be sent
20194         *
20195         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
20196         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
20197         */
20198        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
20199                AccessibilityEvent event) {
20200            return host.onRequestSendAccessibilityEventInternal(child, event);
20201        }
20202
20203        /**
20204         * Gets the provider for managing a virtual view hierarchy rooted at this View
20205         * and reported to {@link android.accessibilityservice.AccessibilityService}s
20206         * that explore the window content.
20207         * <p>
20208         * The default implementation behaves as
20209         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
20210         * the case of no accessibility delegate been set.
20211         * </p>
20212         *
20213         * @return The provider.
20214         *
20215         * @see AccessibilityNodeProvider
20216         */
20217        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
20218            return null;
20219        }
20220
20221        /**
20222         * Returns an {@link AccessibilityNodeInfo} representing the host view from the
20223         * point of view of an {@link android.accessibilityservice.AccessibilityService}.
20224         * This method is responsible for obtaining an accessibility node info from a
20225         * pool of reusable instances and calling
20226         * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host
20227         * view to initialize the former.
20228         * <p>
20229         * <strong>Note:</strong> The client is responsible for recycling the obtained
20230         * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object
20231         * creation.
20232         * </p>
20233         * <p>
20234         * The default implementation behaves as
20235         * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for
20236         * the case of no accessibility delegate been set.
20237         * </p>
20238         * @return A populated {@link AccessibilityNodeInfo}.
20239         *
20240         * @see AccessibilityNodeInfo
20241         *
20242         * @hide
20243         */
20244        public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) {
20245            return host.createAccessibilityNodeInfoInternal();
20246        }
20247    }
20248
20249    private class MatchIdPredicate implements Predicate<View> {
20250        public int mId;
20251
20252        @Override
20253        public boolean apply(View view) {
20254            return (view.mID == mId);
20255        }
20256    }
20257
20258    private class MatchLabelForPredicate implements Predicate<View> {
20259        private int mLabeledId;
20260
20261        @Override
20262        public boolean apply(View view) {
20263            return (view.mLabelForId == mLabeledId);
20264        }
20265    }
20266
20267    private class SendViewStateChangedAccessibilityEvent implements Runnable {
20268        private int mChangeTypes = 0;
20269        private boolean mPosted;
20270        private boolean mPostedWithDelay;
20271        private long mLastEventTimeMillis;
20272
20273        @Override
20274        public void run() {
20275            mPosted = false;
20276            mPostedWithDelay = false;
20277            mLastEventTimeMillis = SystemClock.uptimeMillis();
20278            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
20279                final AccessibilityEvent event = AccessibilityEvent.obtain();
20280                event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
20281                event.setContentChangeTypes(mChangeTypes);
20282                sendAccessibilityEventUnchecked(event);
20283            }
20284            mChangeTypes = 0;
20285        }
20286
20287        public void runOrPost(int changeType) {
20288            mChangeTypes |= changeType;
20289
20290            // If this is a live region or the child of a live region, collect
20291            // all events from this frame and send them on the next frame.
20292            if (inLiveRegion()) {
20293                // If we're already posted with a delay, remove that.
20294                if (mPostedWithDelay) {
20295                    removeCallbacks(this);
20296                    mPostedWithDelay = false;
20297                }
20298                // Only post if we're not already posted.
20299                if (!mPosted) {
20300                    post(this);
20301                    mPosted = true;
20302                }
20303                return;
20304            }
20305
20306            if (mPosted) {
20307                return;
20308            }
20309            final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
20310            final long minEventIntevalMillis =
20311                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
20312            if (timeSinceLastMillis >= minEventIntevalMillis) {
20313                removeCallbacks(this);
20314                run();
20315            } else {
20316                postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
20317                mPosted = true;
20318                mPostedWithDelay = true;
20319            }
20320        }
20321    }
20322
20323    private boolean inLiveRegion() {
20324        if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) {
20325            return true;
20326        }
20327
20328        ViewParent parent = getParent();
20329        while (parent instanceof View) {
20330            if (((View) parent).getAccessibilityLiveRegion()
20331                    != View.ACCESSIBILITY_LIVE_REGION_NONE) {
20332                return true;
20333            }
20334            parent = parent.getParent();
20335        }
20336
20337        return false;
20338    }
20339
20340    /**
20341     * Dump all private flags in readable format, useful for documentation and
20342     * sanity checking.
20343     */
20344    private static void dumpFlags() {
20345        final HashMap<String, String> found = Maps.newHashMap();
20346        try {
20347            for (Field field : View.class.getDeclaredFields()) {
20348                final int modifiers = field.getModifiers();
20349                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
20350                    if (field.getType().equals(int.class)) {
20351                        final int value = field.getInt(null);
20352                        dumpFlag(found, field.getName(), value);
20353                    } else if (field.getType().equals(int[].class)) {
20354                        final int[] values = (int[]) field.get(null);
20355                        for (int i = 0; i < values.length; i++) {
20356                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
20357                        }
20358                    }
20359                }
20360            }
20361        } catch (IllegalAccessException e) {
20362            throw new RuntimeException(e);
20363        }
20364
20365        final ArrayList<String> keys = Lists.newArrayList();
20366        keys.addAll(found.keySet());
20367        Collections.sort(keys);
20368        for (String key : keys) {
20369            Log.d(VIEW_LOG_TAG, found.get(key));
20370        }
20371    }
20372
20373    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
20374        // Sort flags by prefix, then by bits, always keeping unique keys
20375        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
20376        final int prefix = name.indexOf('_');
20377        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
20378        final String output = bits + " " + name;
20379        found.put(key, output);
20380    }
20381}
20382