View.java revision 641bac8e21673a2d526b9c0ccf28d5fd08bd6994
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.content.ClipData;
20import android.content.Context;
21import android.content.pm.ApplicationInfo;
22import android.content.res.Configuration;
23import android.content.res.Resources;
24import android.content.res.TypedArray;
25import android.graphics.Bitmap;
26import android.graphics.Camera;
27import android.graphics.Canvas;
28import android.graphics.Insets;
29import android.graphics.Interpolator;
30import android.graphics.LinearGradient;
31import android.graphics.Matrix;
32import android.graphics.Paint;
33import android.graphics.PixelFormat;
34import android.graphics.Point;
35import android.graphics.PorterDuff;
36import android.graphics.PorterDuffXfermode;
37import android.graphics.Rect;
38import android.graphics.RectF;
39import android.graphics.Region;
40import android.graphics.Shader;
41import android.graphics.drawable.ColorDrawable;
42import android.graphics.drawable.Drawable;
43import android.hardware.display.DisplayManagerGlobal;
44import android.os.Bundle;
45import android.os.Handler;
46import android.os.IBinder;
47import android.os.Parcel;
48import android.os.Parcelable;
49import android.os.RemoteException;
50import android.os.SystemClock;
51import android.os.SystemProperties;
52import android.text.TextUtils;
53import android.util.AttributeSet;
54import android.util.FloatProperty;
55import android.util.LayoutDirection;
56import android.util.Log;
57import android.util.LongSparseLongArray;
58import android.util.Pools.SynchronizedPool;
59import android.util.Property;
60import android.util.SparseArray;
61import android.util.SuperNotCalledException;
62import android.util.TypedValue;
63import android.view.ContextMenu.ContextMenuInfo;
64import android.view.AccessibilityIterators.TextSegmentIterator;
65import android.view.AccessibilityIterators.CharacterTextSegmentIterator;
66import android.view.AccessibilityIterators.WordTextSegmentIterator;
67import android.view.AccessibilityIterators.ParagraphTextSegmentIterator;
68import android.view.accessibility.AccessibilityEvent;
69import android.view.accessibility.AccessibilityEventSource;
70import android.view.accessibility.AccessibilityManager;
71import android.view.accessibility.AccessibilityNodeInfo;
72import android.view.accessibility.AccessibilityNodeProvider;
73import android.view.animation.Animation;
74import android.view.animation.AnimationUtils;
75import android.view.animation.Transformation;
76import android.view.inputmethod.EditorInfo;
77import android.view.inputmethod.InputConnection;
78import android.view.inputmethod.InputMethodManager;
79import android.widget.ScrollBarDrawable;
80
81import static android.os.Build.VERSION_CODES.*;
82import static java.lang.Math.max;
83
84import com.android.internal.R;
85import com.android.internal.util.Predicate;
86import com.android.internal.view.menu.MenuBuilder;
87import com.google.android.collect.Lists;
88import com.google.android.collect.Maps;
89
90import java.lang.ref.WeakReference;
91import java.lang.reflect.Field;
92import java.lang.reflect.InvocationTargetException;
93import java.lang.reflect.Method;
94import java.lang.reflect.Modifier;
95import java.util.ArrayList;
96import java.util.Arrays;
97import java.util.Collections;
98import java.util.HashMap;
99import java.util.Locale;
100import java.util.concurrent.CopyOnWriteArrayList;
101import java.util.concurrent.atomic.AtomicInteger;
102
103/**
104 * <p>
105 * This class represents the basic building block for user interface components. A View
106 * occupies a rectangular area on the screen and is responsible for drawing and
107 * event handling. View is the base class for <em>widgets</em>, which are
108 * used to create interactive UI components (buttons, text fields, etc.). The
109 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
110 * are invisible containers that hold other Views (or other ViewGroups) and define
111 * their layout properties.
112 * </p>
113 *
114 * <div class="special reference">
115 * <h3>Developer Guides</h3>
116 * <p>For information about using this class to develop your application's user interface,
117 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
118 * </div>
119 *
120 * <a name="Using"></a>
121 * <h3>Using Views</h3>
122 * <p>
123 * All of the views in a window are arranged in a single tree. You can add views
124 * either from code or by specifying a tree of views in one or more XML layout
125 * files. There are many specialized subclasses of views that act as controls or
126 * are capable of displaying text, images, or other content.
127 * </p>
128 * <p>
129 * Once you have created a tree of views, there are typically a few types of
130 * common operations you may wish to perform:
131 * <ul>
132 * <li><strong>Set properties:</strong> for example setting the text of a
133 * {@link android.widget.TextView}. The available properties and the methods
134 * that set them will vary among the different subclasses of views. Note that
135 * properties that are known at build time can be set in the XML layout
136 * files.</li>
137 * <li><strong>Set focus:</strong> The framework will handled moving focus in
138 * response to user input. To force focus to a specific view, call
139 * {@link #requestFocus}.</li>
140 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
141 * that will be notified when something interesting happens to the view. For
142 * example, all views will let you set a listener to be notified when the view
143 * gains or loses focus. You can register such a listener using
144 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
145 * Other view subclasses offer more specialized listeners. For example, a Button
146 * exposes a listener to notify clients when the button is clicked.</li>
147 * <li><strong>Set visibility:</strong> You can hide or show views using
148 * {@link #setVisibility(int)}.</li>
149 * </ul>
150 * </p>
151 * <p><em>
152 * Note: The Android framework is responsible for measuring, laying out and
153 * drawing views. You should not call methods that perform these actions on
154 * views yourself unless you are actually implementing a
155 * {@link android.view.ViewGroup}.
156 * </em></p>
157 *
158 * <a name="Lifecycle"></a>
159 * <h3>Implementing a Custom View</h3>
160 *
161 * <p>
162 * To implement a custom view, you will usually begin by providing overrides for
163 * some of the standard methods that the framework calls on all views. You do
164 * not need to override all of these methods. In fact, you can start by just
165 * overriding {@link #onDraw(android.graphics.Canvas)}.
166 * <table border="2" width="85%" align="center" cellpadding="5">
167 *     <thead>
168 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
169 *     </thead>
170 *
171 *     <tbody>
172 *     <tr>
173 *         <td rowspan="2">Creation</td>
174 *         <td>Constructors</td>
175 *         <td>There is a form of the constructor that are called when the view
176 *         is created from code and a form that is called when the view is
177 *         inflated from a layout file. The second form should parse and apply
178 *         any attributes defined in the layout file.
179 *         </td>
180 *     </tr>
181 *     <tr>
182 *         <td><code>{@link #onFinishInflate()}</code></td>
183 *         <td>Called after a view and all of its children has been inflated
184 *         from XML.</td>
185 *     </tr>
186 *
187 *     <tr>
188 *         <td rowspan="3">Layout</td>
189 *         <td><code>{@link #onMeasure(int, int)}</code></td>
190 *         <td>Called to determine the size requirements for this view and all
191 *         of its children.
192 *         </td>
193 *     </tr>
194 *     <tr>
195 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
196 *         <td>Called when this view should assign a size and position to all
197 *         of its children.
198 *         </td>
199 *     </tr>
200 *     <tr>
201 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
202 *         <td>Called when the size of this view has changed.
203 *         </td>
204 *     </tr>
205 *
206 *     <tr>
207 *         <td>Drawing</td>
208 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
209 *         <td>Called when the view should render its content.
210 *         </td>
211 *     </tr>
212 *
213 *     <tr>
214 *         <td rowspan="4">Event processing</td>
215 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
216 *         <td>Called when a new hardware key event occurs.
217 *         </td>
218 *     </tr>
219 *     <tr>
220 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
221 *         <td>Called when a hardware key up event occurs.
222 *         </td>
223 *     </tr>
224 *     <tr>
225 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
226 *         <td>Called when a trackball motion event occurs.
227 *         </td>
228 *     </tr>
229 *     <tr>
230 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
231 *         <td>Called when a touch screen motion event occurs.
232 *         </td>
233 *     </tr>
234 *
235 *     <tr>
236 *         <td rowspan="2">Focus</td>
237 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
238 *         <td>Called when the view gains or loses focus.
239 *         </td>
240 *     </tr>
241 *
242 *     <tr>
243 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
244 *         <td>Called when the window containing the view gains or loses focus.
245 *         </td>
246 *     </tr>
247 *
248 *     <tr>
249 *         <td rowspan="3">Attaching</td>
250 *         <td><code>{@link #onAttachedToWindow()}</code></td>
251 *         <td>Called when the view is attached to a window.
252 *         </td>
253 *     </tr>
254 *
255 *     <tr>
256 *         <td><code>{@link #onDetachedFromWindow}</code></td>
257 *         <td>Called when the view is detached from its window.
258 *         </td>
259 *     </tr>
260 *
261 *     <tr>
262 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
263 *         <td>Called when the visibility of the window containing the view
264 *         has changed.
265 *         </td>
266 *     </tr>
267 *     </tbody>
268 *
269 * </table>
270 * </p>
271 *
272 * <a name="IDs"></a>
273 * <h3>IDs</h3>
274 * Views may have an integer id associated with them. These ids are typically
275 * assigned in the layout XML files, and are used to find specific views within
276 * the view tree. A common pattern is to:
277 * <ul>
278 * <li>Define a Button in the layout file and assign it a unique ID.
279 * <pre>
280 * &lt;Button
281 *     android:id="@+id/my_button"
282 *     android:layout_width="wrap_content"
283 *     android:layout_height="wrap_content"
284 *     android:text="@string/my_button_text"/&gt;
285 * </pre></li>
286 * <li>From the onCreate method of an Activity, find the Button
287 * <pre class="prettyprint">
288 *      Button myButton = (Button) findViewById(R.id.my_button);
289 * </pre></li>
290 * </ul>
291 * <p>
292 * View IDs need not be unique throughout the tree, but it is good practice to
293 * ensure that they are at least unique within the part of the tree you are
294 * searching.
295 * </p>
296 *
297 * <a name="Position"></a>
298 * <h3>Position</h3>
299 * <p>
300 * The geometry of a view is that of a rectangle. A view has a location,
301 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
302 * two dimensions, expressed as a width and a height. The unit for location
303 * and dimensions is the pixel.
304 * </p>
305 *
306 * <p>
307 * It is possible to retrieve the location of a view by invoking the methods
308 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
309 * coordinate of the rectangle representing the view. The latter returns the
310 * top, or Y, coordinate of the rectangle representing the view. These methods
311 * both return the location of the view relative to its parent. For instance,
312 * when getLeft() returns 20, that means the view is located 20 pixels to the
313 * right of the left edge of its direct parent.
314 * </p>
315 *
316 * <p>
317 * In addition, several convenience methods are offered to avoid unnecessary
318 * computations, namely {@link #getRight()} and {@link #getBottom()}.
319 * These methods return the coordinates of the right and bottom edges of the
320 * rectangle representing the view. For instance, calling {@link #getRight()}
321 * is similar to the following computation: <code>getLeft() + getWidth()</code>
322 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
323 * </p>
324 *
325 * <a name="SizePaddingMargins"></a>
326 * <h3>Size, padding and margins</h3>
327 * <p>
328 * The size of a view is expressed with a width and a height. A view actually
329 * possess two pairs of width and height values.
330 * </p>
331 *
332 * <p>
333 * The first pair is known as <em>measured width</em> and
334 * <em>measured height</em>. These dimensions define how big a view wants to be
335 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
336 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
337 * and {@link #getMeasuredHeight()}.
338 * </p>
339 *
340 * <p>
341 * The second pair is simply known as <em>width</em> and <em>height</em>, or
342 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
343 * dimensions define the actual size of the view on screen, at drawing time and
344 * after layout. These values may, but do not have to, be different from the
345 * measured width and height. The width and height can be obtained by calling
346 * {@link #getWidth()} and {@link #getHeight()}.
347 * </p>
348 *
349 * <p>
350 * To measure its dimensions, a view takes into account its padding. The padding
351 * is expressed in pixels for the left, top, right and bottom parts of the view.
352 * Padding can be used to offset the content of the view by a specific amount of
353 * pixels. For instance, a left padding of 2 will push the view's content by
354 * 2 pixels to the right of the left edge. Padding can be set using the
355 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)}
356 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()},
357 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()},
358 * {@link #getPaddingEnd()}.
359 * </p>
360 *
361 * <p>
362 * Even though a view can define a padding, it does not provide any support for
363 * margins. However, view groups provide such a support. Refer to
364 * {@link android.view.ViewGroup} and
365 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
366 * </p>
367 *
368 * <a name="Layout"></a>
369 * <h3>Layout</h3>
370 * <p>
371 * Layout is a two pass process: a measure pass and a layout pass. The measuring
372 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
373 * of the view tree. Each view pushes dimension specifications down the tree
374 * during the recursion. At the end of the measure pass, every view has stored
375 * its measurements. The second pass happens in
376 * {@link #layout(int,int,int,int)} and is also top-down. During
377 * this pass each parent is responsible for positioning all of its children
378 * using the sizes computed in the measure pass.
379 * </p>
380 *
381 * <p>
382 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
383 * {@link #getMeasuredHeight()} values must be set, along with those for all of
384 * that view's descendants. A view's measured width and measured height values
385 * must respect the constraints imposed by the view's parents. This guarantees
386 * that at the end of the measure pass, all parents accept all of their
387 * children's measurements. A parent view may call measure() more than once on
388 * its children. For example, the parent may measure each child once with
389 * unspecified dimensions to find out how big they want to be, then call
390 * measure() on them again with actual numbers if the sum of all the children's
391 * unconstrained sizes is too big or too small.
392 * </p>
393 *
394 * <p>
395 * The measure pass uses two classes to communicate dimensions. The
396 * {@link MeasureSpec} class is used by views to tell their parents how they
397 * want to be measured and positioned. The base LayoutParams class just
398 * describes how big the view wants to be for both width and height. For each
399 * dimension, it can specify one of:
400 * <ul>
401 * <li> an exact number
402 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
403 * (minus padding)
404 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
405 * enclose its content (plus padding).
406 * </ul>
407 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
408 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
409 * an X and Y value.
410 * </p>
411 *
412 * <p>
413 * MeasureSpecs are used to push requirements down the tree from parent to
414 * child. A MeasureSpec can be in one of three modes:
415 * <ul>
416 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
417 * of a child view. For example, a LinearLayout may call measure() on its child
418 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
419 * tall the child view wants to be given a width of 240 pixels.
420 * <li>EXACTLY: This is used by the parent to impose an exact size on the
421 * child. The child must use this size, and guarantee that all of its
422 * descendants will fit within this size.
423 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
424 * child. The child must gurantee that it and all of its descendants will fit
425 * within this size.
426 * </ul>
427 * </p>
428 *
429 * <p>
430 * To intiate a layout, call {@link #requestLayout}. This method is typically
431 * called by a view on itself when it believes that is can no longer fit within
432 * its current bounds.
433 * </p>
434 *
435 * <a name="Drawing"></a>
436 * <h3>Drawing</h3>
437 * <p>
438 * Drawing is handled by walking the tree and rendering each view that
439 * intersects the invalid region. Because the tree is traversed in-order,
440 * this means that parents will draw before (i.e., behind) their children, with
441 * siblings drawn in the order they appear in the tree.
442 * If you set a background drawable for a View, then the View will draw it for you
443 * before calling back to its <code>onDraw()</code> method.
444 * </p>
445 *
446 * <p>
447 * Note that the framework will not draw views that are not in the invalid region.
448 * </p>
449 *
450 * <p>
451 * To force a view to draw, call {@link #invalidate()}.
452 * </p>
453 *
454 * <a name="EventHandlingThreading"></a>
455 * <h3>Event Handling and Threading</h3>
456 * <p>
457 * The basic cycle of a view is as follows:
458 * <ol>
459 * <li>An event comes in and is dispatched to the appropriate view. The view
460 * handles the event and notifies any listeners.</li>
461 * <li>If in the course of processing the event, the view's bounds may need
462 * to be changed, the view will call {@link #requestLayout()}.</li>
463 * <li>Similarly, if in the course of processing the event the view's appearance
464 * may need to be changed, the view will call {@link #invalidate()}.</li>
465 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
466 * the framework will take care of measuring, laying out, and drawing the tree
467 * as appropriate.</li>
468 * </ol>
469 * </p>
470 *
471 * <p><em>Note: The entire view tree is single threaded. You must always be on
472 * the UI thread when calling any method on any view.</em>
473 * If you are doing work on other threads and want to update the state of a view
474 * from that thread, you should use a {@link Handler}.
475 * </p>
476 *
477 * <a name="FocusHandling"></a>
478 * <h3>Focus Handling</h3>
479 * <p>
480 * The framework will handle routine focus movement in response to user input.
481 * This includes changing the focus as views are removed or hidden, or as new
482 * views become available. Views indicate their willingness to take focus
483 * through the {@link #isFocusable} method. To change whether a view can take
484 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
485 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
486 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
487 * </p>
488 * <p>
489 * Focus movement is based on an algorithm which finds the nearest neighbor in a
490 * given direction. In rare cases, the default algorithm may not match the
491 * intended behavior of the developer. In these situations, you can provide
492 * explicit overrides by using these XML attributes in the layout file:
493 * <pre>
494 * nextFocusDown
495 * nextFocusLeft
496 * nextFocusRight
497 * nextFocusUp
498 * </pre>
499 * </p>
500 *
501 *
502 * <p>
503 * To get a particular view to take focus, call {@link #requestFocus()}.
504 * </p>
505 *
506 * <a name="TouchMode"></a>
507 * <h3>Touch Mode</h3>
508 * <p>
509 * When a user is navigating a user interface via directional keys such as a D-pad, it is
510 * necessary to give focus to actionable items such as buttons so the user can see
511 * what will take input.  If the device has touch capabilities, however, and the user
512 * begins interacting with the interface by touching it, it is no longer necessary to
513 * always highlight, or give focus to, a particular view.  This motivates a mode
514 * for interaction named 'touch mode'.
515 * </p>
516 * <p>
517 * For a touch capable device, once the user touches the screen, the device
518 * will enter touch mode.  From this point onward, only views for which
519 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
520 * Other views that are touchable, like buttons, will not take focus when touched; they will
521 * only fire the on click listeners.
522 * </p>
523 * <p>
524 * Any time a user hits a directional key, such as a D-pad direction, the view device will
525 * exit touch mode, and find a view to take focus, so that the user may resume interacting
526 * with the user interface without touching the screen again.
527 * </p>
528 * <p>
529 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
530 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
531 * </p>
532 *
533 * <a name="Scrolling"></a>
534 * <h3>Scrolling</h3>
535 * <p>
536 * The framework provides basic support for views that wish to internally
537 * scroll their content. This includes keeping track of the X and Y scroll
538 * offset as well as mechanisms for drawing scrollbars. See
539 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
540 * {@link #awakenScrollBars()} for more details.
541 * </p>
542 *
543 * <a name="Tags"></a>
544 * <h3>Tags</h3>
545 * <p>
546 * Unlike IDs, tags are not used to identify views. Tags are essentially an
547 * extra piece of information that can be associated with a view. They are most
548 * often used as a convenience to store data related to views in the views
549 * themselves rather than by putting them in a separate structure.
550 * </p>
551 *
552 * <a name="Properties"></a>
553 * <h3>Properties</h3>
554 * <p>
555 * The View class exposes an {@link #ALPHA} property, as well as several transform-related
556 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are
557 * available both in the {@link Property} form as well as in similarly-named setter/getter
558 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can
559 * be used to set persistent state associated with these rendering-related properties on the view.
560 * The properties and methods can also be used in conjunction with
561 * {@link android.animation.Animator Animator}-based animations, described more in the
562 * <a href="#Animation">Animation</a> section.
563 * </p>
564 *
565 * <a name="Animation"></a>
566 * <h3>Animation</h3>
567 * <p>
568 * Starting with Android 3.0, the preferred way of animating views is to use the
569 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based
570 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and
571 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0
572 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only
573 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class
574 * makes animating these View properties particularly easy and efficient.
575 * </p>
576 * <p>
577 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered.
578 * You can attach an {@link Animation} object to a view using
579 * {@link #setAnimation(Animation)} or
580 * {@link #startAnimation(Animation)}. The animation can alter the scale,
581 * rotation, translation and alpha of a view over time. If the animation is
582 * attached to a view that has children, the animation will affect the entire
583 * subtree rooted by that node. When an animation is started, the framework will
584 * take care of redrawing the appropriate views until the animation completes.
585 * </p>
586 *
587 * <a name="Security"></a>
588 * <h3>Security</h3>
589 * <p>
590 * Sometimes it is essential that an application be able to verify that an action
591 * is being performed with the full knowledge and consent of the user, such as
592 * granting a permission request, making a purchase or clicking on an advertisement.
593 * Unfortunately, a malicious application could try to spoof the user into
594 * performing these actions, unaware, by concealing the intended purpose of the view.
595 * As a remedy, the framework offers a touch filtering mechanism that can be used to
596 * improve the security of views that provide access to sensitive functionality.
597 * </p><p>
598 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
599 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
600 * will discard touches that are received whenever the view's window is obscured by
601 * another visible window.  As a result, the view will not receive touches whenever a
602 * toast, dialog or other window appears above the view's window.
603 * </p><p>
604 * For more fine-grained control over security, consider overriding the
605 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
606 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
607 * </p>
608 *
609 * @attr ref android.R.styleable#View_alpha
610 * @attr ref android.R.styleable#View_background
611 * @attr ref android.R.styleable#View_clickable
612 * @attr ref android.R.styleable#View_contentDescription
613 * @attr ref android.R.styleable#View_drawingCacheQuality
614 * @attr ref android.R.styleable#View_duplicateParentState
615 * @attr ref android.R.styleable#View_id
616 * @attr ref android.R.styleable#View_requiresFadingEdge
617 * @attr ref android.R.styleable#View_fadeScrollbars
618 * @attr ref android.R.styleable#View_fadingEdgeLength
619 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
620 * @attr ref android.R.styleable#View_fitsSystemWindows
621 * @attr ref android.R.styleable#View_isScrollContainer
622 * @attr ref android.R.styleable#View_focusable
623 * @attr ref android.R.styleable#View_focusableInTouchMode
624 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
625 * @attr ref android.R.styleable#View_keepScreenOn
626 * @attr ref android.R.styleable#View_layerType
627 * @attr ref android.R.styleable#View_layoutDirection
628 * @attr ref android.R.styleable#View_longClickable
629 * @attr ref android.R.styleable#View_minHeight
630 * @attr ref android.R.styleable#View_minWidth
631 * @attr ref android.R.styleable#View_nextFocusDown
632 * @attr ref android.R.styleable#View_nextFocusLeft
633 * @attr ref android.R.styleable#View_nextFocusRight
634 * @attr ref android.R.styleable#View_nextFocusUp
635 * @attr ref android.R.styleable#View_onClick
636 * @attr ref android.R.styleable#View_padding
637 * @attr ref android.R.styleable#View_paddingBottom
638 * @attr ref android.R.styleable#View_paddingLeft
639 * @attr ref android.R.styleable#View_paddingRight
640 * @attr ref android.R.styleable#View_paddingTop
641 * @attr ref android.R.styleable#View_paddingStart
642 * @attr ref android.R.styleable#View_paddingEnd
643 * @attr ref android.R.styleable#View_saveEnabled
644 * @attr ref android.R.styleable#View_rotation
645 * @attr ref android.R.styleable#View_rotationX
646 * @attr ref android.R.styleable#View_rotationY
647 * @attr ref android.R.styleable#View_scaleX
648 * @attr ref android.R.styleable#View_scaleY
649 * @attr ref android.R.styleable#View_scrollX
650 * @attr ref android.R.styleable#View_scrollY
651 * @attr ref android.R.styleable#View_scrollbarSize
652 * @attr ref android.R.styleable#View_scrollbarStyle
653 * @attr ref android.R.styleable#View_scrollbars
654 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
655 * @attr ref android.R.styleable#View_scrollbarFadeDuration
656 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
657 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
658 * @attr ref android.R.styleable#View_scrollbarThumbVertical
659 * @attr ref android.R.styleable#View_scrollbarTrackVertical
660 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
661 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
662 * @attr ref android.R.styleable#View_soundEffectsEnabled
663 * @attr ref android.R.styleable#View_tag
664 * @attr ref android.R.styleable#View_textAlignment
665 * @attr ref android.R.styleable#View_textDirection
666 * @attr ref android.R.styleable#View_transformPivotX
667 * @attr ref android.R.styleable#View_transformPivotY
668 * @attr ref android.R.styleable#View_translationX
669 * @attr ref android.R.styleable#View_translationY
670 * @attr ref android.R.styleable#View_visibility
671 *
672 * @see android.view.ViewGroup
673 */
674public class View implements Drawable.Callback, KeyEvent.Callback,
675        AccessibilityEventSource {
676    private static final boolean DBG = false;
677
678    /**
679     * The logging tag used by this class with android.util.Log.
680     */
681    protected static final String VIEW_LOG_TAG = "View";
682
683    /**
684     * When set to true, apps will draw debugging information about their layouts.
685     *
686     * @hide
687     */
688    public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout";
689
690    /**
691     * Used to mark a View that has no ID.
692     */
693    public static final int NO_ID = -1;
694
695    /**
696     * Signals that compatibility booleans have been initialized according to
697     * target SDK versions.
698     */
699    private static boolean sCompatibilityDone = false;
700
701    /**
702     * Use the old (broken) way of building MeasureSpecs.
703     */
704    private static boolean sUseBrokenMakeMeasureSpec = false;
705
706    /**
707     * Ignore any optimizations using the measure cache.
708     */
709    private static boolean sIgnoreMeasureCache = false;
710
711    /**
712     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
713     * calling setFlags.
714     */
715    private static final int NOT_FOCUSABLE = 0x00000000;
716
717    /**
718     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
719     * setFlags.
720     */
721    private static final int FOCUSABLE = 0x00000001;
722
723    /**
724     * Mask for use with setFlags indicating bits used for focus.
725     */
726    private static final int FOCUSABLE_MASK = 0x00000001;
727
728    /**
729     * This view will adjust its padding to fit sytem windows (e.g. status bar)
730     */
731    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
732
733    /**
734     * This view is visible.
735     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
736     * android:visibility}.
737     */
738    public static final int VISIBLE = 0x00000000;
739
740    /**
741     * This view is invisible, but it still takes up space for layout purposes.
742     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
743     * android:visibility}.
744     */
745    public static final int INVISIBLE = 0x00000004;
746
747    /**
748     * This view is invisible, and it doesn't take any space for layout
749     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
750     * android:visibility}.
751     */
752    public static final int GONE = 0x00000008;
753
754    /**
755     * Mask for use with setFlags indicating bits used for visibility.
756     * {@hide}
757     */
758    static final int VISIBILITY_MASK = 0x0000000C;
759
760    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
761
762    /**
763     * This view is enabled. Interpretation varies by subclass.
764     * Use with ENABLED_MASK when calling setFlags.
765     * {@hide}
766     */
767    static final int ENABLED = 0x00000000;
768
769    /**
770     * This view is disabled. Interpretation varies by subclass.
771     * Use with ENABLED_MASK when calling setFlags.
772     * {@hide}
773     */
774    static final int DISABLED = 0x00000020;
775
776   /**
777    * Mask for use with setFlags indicating bits used for indicating whether
778    * this view is enabled
779    * {@hide}
780    */
781    static final int ENABLED_MASK = 0x00000020;
782
783    /**
784     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
785     * called and further optimizations will be performed. It is okay to have
786     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
787     * {@hide}
788     */
789    static final int WILL_NOT_DRAW = 0x00000080;
790
791    /**
792     * Mask for use with setFlags indicating bits used for indicating whether
793     * this view is will draw
794     * {@hide}
795     */
796    static final int DRAW_MASK = 0x00000080;
797
798    /**
799     * <p>This view doesn't show scrollbars.</p>
800     * {@hide}
801     */
802    static final int SCROLLBARS_NONE = 0x00000000;
803
804    /**
805     * <p>This view shows horizontal scrollbars.</p>
806     * {@hide}
807     */
808    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
809
810    /**
811     * <p>This view shows vertical scrollbars.</p>
812     * {@hide}
813     */
814    static final int SCROLLBARS_VERTICAL = 0x00000200;
815
816    /**
817     * <p>Mask for use with setFlags indicating bits used for indicating which
818     * scrollbars are enabled.</p>
819     * {@hide}
820     */
821    static final int SCROLLBARS_MASK = 0x00000300;
822
823    /**
824     * Indicates that the view should filter touches when its window is obscured.
825     * Refer to the class comments for more information about this security feature.
826     * {@hide}
827     */
828    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
829
830    /**
831     * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
832     * that they are optional and should be skipped if the window has
833     * requested system UI flags that ignore those insets for layout.
834     */
835    static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
836
837    /**
838     * <p>This view doesn't show fading edges.</p>
839     * {@hide}
840     */
841    static final int FADING_EDGE_NONE = 0x00000000;
842
843    /**
844     * <p>This view shows horizontal fading edges.</p>
845     * {@hide}
846     */
847    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
848
849    /**
850     * <p>This view shows vertical fading edges.</p>
851     * {@hide}
852     */
853    static final int FADING_EDGE_VERTICAL = 0x00002000;
854
855    /**
856     * <p>Mask for use with setFlags indicating bits used for indicating which
857     * fading edges are enabled.</p>
858     * {@hide}
859     */
860    static final int FADING_EDGE_MASK = 0x00003000;
861
862    /**
863     * <p>Indicates this view can be clicked. When clickable, a View reacts
864     * to clicks by notifying the OnClickListener.<p>
865     * {@hide}
866     */
867    static final int CLICKABLE = 0x00004000;
868
869    /**
870     * <p>Indicates this view is caching its drawing into a bitmap.</p>
871     * {@hide}
872     */
873    static final int DRAWING_CACHE_ENABLED = 0x00008000;
874
875    /**
876     * <p>Indicates that no icicle should be saved for this view.<p>
877     * {@hide}
878     */
879    static final int SAVE_DISABLED = 0x000010000;
880
881    /**
882     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
883     * property.</p>
884     * {@hide}
885     */
886    static final int SAVE_DISABLED_MASK = 0x000010000;
887
888    /**
889     * <p>Indicates that no drawing cache should ever be created for this view.<p>
890     * {@hide}
891     */
892    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
893
894    /**
895     * <p>Indicates this view can take / keep focus when int touch mode.</p>
896     * {@hide}
897     */
898    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
899
900    /**
901     * <p>Enables low quality mode for the drawing cache.</p>
902     */
903    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
904
905    /**
906     * <p>Enables high quality mode for the drawing cache.</p>
907     */
908    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
909
910    /**
911     * <p>Enables automatic quality mode for the drawing cache.</p>
912     */
913    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
914
915    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
916            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
917    };
918
919    /**
920     * <p>Mask for use with setFlags indicating bits used for the cache
921     * quality property.</p>
922     * {@hide}
923     */
924    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
925
926    /**
927     * <p>
928     * Indicates this view can be long clicked. When long clickable, a View
929     * reacts to long clicks by notifying the OnLongClickListener or showing a
930     * context menu.
931     * </p>
932     * {@hide}
933     */
934    static final int LONG_CLICKABLE = 0x00200000;
935
936    /**
937     * <p>Indicates that this view gets its drawable states from its direct parent
938     * and ignores its original internal states.</p>
939     *
940     * @hide
941     */
942    static final int DUPLICATE_PARENT_STATE = 0x00400000;
943
944    /**
945     * The scrollbar style to display the scrollbars inside the content area,
946     * without increasing the padding. The scrollbars will be overlaid with
947     * translucency on the view's content.
948     */
949    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
950
951    /**
952     * The scrollbar style to display the scrollbars inside the padded area,
953     * increasing the padding of the view. The scrollbars will not overlap the
954     * content area of the view.
955     */
956    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
957
958    /**
959     * The scrollbar style to display the scrollbars at the edge of the view,
960     * without increasing the padding. The scrollbars will be overlaid with
961     * translucency.
962     */
963    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
964
965    /**
966     * The scrollbar style to display the scrollbars at the edge of the view,
967     * increasing the padding of the view. The scrollbars will only overlap the
968     * background, if any.
969     */
970    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
971
972    /**
973     * Mask to check if the scrollbar style is overlay or inset.
974     * {@hide}
975     */
976    static final int SCROLLBARS_INSET_MASK = 0x01000000;
977
978    /**
979     * Mask to check if the scrollbar style is inside or outside.
980     * {@hide}
981     */
982    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
983
984    /**
985     * Mask for scrollbar style.
986     * {@hide}
987     */
988    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
989
990    /**
991     * View flag indicating that the screen should remain on while the
992     * window containing this view is visible to the user.  This effectively
993     * takes care of automatically setting the WindowManager's
994     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
995     */
996    public static final int KEEP_SCREEN_ON = 0x04000000;
997
998    /**
999     * View flag indicating whether this view should have sound effects enabled
1000     * for events such as clicking and touching.
1001     */
1002    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
1003
1004    /**
1005     * View flag indicating whether this view should have haptic feedback
1006     * enabled for events such as long presses.
1007     */
1008    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
1009
1010    /**
1011     * <p>Indicates that the view hierarchy should stop saving state when
1012     * it reaches this view.  If state saving is initiated immediately at
1013     * the view, it will be allowed.
1014     * {@hide}
1015     */
1016    static final int PARENT_SAVE_DISABLED = 0x20000000;
1017
1018    /**
1019     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
1020     * {@hide}
1021     */
1022    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
1023
1024    /**
1025     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1026     * should add all focusable Views regardless if they are focusable in touch mode.
1027     */
1028    public static final int FOCUSABLES_ALL = 0x00000000;
1029
1030    /**
1031     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1032     * should add only Views focusable in touch mode.
1033     */
1034    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1035
1036    /**
1037     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1038     * item.
1039     */
1040    public static final int FOCUS_BACKWARD = 0x00000001;
1041
1042    /**
1043     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1044     * item.
1045     */
1046    public static final int FOCUS_FORWARD = 0x00000002;
1047
1048    /**
1049     * Use with {@link #focusSearch(int)}. Move focus to the left.
1050     */
1051    public static final int FOCUS_LEFT = 0x00000011;
1052
1053    /**
1054     * Use with {@link #focusSearch(int)}. Move focus up.
1055     */
1056    public static final int FOCUS_UP = 0x00000021;
1057
1058    /**
1059     * Use with {@link #focusSearch(int)}. Move focus to the right.
1060     */
1061    public static final int FOCUS_RIGHT = 0x00000042;
1062
1063    /**
1064     * Use with {@link #focusSearch(int)}. Move focus down.
1065     */
1066    public static final int FOCUS_DOWN = 0x00000082;
1067
1068    /**
1069     * Bits of {@link #getMeasuredWidthAndState()} and
1070     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1071     */
1072    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1073
1074    /**
1075     * Bits of {@link #getMeasuredWidthAndState()} and
1076     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1077     */
1078    public static final int MEASURED_STATE_MASK = 0xff000000;
1079
1080    /**
1081     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1082     * for functions that combine both width and height into a single int,
1083     * such as {@link #getMeasuredState()} and the childState argument of
1084     * {@link #resolveSizeAndState(int, int, int)}.
1085     */
1086    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1087
1088    /**
1089     * Bit of {@link #getMeasuredWidthAndState()} and
1090     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1091     * is smaller that the space the view would like to have.
1092     */
1093    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1094
1095    /**
1096     * Base View state sets
1097     */
1098    // Singles
1099    /**
1100     * Indicates the view has no states set. States are used with
1101     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1102     * view depending on its state.
1103     *
1104     * @see android.graphics.drawable.Drawable
1105     * @see #getDrawableState()
1106     */
1107    protected static final int[] EMPTY_STATE_SET;
1108    /**
1109     * Indicates the view is enabled. States are used with
1110     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1111     * view depending on its state.
1112     *
1113     * @see android.graphics.drawable.Drawable
1114     * @see #getDrawableState()
1115     */
1116    protected static final int[] ENABLED_STATE_SET;
1117    /**
1118     * Indicates the view is focused. States are used with
1119     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1120     * view depending on its state.
1121     *
1122     * @see android.graphics.drawable.Drawable
1123     * @see #getDrawableState()
1124     */
1125    protected static final int[] FOCUSED_STATE_SET;
1126    /**
1127     * Indicates the view is selected. States are used with
1128     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1129     * view depending on its state.
1130     *
1131     * @see android.graphics.drawable.Drawable
1132     * @see #getDrawableState()
1133     */
1134    protected static final int[] SELECTED_STATE_SET;
1135    /**
1136     * Indicates the view is pressed. States are used with
1137     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1138     * view depending on its state.
1139     *
1140     * @see android.graphics.drawable.Drawable
1141     * @see #getDrawableState()
1142     */
1143    protected static final int[] PRESSED_STATE_SET;
1144    /**
1145     * Indicates the view's window has focus. States are used with
1146     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1147     * view depending on its state.
1148     *
1149     * @see android.graphics.drawable.Drawable
1150     * @see #getDrawableState()
1151     */
1152    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1153    // Doubles
1154    /**
1155     * Indicates the view is enabled and has the focus.
1156     *
1157     * @see #ENABLED_STATE_SET
1158     * @see #FOCUSED_STATE_SET
1159     */
1160    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1161    /**
1162     * Indicates the view is enabled and selected.
1163     *
1164     * @see #ENABLED_STATE_SET
1165     * @see #SELECTED_STATE_SET
1166     */
1167    protected static final int[] ENABLED_SELECTED_STATE_SET;
1168    /**
1169     * Indicates the view is enabled and that its window has focus.
1170     *
1171     * @see #ENABLED_STATE_SET
1172     * @see #WINDOW_FOCUSED_STATE_SET
1173     */
1174    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1175    /**
1176     * Indicates the view is focused and selected.
1177     *
1178     * @see #FOCUSED_STATE_SET
1179     * @see #SELECTED_STATE_SET
1180     */
1181    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1182    /**
1183     * Indicates the view has the focus and that its window has the focus.
1184     *
1185     * @see #FOCUSED_STATE_SET
1186     * @see #WINDOW_FOCUSED_STATE_SET
1187     */
1188    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1189    /**
1190     * Indicates the view is selected and that its window has the focus.
1191     *
1192     * @see #SELECTED_STATE_SET
1193     * @see #WINDOW_FOCUSED_STATE_SET
1194     */
1195    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1196    // Triples
1197    /**
1198     * Indicates the view is enabled, focused and selected.
1199     *
1200     * @see #ENABLED_STATE_SET
1201     * @see #FOCUSED_STATE_SET
1202     * @see #SELECTED_STATE_SET
1203     */
1204    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1205    /**
1206     * Indicates the view is enabled, focused and its window has the focus.
1207     *
1208     * @see #ENABLED_STATE_SET
1209     * @see #FOCUSED_STATE_SET
1210     * @see #WINDOW_FOCUSED_STATE_SET
1211     */
1212    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1213    /**
1214     * Indicates the view is enabled, selected and its window has the focus.
1215     *
1216     * @see #ENABLED_STATE_SET
1217     * @see #SELECTED_STATE_SET
1218     * @see #WINDOW_FOCUSED_STATE_SET
1219     */
1220    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1221    /**
1222     * Indicates the view is focused, selected and its window has the focus.
1223     *
1224     * @see #FOCUSED_STATE_SET
1225     * @see #SELECTED_STATE_SET
1226     * @see #WINDOW_FOCUSED_STATE_SET
1227     */
1228    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1229    /**
1230     * Indicates the view is enabled, focused, selected and its window
1231     * has the focus.
1232     *
1233     * @see #ENABLED_STATE_SET
1234     * @see #FOCUSED_STATE_SET
1235     * @see #SELECTED_STATE_SET
1236     * @see #WINDOW_FOCUSED_STATE_SET
1237     */
1238    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1239    /**
1240     * Indicates the view is pressed and its window has the focus.
1241     *
1242     * @see #PRESSED_STATE_SET
1243     * @see #WINDOW_FOCUSED_STATE_SET
1244     */
1245    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1246    /**
1247     * Indicates the view is pressed and selected.
1248     *
1249     * @see #PRESSED_STATE_SET
1250     * @see #SELECTED_STATE_SET
1251     */
1252    protected static final int[] PRESSED_SELECTED_STATE_SET;
1253    /**
1254     * Indicates the view is pressed, selected and its window has the focus.
1255     *
1256     * @see #PRESSED_STATE_SET
1257     * @see #SELECTED_STATE_SET
1258     * @see #WINDOW_FOCUSED_STATE_SET
1259     */
1260    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1261    /**
1262     * Indicates the view is pressed and focused.
1263     *
1264     * @see #PRESSED_STATE_SET
1265     * @see #FOCUSED_STATE_SET
1266     */
1267    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1268    /**
1269     * Indicates the view is pressed, focused and its window has the focus.
1270     *
1271     * @see #PRESSED_STATE_SET
1272     * @see #FOCUSED_STATE_SET
1273     * @see #WINDOW_FOCUSED_STATE_SET
1274     */
1275    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1276    /**
1277     * Indicates the view is pressed, focused and selected.
1278     *
1279     * @see #PRESSED_STATE_SET
1280     * @see #SELECTED_STATE_SET
1281     * @see #FOCUSED_STATE_SET
1282     */
1283    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1284    /**
1285     * Indicates the view is pressed, focused, selected and its window has the focus.
1286     *
1287     * @see #PRESSED_STATE_SET
1288     * @see #FOCUSED_STATE_SET
1289     * @see #SELECTED_STATE_SET
1290     * @see #WINDOW_FOCUSED_STATE_SET
1291     */
1292    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1293    /**
1294     * Indicates the view is pressed and enabled.
1295     *
1296     * @see #PRESSED_STATE_SET
1297     * @see #ENABLED_STATE_SET
1298     */
1299    protected static final int[] PRESSED_ENABLED_STATE_SET;
1300    /**
1301     * Indicates the view is pressed, enabled and its window has the focus.
1302     *
1303     * @see #PRESSED_STATE_SET
1304     * @see #ENABLED_STATE_SET
1305     * @see #WINDOW_FOCUSED_STATE_SET
1306     */
1307    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1308    /**
1309     * Indicates the view is pressed, enabled and selected.
1310     *
1311     * @see #PRESSED_STATE_SET
1312     * @see #ENABLED_STATE_SET
1313     * @see #SELECTED_STATE_SET
1314     */
1315    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1316    /**
1317     * Indicates the view is pressed, enabled, selected and its window has the
1318     * focus.
1319     *
1320     * @see #PRESSED_STATE_SET
1321     * @see #ENABLED_STATE_SET
1322     * @see #SELECTED_STATE_SET
1323     * @see #WINDOW_FOCUSED_STATE_SET
1324     */
1325    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1326    /**
1327     * Indicates the view is pressed, enabled and focused.
1328     *
1329     * @see #PRESSED_STATE_SET
1330     * @see #ENABLED_STATE_SET
1331     * @see #FOCUSED_STATE_SET
1332     */
1333    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1334    /**
1335     * Indicates the view is pressed, enabled, focused and its window has the
1336     * focus.
1337     *
1338     * @see #PRESSED_STATE_SET
1339     * @see #ENABLED_STATE_SET
1340     * @see #FOCUSED_STATE_SET
1341     * @see #WINDOW_FOCUSED_STATE_SET
1342     */
1343    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1344    /**
1345     * Indicates the view is pressed, enabled, focused and selected.
1346     *
1347     * @see #PRESSED_STATE_SET
1348     * @see #ENABLED_STATE_SET
1349     * @see #SELECTED_STATE_SET
1350     * @see #FOCUSED_STATE_SET
1351     */
1352    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1353    /**
1354     * Indicates the view is pressed, enabled, focused, selected and its window
1355     * has the focus.
1356     *
1357     * @see #PRESSED_STATE_SET
1358     * @see #ENABLED_STATE_SET
1359     * @see #SELECTED_STATE_SET
1360     * @see #FOCUSED_STATE_SET
1361     * @see #WINDOW_FOCUSED_STATE_SET
1362     */
1363    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1364
1365    /**
1366     * The order here is very important to {@link #getDrawableState()}
1367     */
1368    private static final int[][] VIEW_STATE_SETS;
1369
1370    static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1371    static final int VIEW_STATE_SELECTED = 1 << 1;
1372    static final int VIEW_STATE_FOCUSED = 1 << 2;
1373    static final int VIEW_STATE_ENABLED = 1 << 3;
1374    static final int VIEW_STATE_PRESSED = 1 << 4;
1375    static final int VIEW_STATE_ACTIVATED = 1 << 5;
1376    static final int VIEW_STATE_ACCELERATED = 1 << 6;
1377    static final int VIEW_STATE_HOVERED = 1 << 7;
1378    static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8;
1379    static final int VIEW_STATE_DRAG_HOVERED = 1 << 9;
1380
1381    static final int[] VIEW_STATE_IDS = new int[] {
1382        R.attr.state_window_focused,    VIEW_STATE_WINDOW_FOCUSED,
1383        R.attr.state_selected,          VIEW_STATE_SELECTED,
1384        R.attr.state_focused,           VIEW_STATE_FOCUSED,
1385        R.attr.state_enabled,           VIEW_STATE_ENABLED,
1386        R.attr.state_pressed,           VIEW_STATE_PRESSED,
1387        R.attr.state_activated,         VIEW_STATE_ACTIVATED,
1388        R.attr.state_accelerated,       VIEW_STATE_ACCELERATED,
1389        R.attr.state_hovered,           VIEW_STATE_HOVERED,
1390        R.attr.state_drag_can_accept,   VIEW_STATE_DRAG_CAN_ACCEPT,
1391        R.attr.state_drag_hovered,      VIEW_STATE_DRAG_HOVERED
1392    };
1393
1394    static {
1395        if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1396            throw new IllegalStateException(
1397                    "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1398        }
1399        int[] orderedIds = new int[VIEW_STATE_IDS.length];
1400        for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
1401            int viewState = R.styleable.ViewDrawableStates[i];
1402            for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
1403                if (VIEW_STATE_IDS[j] == viewState) {
1404                    orderedIds[i * 2] = viewState;
1405                    orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
1406                }
1407            }
1408        }
1409        final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1410        VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1411        for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
1412            int numBits = Integer.bitCount(i);
1413            int[] set = new int[numBits];
1414            int pos = 0;
1415            for (int j = 0; j < orderedIds.length; j += 2) {
1416                if ((i & orderedIds[j+1]) != 0) {
1417                    set[pos++] = orderedIds[j];
1418                }
1419            }
1420            VIEW_STATE_SETS[i] = set;
1421        }
1422
1423        EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1424        WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1425        SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1426        SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1427                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1428        FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1429        FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1430                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1431        FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1432                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1433        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1434                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1435                | VIEW_STATE_FOCUSED];
1436        ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1437        ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1438                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1439        ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1440                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1441        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1442                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1443                | VIEW_STATE_ENABLED];
1444        ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1445                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1446        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1447                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1448                | VIEW_STATE_ENABLED];
1449        ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1450                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1451                | VIEW_STATE_ENABLED];
1452        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1453                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1454                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1455
1456        PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1457        PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1458                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1459        PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1460                VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1461        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1462                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1463                | VIEW_STATE_PRESSED];
1464        PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1465                VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1466        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1467                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1468                | VIEW_STATE_PRESSED];
1469        PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1470                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1471                | VIEW_STATE_PRESSED];
1472        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1473                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1474                | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1475        PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1476                VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1477        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1478                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1479                | VIEW_STATE_PRESSED];
1480        PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1481                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1482                | VIEW_STATE_PRESSED];
1483        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1484                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1485                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1486        PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1487                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1488                | VIEW_STATE_PRESSED];
1489        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1490                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1491                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1492        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1493                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1494                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1495        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1496                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1497                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1498                | VIEW_STATE_PRESSED];
1499    }
1500
1501    /**
1502     * Accessibility event types that are dispatched for text population.
1503     */
1504    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1505            AccessibilityEvent.TYPE_VIEW_CLICKED
1506            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1507            | AccessibilityEvent.TYPE_VIEW_SELECTED
1508            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1509            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1510            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1511            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1512            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1513            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
1514            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
1515            | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY;
1516
1517    /**
1518     * Temporary Rect currently for use in setBackground().  This will probably
1519     * be extended in the future to hold our own class with more than just
1520     * a Rect. :)
1521     */
1522    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1523
1524    /**
1525     * Map used to store views' tags.
1526     */
1527    private SparseArray<Object> mKeyedTags;
1528
1529    /**
1530     * The next available accessibility id.
1531     */
1532    private static int sNextAccessibilityViewId;
1533
1534    /**
1535     * The animation currently associated with this view.
1536     * @hide
1537     */
1538    protected Animation mCurrentAnimation = null;
1539
1540    /**
1541     * Width as measured during measure pass.
1542     * {@hide}
1543     */
1544    @ViewDebug.ExportedProperty(category = "measurement")
1545    int mMeasuredWidth;
1546
1547    /**
1548     * Height as measured during measure pass.
1549     * {@hide}
1550     */
1551    @ViewDebug.ExportedProperty(category = "measurement")
1552    int mMeasuredHeight;
1553
1554    /**
1555     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1556     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1557     * its display list. This flag, used only when hw accelerated, allows us to clear the
1558     * flag while retaining this information until it's needed (at getDisplayList() time and
1559     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1560     *
1561     * {@hide}
1562     */
1563    boolean mRecreateDisplayList = false;
1564
1565    /**
1566     * The view's identifier.
1567     * {@hide}
1568     *
1569     * @see #setId(int)
1570     * @see #getId()
1571     */
1572    @ViewDebug.ExportedProperty(resolveId = true)
1573    int mID = NO_ID;
1574
1575    /**
1576     * The stable ID of this view for accessibility purposes.
1577     */
1578    int mAccessibilityViewId = NO_ID;
1579
1580    private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
1581
1582    SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent;
1583
1584    /**
1585     * The view's tag.
1586     * {@hide}
1587     *
1588     * @see #setTag(Object)
1589     * @see #getTag()
1590     */
1591    protected Object mTag;
1592
1593    // for mPrivateFlags:
1594    /** {@hide} */
1595    static final int PFLAG_WANTS_FOCUS                 = 0x00000001;
1596    /** {@hide} */
1597    static final int PFLAG_FOCUSED                     = 0x00000002;
1598    /** {@hide} */
1599    static final int PFLAG_SELECTED                    = 0x00000004;
1600    /** {@hide} */
1601    static final int PFLAG_IS_ROOT_NAMESPACE           = 0x00000008;
1602    /** {@hide} */
1603    static final int PFLAG_HAS_BOUNDS                  = 0x00000010;
1604    /** {@hide} */
1605    static final int PFLAG_DRAWN                       = 0x00000020;
1606    /**
1607     * When this flag is set, this view is running an animation on behalf of its
1608     * children and should therefore not cancel invalidate requests, even if they
1609     * lie outside of this view's bounds.
1610     *
1611     * {@hide}
1612     */
1613    static final int PFLAG_DRAW_ANIMATION              = 0x00000040;
1614    /** {@hide} */
1615    static final int PFLAG_SKIP_DRAW                   = 0x00000080;
1616    /** {@hide} */
1617    static final int PFLAG_ONLY_DRAWS_BACKGROUND       = 0x00000100;
1618    /** {@hide} */
1619    static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1620    /** {@hide} */
1621    static final int PFLAG_DRAWABLE_STATE_DIRTY        = 0x00000400;
1622    /** {@hide} */
1623    static final int PFLAG_MEASURED_DIMENSION_SET      = 0x00000800;
1624    /** {@hide} */
1625    static final int PFLAG_FORCE_LAYOUT                = 0x00001000;
1626    /** {@hide} */
1627    static final int PFLAG_LAYOUT_REQUIRED             = 0x00002000;
1628
1629    private static final int PFLAG_PRESSED             = 0x00004000;
1630
1631    /** {@hide} */
1632    static final int PFLAG_DRAWING_CACHE_VALID         = 0x00008000;
1633    /**
1634     * Flag used to indicate that this view should be drawn once more (and only once
1635     * more) after its animation has completed.
1636     * {@hide}
1637     */
1638    static final int PFLAG_ANIMATION_STARTED           = 0x00010000;
1639
1640    private static final int PFLAG_SAVE_STATE_CALLED   = 0x00020000;
1641
1642    /**
1643     * Indicates that the View returned true when onSetAlpha() was called and that
1644     * the alpha must be restored.
1645     * {@hide}
1646     */
1647    static final int PFLAG_ALPHA_SET                   = 0x00040000;
1648
1649    /**
1650     * Set by {@link #setScrollContainer(boolean)}.
1651     */
1652    static final int PFLAG_SCROLL_CONTAINER            = 0x00080000;
1653
1654    /**
1655     * Set by {@link #setScrollContainer(boolean)}.
1656     */
1657    static final int PFLAG_SCROLL_CONTAINER_ADDED      = 0x00100000;
1658
1659    /**
1660     * View flag indicating whether this view was invalidated (fully or partially.)
1661     *
1662     * @hide
1663     */
1664    static final int PFLAG_DIRTY                       = 0x00200000;
1665
1666    /**
1667     * View flag indicating whether this view was invalidated by an opaque
1668     * invalidate request.
1669     *
1670     * @hide
1671     */
1672    static final int PFLAG_DIRTY_OPAQUE                = 0x00400000;
1673
1674    /**
1675     * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}.
1676     *
1677     * @hide
1678     */
1679    static final int PFLAG_DIRTY_MASK                  = 0x00600000;
1680
1681    /**
1682     * Indicates whether the background is opaque.
1683     *
1684     * @hide
1685     */
1686    static final int PFLAG_OPAQUE_BACKGROUND           = 0x00800000;
1687
1688    /**
1689     * Indicates whether the scrollbars are opaque.
1690     *
1691     * @hide
1692     */
1693    static final int PFLAG_OPAQUE_SCROLLBARS           = 0x01000000;
1694
1695    /**
1696     * Indicates whether the view is opaque.
1697     *
1698     * @hide
1699     */
1700    static final int PFLAG_OPAQUE_MASK                 = 0x01800000;
1701
1702    /**
1703     * Indicates a prepressed state;
1704     * the short time between ACTION_DOWN and recognizing
1705     * a 'real' press. Prepressed is used to recognize quick taps
1706     * even when they are shorter than ViewConfiguration.getTapTimeout().
1707     *
1708     * @hide
1709     */
1710    private static final int PFLAG_PREPRESSED          = 0x02000000;
1711
1712    /**
1713     * Indicates whether the view is temporarily detached.
1714     *
1715     * @hide
1716     */
1717    static final int PFLAG_CANCEL_NEXT_UP_EVENT        = 0x04000000;
1718
1719    /**
1720     * Indicates that we should awaken scroll bars once attached
1721     *
1722     * @hide
1723     */
1724    private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1725
1726    /**
1727     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1728     * @hide
1729     */
1730    private static final int PFLAG_HOVERED             = 0x10000000;
1731
1732    /**
1733     * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1734     * for transform operations
1735     *
1736     * @hide
1737     */
1738    private static final int PFLAG_PIVOT_EXPLICITLY_SET = 0x20000000;
1739
1740    /** {@hide} */
1741    static final int PFLAG_ACTIVATED                   = 0x40000000;
1742
1743    /**
1744     * Indicates that this view was specifically invalidated, not just dirtied because some
1745     * child view was invalidated. The flag is used to determine when we need to recreate
1746     * a view's display list (as opposed to just returning a reference to its existing
1747     * display list).
1748     *
1749     * @hide
1750     */
1751    static final int PFLAG_INVALIDATED                 = 0x80000000;
1752
1753    /**
1754     * Masks for mPrivateFlags2, as generated by dumpFlags():
1755     *
1756     * |-------|-------|-------|-------|
1757     *                                 1 PFLAG2_DRAG_CAN_ACCEPT
1758     *                                1  PFLAG2_DRAG_HOVERED
1759     *                              11   PFLAG2_LAYOUT_DIRECTION_MASK
1760     *                             1     PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL
1761     *                            1      PFLAG2_LAYOUT_DIRECTION_RESOLVED
1762     *                            11     PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK
1763     *                           1       PFLAG2_TEXT_DIRECTION_FLAGS[1]
1764     *                          1        PFLAG2_TEXT_DIRECTION_FLAGS[2]
1765     *                          11       PFLAG2_TEXT_DIRECTION_FLAGS[3]
1766     *                         1         PFLAG2_TEXT_DIRECTION_FLAGS[4]
1767     *                         1 1       PFLAG2_TEXT_DIRECTION_FLAGS[5]
1768     *                         111       PFLAG2_TEXT_DIRECTION_MASK
1769     *                        1          PFLAG2_TEXT_DIRECTION_RESOLVED
1770     *                       1           PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT
1771     *                     111           PFLAG2_TEXT_DIRECTION_RESOLVED_MASK
1772     *                    1              PFLAG2_TEXT_ALIGNMENT_FLAGS[1]
1773     *                   1               PFLAG2_TEXT_ALIGNMENT_FLAGS[2]
1774     *                   11              PFLAG2_TEXT_ALIGNMENT_FLAGS[3]
1775     *                  1                PFLAG2_TEXT_ALIGNMENT_FLAGS[4]
1776     *                  1 1              PFLAG2_TEXT_ALIGNMENT_FLAGS[5]
1777     *                  11               PFLAG2_TEXT_ALIGNMENT_FLAGS[6]
1778     *                  111              PFLAG2_TEXT_ALIGNMENT_MASK
1779     *                 1                 PFLAG2_TEXT_ALIGNMENT_RESOLVED
1780     *                1                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT
1781     *              111                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK
1782     *           111                     PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK
1783     *         11                        PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK
1784     *       1                           PFLAG2_ACCESSIBILITY_FOCUSED
1785     *      1                            PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED
1786     *     1                             PFLAG2_VIEW_QUICK_REJECTED
1787     *    1                              PFLAG2_PADDING_RESOLVED
1788     *   1                               PFLAG2_DRAWABLE_RESOLVED
1789     *  1                                PFLAG2_HAS_TRANSIENT_STATE
1790     * |-------|-------|-------|-------|
1791     */
1792
1793    /**
1794     * Indicates that this view has reported that it can accept the current drag's content.
1795     * Cleared when the drag operation concludes.
1796     * @hide
1797     */
1798    static final int PFLAG2_DRAG_CAN_ACCEPT            = 0x00000001;
1799
1800    /**
1801     * Indicates that this view is currently directly under the drag location in a
1802     * drag-and-drop operation involving content that it can accept.  Cleared when
1803     * the drag exits the view, or when the drag operation concludes.
1804     * @hide
1805     */
1806    static final int PFLAG2_DRAG_HOVERED               = 0x00000002;
1807
1808    /**
1809     * Horizontal layout direction of this view is from Left to Right.
1810     * Use with {@link #setLayoutDirection}.
1811     */
1812    public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR;
1813
1814    /**
1815     * Horizontal layout direction of this view is from Right to Left.
1816     * Use with {@link #setLayoutDirection}.
1817     */
1818    public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL;
1819
1820    /**
1821     * Horizontal layout direction of this view is inherited from its parent.
1822     * Use with {@link #setLayoutDirection}.
1823     */
1824    public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT;
1825
1826    /**
1827     * Horizontal layout direction of this view is from deduced from the default language
1828     * script for the locale. Use with {@link #setLayoutDirection}.
1829     */
1830    public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE;
1831
1832    /**
1833     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1834     * @hide
1835     */
1836    static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2;
1837
1838    /**
1839     * Mask for use with private flags indicating bits used for horizontal layout direction.
1840     * @hide
1841     */
1842    static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1843
1844    /**
1845     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
1846     * right-to-left direction.
1847     * @hide
1848     */
1849    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1850
1851    /**
1852     * Indicates whether the view horizontal layout direction has been resolved.
1853     * @hide
1854     */
1855    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1856
1857    /**
1858     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
1859     * @hide
1860     */
1861    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C
1862            << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1863
1864    /*
1865     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
1866     * flag value.
1867     * @hide
1868     */
1869    private static final int[] LAYOUT_DIRECTION_FLAGS = {
1870            LAYOUT_DIRECTION_LTR,
1871            LAYOUT_DIRECTION_RTL,
1872            LAYOUT_DIRECTION_INHERIT,
1873            LAYOUT_DIRECTION_LOCALE
1874    };
1875
1876    /**
1877     * Default horizontal layout direction.
1878     */
1879    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
1880
1881    /**
1882     * Default horizontal layout direction.
1883     * @hide
1884     */
1885    static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR;
1886
1887    /**
1888     * Text direction is inherited thru {@link ViewGroup}
1889     */
1890    public static final int TEXT_DIRECTION_INHERIT = 0;
1891
1892    /**
1893     * Text direction is using "first strong algorithm". The first strong directional character
1894     * determines the paragraph direction. If there is no strong directional character, the
1895     * paragraph direction is the view's resolved layout direction.
1896     */
1897    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
1898
1899    /**
1900     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
1901     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
1902     * If there are neither, the paragraph direction is the view's resolved layout direction.
1903     */
1904    public static final int TEXT_DIRECTION_ANY_RTL = 2;
1905
1906    /**
1907     * Text direction is forced to LTR.
1908     */
1909    public static final int TEXT_DIRECTION_LTR = 3;
1910
1911    /**
1912     * Text direction is forced to RTL.
1913     */
1914    public static final int TEXT_DIRECTION_RTL = 4;
1915
1916    /**
1917     * Text direction is coming from the system Locale.
1918     */
1919    public static final int TEXT_DIRECTION_LOCALE = 5;
1920
1921    /**
1922     * Default text direction is inherited
1923     */
1924    private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
1925
1926    /**
1927     * Default resolved text direction
1928     * @hide
1929     */
1930    static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG;
1931
1932    /**
1933     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
1934     * @hide
1935     */
1936    static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6;
1937
1938    /**
1939     * Mask for use with private flags indicating bits used for text direction.
1940     * @hide
1941     */
1942    static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007
1943            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
1944
1945    /**
1946     * Array of text direction flags for mapping attribute "textDirection" to correct
1947     * flag value.
1948     * @hide
1949     */
1950    private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = {
1951            TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1952            TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1953            TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1954            TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1955            TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1956            TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT
1957    };
1958
1959    /**
1960     * Indicates whether the view text direction has been resolved.
1961     * @hide
1962     */
1963    static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008
1964            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
1965
1966    /**
1967     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1968     * @hide
1969     */
1970    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
1971
1972    /**
1973     * Mask for use with private flags indicating bits used for resolved text direction.
1974     * @hide
1975     */
1976    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007
1977            << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
1978
1979    /**
1980     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
1981     * @hide
1982     */
1983    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT =
1984            TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
1985
1986    /*
1987     * Default text alignment. The text alignment of this View is inherited from its parent.
1988     * Use with {@link #setTextAlignment(int)}
1989     */
1990    public static final int TEXT_ALIGNMENT_INHERIT = 0;
1991
1992    /**
1993     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
1994     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
1995     *
1996     * Use with {@link #setTextAlignment(int)}
1997     */
1998    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
1999
2000    /**
2001     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
2002     *
2003     * Use with {@link #setTextAlignment(int)}
2004     */
2005    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
2006
2007    /**
2008     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
2009     *
2010     * Use with {@link #setTextAlignment(int)}
2011     */
2012    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
2013
2014    /**
2015     * Center the paragraph, e.g. ALIGN_CENTER.
2016     *
2017     * Use with {@link #setTextAlignment(int)}
2018     */
2019    public static final int TEXT_ALIGNMENT_CENTER = 4;
2020
2021    /**
2022     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
2023     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
2024     *
2025     * Use with {@link #setTextAlignment(int)}
2026     */
2027    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
2028
2029    /**
2030     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
2031     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
2032     *
2033     * Use with {@link #setTextAlignment(int)}
2034     */
2035    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
2036
2037    /**
2038     * Default text alignment is inherited
2039     */
2040    private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2041
2042    /**
2043     * Default resolved text alignment
2044     * @hide
2045     */
2046    static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2047
2048    /**
2049      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2050      * @hide
2051      */
2052    static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13;
2053
2054    /**
2055      * Mask for use with private flags indicating bits used for text alignment.
2056      * @hide
2057      */
2058    static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2059
2060    /**
2061     * Array of text direction flags for mapping attribute "textAlignment" to correct
2062     * flag value.
2063     * @hide
2064     */
2065    private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = {
2066            TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2067            TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2068            TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2069            TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2070            TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2071            TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2072            TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
2073    };
2074
2075    /**
2076     * Indicates whether the view text alignment has been resolved.
2077     * @hide
2078     */
2079    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2080
2081    /**
2082     * Bit shift to get the resolved text alignment.
2083     * @hide
2084     */
2085    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2086
2087    /**
2088     * Mask for use with private flags indicating bits used for text alignment.
2089     * @hide
2090     */
2091    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007
2092            << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2093
2094    /**
2095     * Indicates whether if the view text alignment has been resolved to gravity
2096     */
2097    private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2098            TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2099
2100    // Accessiblity constants for mPrivateFlags2
2101
2102    /**
2103     * Shift for the bits in {@link #mPrivateFlags2} related to the
2104     * "importantForAccessibility" attribute.
2105     */
2106    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2107
2108    /**
2109     * Automatically determine whether a view is important for accessibility.
2110     */
2111    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2112
2113    /**
2114     * The view is important for accessibility.
2115     */
2116    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2117
2118    /**
2119     * The view is not important for accessibility.
2120     */
2121    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2122
2123    /**
2124     * The view is not important for accessibility, nor are any of its
2125     * descendant views.
2126     */
2127    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004;
2128
2129    /**
2130     * The default whether the view is important for accessibility.
2131     */
2132    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2133
2134    /**
2135     * Mask for obtainig the bits which specify how to determine
2136     * whether a view is important for accessibility.
2137     */
2138    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2139        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO
2140        | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS)
2141        << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2142
2143    /**
2144     * Shift for the bits in {@link #mPrivateFlags2} related to the
2145     * "accessibilityLiveRegion" attribute.
2146     */
2147    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23;
2148
2149    /**
2150     * Live region mode specifying that accessibility services should not
2151     * automatically announce changes to this view. This is the default live
2152     * region mode for most views.
2153     * <p>
2154     * Use with {@link #setAccessibilityLiveRegion(int)}.
2155     */
2156    public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000;
2157
2158    /**
2159     * Live region mode specifying that accessibility services should announce
2160     * changes to this view.
2161     * <p>
2162     * Use with {@link #setAccessibilityLiveRegion(int)}.
2163     */
2164    public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001;
2165
2166    /**
2167     * Live region mode specifying that accessibility services should interrupt
2168     * ongoing speech to immediately announce changes to this view.
2169     * <p>
2170     * Use with {@link #setAccessibilityLiveRegion(int)}.
2171     */
2172    public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002;
2173
2174    /**
2175     * The default whether the view is important for accessibility.
2176     */
2177    static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE;
2178
2179    /**
2180     * Mask for obtaining the bits which specify a view's accessibility live
2181     * region mode.
2182     */
2183    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE
2184            | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE)
2185            << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
2186
2187    /**
2188     * Flag indicating whether a view has accessibility focus.
2189     */
2190    static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000;
2191
2192    /**
2193     * Flag whether the accessibility state of the subtree rooted at this view changed.
2194     */
2195    static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000;
2196
2197    /**
2198     * Flag indicating whether a view failed the quickReject() check in draw(). This condition
2199     * is used to check whether later changes to the view's transform should invalidate the
2200     * view to force the quickReject test to run again.
2201     */
2202    static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000;
2203
2204    /**
2205     * Flag indicating that start/end padding has been resolved into left/right padding
2206     * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()}
2207     * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved
2208     * during measurement. In some special cases this is required such as when an adapter-based
2209     * view measures prospective children without attaching them to a window.
2210     */
2211    static final int PFLAG2_PADDING_RESOLVED = 0x20000000;
2212
2213    /**
2214     * Flag indicating that the start/end drawables has been resolved into left/right ones.
2215     */
2216    static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000;
2217
2218    /**
2219     * Indicates that the view is tracking some sort of transient state
2220     * that the app should not need to be aware of, but that the framework
2221     * should take special care to preserve.
2222     */
2223    static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000;
2224
2225    /**
2226     * Group of bits indicating that RTL properties resolution is done.
2227     */
2228    static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED |
2229            PFLAG2_TEXT_DIRECTION_RESOLVED |
2230            PFLAG2_TEXT_ALIGNMENT_RESOLVED |
2231            PFLAG2_PADDING_RESOLVED |
2232            PFLAG2_DRAWABLE_RESOLVED;
2233
2234    // There are a couple of flags left in mPrivateFlags2
2235
2236    /* End of masks for mPrivateFlags2 */
2237
2238    /* Masks for mPrivateFlags3 */
2239
2240    /**
2241     * Flag indicating that view has a transform animation set on it. This is used to track whether
2242     * an animation is cleared between successive frames, in order to tell the associated
2243     * DisplayList to clear its animation matrix.
2244     */
2245    static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1;
2246
2247    /**
2248     * Flag indicating that view has an alpha animation set on it. This is used to track whether an
2249     * animation is cleared between successive frames, in order to tell the associated
2250     * DisplayList to restore its alpha value.
2251     */
2252    static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2;
2253
2254    /**
2255     * Flag indicating that the view has been through at least one layout since it
2256     * was last attached to a window.
2257     */
2258    static final int PFLAG3_IS_LAID_OUT = 0x4;
2259
2260    /**
2261     * Flag indicating that a call to measure() was skipped and should be done
2262     * instead when layout() is invoked.
2263     */
2264    static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8;
2265
2266    /**
2267     * Flag indicating that an overridden method correctly  called down to
2268     * the superclass implementation as required by the API spec.
2269     */
2270    static final int PFLAG3_CALLED_SUPER = 0x10;
2271
2272
2273    /* End of masks for mPrivateFlags3 */
2274
2275    static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED;
2276
2277    /**
2278     * Always allow a user to over-scroll this view, provided it is a
2279     * view that can scroll.
2280     *
2281     * @see #getOverScrollMode()
2282     * @see #setOverScrollMode(int)
2283     */
2284    public static final int OVER_SCROLL_ALWAYS = 0;
2285
2286    /**
2287     * Allow a user to over-scroll this view only if the content is large
2288     * enough to meaningfully scroll, provided it is a view that can scroll.
2289     *
2290     * @see #getOverScrollMode()
2291     * @see #setOverScrollMode(int)
2292     */
2293    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2294
2295    /**
2296     * Never allow a user to over-scroll this view.
2297     *
2298     * @see #getOverScrollMode()
2299     * @see #setOverScrollMode(int)
2300     */
2301    public static final int OVER_SCROLL_NEVER = 2;
2302
2303    /**
2304     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2305     * requested the system UI (status bar) to be visible (the default).
2306     *
2307     * @see #setSystemUiVisibility(int)
2308     */
2309    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2310
2311    /**
2312     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2313     * system UI to enter an unobtrusive "low profile" mode.
2314     *
2315     * <p>This is for use in games, book readers, video players, or any other
2316     * "immersive" application where the usual system chrome is deemed too distracting.
2317     *
2318     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2319     *
2320     * @see #setSystemUiVisibility(int)
2321     */
2322    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2323
2324    /**
2325     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2326     * system navigation be temporarily hidden.
2327     *
2328     * <p>This is an even less obtrusive state than that called for by
2329     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2330     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2331     * those to disappear. This is useful (in conjunction with the
2332     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2333     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2334     * window flags) for displaying content using every last pixel on the display.
2335     *
2336     * <p>There is a limitation: because navigation controls are so important, the least user
2337     * interaction will cause them to reappear immediately.  When this happens, both
2338     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2339     * so that both elements reappear at the same time.
2340     *
2341     * @see #setSystemUiVisibility(int)
2342     */
2343    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2344
2345    /**
2346     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2347     * into the normal fullscreen mode so that its content can take over the screen
2348     * while still allowing the user to interact with the application.
2349     *
2350     * <p>This has the same visual effect as
2351     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2352     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2353     * meaning that non-critical screen decorations (such as the status bar) will be
2354     * hidden while the user is in the View's window, focusing the experience on
2355     * that content.  Unlike the window flag, if you are using ActionBar in
2356     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2357     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2358     * hide the action bar.
2359     *
2360     * <p>This approach to going fullscreen is best used over the window flag when
2361     * it is a transient state -- that is, the application does this at certain
2362     * points in its user interaction where it wants to allow the user to focus
2363     * on content, but not as a continuous state.  For situations where the application
2364     * would like to simply stay full screen the entire time (such as a game that
2365     * wants to take over the screen), the
2366     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2367     * is usually a better approach.  The state set here will be removed by the system
2368     * in various situations (such as the user moving to another application) like
2369     * the other system UI states.
2370     *
2371     * <p>When using this flag, the application should provide some easy facility
2372     * for the user to go out of it.  A common example would be in an e-book
2373     * reader, where tapping on the screen brings back whatever screen and UI
2374     * decorations that had been hidden while the user was immersed in reading
2375     * the book.
2376     *
2377     * @see #setSystemUiVisibility(int)
2378     */
2379    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2380
2381    /**
2382     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2383     * flags, we would like a stable view of the content insets given to
2384     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2385     * will always represent the worst case that the application can expect
2386     * as a continuous state.  In the stock Android UI this is the space for
2387     * the system bar, nav bar, and status bar, but not more transient elements
2388     * such as an input method.
2389     *
2390     * The stable layout your UI sees is based on the system UI modes you can
2391     * switch to.  That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
2392     * then you will get a stable layout for changes of the
2393     * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
2394     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
2395     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
2396     * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
2397     * with a stable layout.  (Note that you should avoid using
2398     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
2399     *
2400     * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN}
2401     * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
2402     * then a hidden status bar will be considered a "stable" state for purposes
2403     * here.  This allows your UI to continually hide the status bar, while still
2404     * using the system UI flags to hide the action bar while still retaining
2405     * a stable layout.  Note that changing the window fullscreen flag will never
2406     * provide a stable layout for a clean transition.
2407     *
2408     * <p>If you are using ActionBar in
2409     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2410     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2411     * insets it adds to those given to the application.
2412     */
2413    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2414
2415    /**
2416     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2417     * to be layed out as if it has requested
2418     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2419     * allows it to avoid artifacts when switching in and out of that mode, at
2420     * the expense that some of its user interface may be covered by screen
2421     * decorations when they are shown.  You can perform layout of your inner
2422     * UI elements to account for the navigation system UI through the
2423     * {@link #fitSystemWindows(Rect)} method.
2424     */
2425    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2426
2427    /**
2428     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2429     * to be layed out as if it has requested
2430     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2431     * allows it to avoid artifacts when switching in and out of that mode, at
2432     * the expense that some of its user interface may be covered by screen
2433     * decorations when they are shown.  You can perform layout of your inner
2434     * UI elements to account for non-fullscreen system UI through the
2435     * {@link #fitSystemWindows(Rect)} method.
2436     */
2437    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2438
2439    /**
2440     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2441     * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  If this flag is
2442     * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any
2443     * user interaction.
2444     * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only
2445     * has an effect when used in combination with that flag.</p>
2446     */
2447    public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800;
2448
2449    /**
2450     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2451     * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation
2452     * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  Use this flag to create an immersive
2453     * experience while also hiding the system bars.  If this flag is not set,
2454     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user
2455     * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system
2456     * if the user swipes from the top of the screen.
2457     * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with
2458     * system gestures, such as swiping from the top of the screen.  These transient system bars
2459     * will overlay app’s content, may have some degree of transparency, and will automatically
2460     * hide after a short timeout.
2461     * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and
2462     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination
2463     * with one or both of those flags.</p>
2464     */
2465    public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000;
2466
2467    /**
2468     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2469     */
2470    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2471
2472    /**
2473     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2474     */
2475    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2476
2477    /**
2478     * @hide
2479     *
2480     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2481     * out of the public fields to keep the undefined bits out of the developer's way.
2482     *
2483     * Flag to make the status bar not expandable.  Unless you also
2484     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
2485     */
2486    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
2487
2488    /**
2489     * @hide
2490     *
2491     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2492     * out of the public fields to keep the undefined bits out of the developer's way.
2493     *
2494     * Flag to hide notification icons and scrolling ticker text.
2495     */
2496    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
2497
2498    /**
2499     * @hide
2500     *
2501     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2502     * out of the public fields to keep the undefined bits out of the developer's way.
2503     *
2504     * Flag to disable incoming notification alerts.  This will not block
2505     * icons, but it will block sound, vibrating and other visual or aural notifications.
2506     */
2507    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
2508
2509    /**
2510     * @hide
2511     *
2512     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2513     * out of the public fields to keep the undefined bits out of the developer's way.
2514     *
2515     * Flag to hide only the scrolling ticker.  Note that
2516     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
2517     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
2518     */
2519    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
2520
2521    /**
2522     * @hide
2523     *
2524     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2525     * out of the public fields to keep the undefined bits out of the developer's way.
2526     *
2527     * Flag to hide the center system info area.
2528     */
2529    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
2530
2531    /**
2532     * @hide
2533     *
2534     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2535     * out of the public fields to keep the undefined bits out of the developer's way.
2536     *
2537     * Flag to hide only the home button.  Don't use this
2538     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2539     */
2540    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
2541
2542    /**
2543     * @hide
2544     *
2545     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2546     * out of the public fields to keep the undefined bits out of the developer's way.
2547     *
2548     * Flag to hide only the back button. Don't use this
2549     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2550     */
2551    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
2552
2553    /**
2554     * @hide
2555     *
2556     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2557     * out of the public fields to keep the undefined bits out of the developer's way.
2558     *
2559     * Flag to hide only the clock.  You might use this if your activity has
2560     * its own clock making the status bar's clock redundant.
2561     */
2562    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
2563
2564    /**
2565     * @hide
2566     *
2567     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2568     * out of the public fields to keep the undefined bits out of the developer's way.
2569     *
2570     * Flag to hide only the recent apps button. Don't use this
2571     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2572     */
2573    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
2574
2575    /**
2576     * @hide
2577     *
2578     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2579     * out of the public fields to keep the undefined bits out of the developer's way.
2580     *
2581     * Flag to disable the global search gesture. Don't use this
2582     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2583     */
2584    public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000;
2585
2586    /**
2587     * @hide
2588     *
2589     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2590     * out of the public fields to keep the undefined bits out of the developer's way.
2591     *
2592     * Flag to specify that the status bar is displayed in transient mode.
2593     */
2594    public static final int STATUS_BAR_TRANSIENT = 0x04000000;
2595
2596    /**
2597     * @hide
2598     *
2599     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2600     * out of the public fields to keep the undefined bits out of the developer's way.
2601     *
2602     * Flag to specify that the navigation bar is displayed in transient mode.
2603     */
2604    public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000;
2605
2606    /**
2607     * @hide
2608     *
2609     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2610     * out of the public fields to keep the undefined bits out of the developer's way.
2611     *
2612     * Flag to specify that the hidden status bar would like to be shown.
2613     */
2614    public static final int STATUS_BAR_UNHIDE = 0x10000000;
2615
2616    /**
2617     * @hide
2618     *
2619     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2620     * out of the public fields to keep the undefined bits out of the developer's way.
2621     *
2622     * Flag to specify that the hidden navigation bar would like to be shown.
2623     */
2624    public static final int NAVIGATION_BAR_UNHIDE = 0x20000000;
2625
2626    /**
2627     * @hide
2628     *
2629     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2630     * out of the public fields to keep the undefined bits out of the developer's way.
2631     *
2632     * Flag to specify that the status bar is displayed in translucent mode.
2633     */
2634    public static final int STATUS_BAR_TRANSLUCENT = 0x40000000;
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 specify that the navigation bar is displayed in translucent mode.
2643     */
2644    public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000;
2645
2646    /**
2647     * @hide
2648     */
2649    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF;
2650
2651    /**
2652     * These are the system UI flags that can be cleared by events outside
2653     * of an application.  Currently this is just the ability to tap on the
2654     * screen while hiding the navigation bar to have it return.
2655     * @hide
2656     */
2657    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
2658            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
2659            | SYSTEM_UI_FLAG_FULLSCREEN;
2660
2661    /**
2662     * Flags that can impact the layout in relation to system UI.
2663     */
2664    public static final int SYSTEM_UI_LAYOUT_FLAGS =
2665            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
2666            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
2667
2668    /**
2669     * Find views that render the specified text.
2670     *
2671     * @see #findViewsWithText(ArrayList, CharSequence, int)
2672     */
2673    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
2674
2675    /**
2676     * Find find views that contain the specified content description.
2677     *
2678     * @see #findViewsWithText(ArrayList, CharSequence, int)
2679     */
2680    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
2681
2682    /**
2683     * Find views that contain {@link AccessibilityNodeProvider}. Such
2684     * a View is a root of virtual view hierarchy and may contain the searched
2685     * text. If this flag is set Views with providers are automatically
2686     * added and it is a responsibility of the client to call the APIs of
2687     * the provider to determine whether the virtual tree rooted at this View
2688     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
2689     * represeting the virtual views with this text.
2690     *
2691     * @see #findViewsWithText(ArrayList, CharSequence, int)
2692     *
2693     * @hide
2694     */
2695    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
2696
2697    /**
2698     * The undefined cursor position.
2699     *
2700     * @hide
2701     */
2702    public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1;
2703
2704    /**
2705     * Indicates that the screen has changed state and is now off.
2706     *
2707     * @see #onScreenStateChanged(int)
2708     */
2709    public static final int SCREEN_STATE_OFF = 0x0;
2710
2711    /**
2712     * Indicates that the screen has changed state and is now on.
2713     *
2714     * @see #onScreenStateChanged(int)
2715     */
2716    public static final int SCREEN_STATE_ON = 0x1;
2717
2718    /**
2719     * Controls the over-scroll mode for this view.
2720     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
2721     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
2722     * and {@link #OVER_SCROLL_NEVER}.
2723     */
2724    private int mOverScrollMode;
2725
2726    /**
2727     * The parent this view is attached to.
2728     * {@hide}
2729     *
2730     * @see #getParent()
2731     */
2732    protected ViewParent mParent;
2733
2734    /**
2735     * {@hide}
2736     */
2737    AttachInfo mAttachInfo;
2738
2739    /**
2740     * {@hide}
2741     */
2742    @ViewDebug.ExportedProperty(flagMapping = {
2743        @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT,
2744                name = "FORCE_LAYOUT"),
2745        @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED,
2746                name = "LAYOUT_REQUIRED"),
2747        @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID,
2748            name = "DRAWING_CACHE_INVALID", outputIf = false),
2749        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true),
2750        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false),
2751        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
2752        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY")
2753    })
2754    int mPrivateFlags;
2755    int mPrivateFlags2;
2756    int mPrivateFlags3;
2757
2758    /**
2759     * This view's request for the visibility of the status bar.
2760     * @hide
2761     */
2762    @ViewDebug.ExportedProperty(flagMapping = {
2763        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
2764                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
2765                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
2766        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2767                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2768                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
2769        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
2770                                equals = SYSTEM_UI_FLAG_VISIBLE,
2771                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
2772    })
2773    int mSystemUiVisibility;
2774
2775    /**
2776     * Reference count for transient state.
2777     * @see #setHasTransientState(boolean)
2778     */
2779    int mTransientStateCount = 0;
2780
2781    /**
2782     * Count of how many windows this view has been attached to.
2783     */
2784    int mWindowAttachCount;
2785
2786    /**
2787     * The layout parameters associated with this view and used by the parent
2788     * {@link android.view.ViewGroup} to determine how this view should be
2789     * laid out.
2790     * {@hide}
2791     */
2792    protected ViewGroup.LayoutParams mLayoutParams;
2793
2794    /**
2795     * The view flags hold various views states.
2796     * {@hide}
2797     */
2798    @ViewDebug.ExportedProperty
2799    int mViewFlags;
2800
2801    static class TransformationInfo {
2802        /**
2803         * The transform matrix for the View. This transform is calculated internally
2804         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2805         * is used by default. Do *not* use this variable directly; instead call
2806         * getMatrix(), which will automatically recalculate the matrix if necessary
2807         * to get the correct matrix based on the latest rotation and scale properties.
2808         */
2809        private final Matrix mMatrix = new Matrix();
2810
2811        /**
2812         * The transform matrix for the View. This transform is calculated internally
2813         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2814         * is used by default. Do *not* use this variable directly; instead call
2815         * getInverseMatrix(), which will automatically recalculate the matrix if necessary
2816         * to get the correct matrix based on the latest rotation and scale properties.
2817         */
2818        private Matrix mInverseMatrix;
2819
2820        /**
2821         * An internal variable that tracks whether we need to recalculate the
2822         * transform matrix, based on whether the rotation or scaleX/Y properties
2823         * have changed since the matrix was last calculated.
2824         */
2825        boolean mMatrixDirty = false;
2826
2827        /**
2828         * An internal variable that tracks whether we need to recalculate the
2829         * transform matrix, based on whether the rotation or scaleX/Y properties
2830         * have changed since the matrix was last calculated.
2831         */
2832        private boolean mInverseMatrixDirty = true;
2833
2834        /**
2835         * A variable that tracks whether we need to recalculate the
2836         * transform matrix, based on whether the rotation or scaleX/Y properties
2837         * have changed since the matrix was last calculated. This variable
2838         * is only valid after a call to updateMatrix() or to a function that
2839         * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
2840         */
2841        private boolean mMatrixIsIdentity = true;
2842
2843        /**
2844         * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
2845         */
2846        private Camera mCamera = null;
2847
2848        /**
2849         * This matrix is used when computing the matrix for 3D rotations.
2850         */
2851        private Matrix matrix3D = null;
2852
2853        /**
2854         * These prev values are used to recalculate a centered pivot point when necessary. The
2855         * pivot point is only used in matrix operations (when rotation, scale, or translation are
2856         * set), so thes values are only used then as well.
2857         */
2858        private int mPrevWidth = -1;
2859        private int mPrevHeight = -1;
2860
2861        /**
2862         * The degrees rotation around the vertical axis through the pivot point.
2863         */
2864        @ViewDebug.ExportedProperty
2865        float mRotationY = 0f;
2866
2867        /**
2868         * The degrees rotation around the horizontal axis through the pivot point.
2869         */
2870        @ViewDebug.ExportedProperty
2871        float mRotationX = 0f;
2872
2873        /**
2874         * The degrees rotation around the pivot point.
2875         */
2876        @ViewDebug.ExportedProperty
2877        float mRotation = 0f;
2878
2879        /**
2880         * The amount of translation of the object away from its left property (post-layout).
2881         */
2882        @ViewDebug.ExportedProperty
2883        float mTranslationX = 0f;
2884
2885        /**
2886         * The amount of translation of the object away from its top property (post-layout).
2887         */
2888        @ViewDebug.ExportedProperty
2889        float mTranslationY = 0f;
2890
2891        /**
2892         * The amount of scale in the x direction around the pivot point. A
2893         * value of 1 means no scaling is applied.
2894         */
2895        @ViewDebug.ExportedProperty
2896        float mScaleX = 1f;
2897
2898        /**
2899         * The amount of scale in the y direction around the pivot point. A
2900         * value of 1 means no scaling is applied.
2901         */
2902        @ViewDebug.ExportedProperty
2903        float mScaleY = 1f;
2904
2905        /**
2906         * The x location of the point around which the view is rotated and scaled.
2907         */
2908        @ViewDebug.ExportedProperty
2909        float mPivotX = 0f;
2910
2911        /**
2912         * The y location of the point around which the view is rotated and scaled.
2913         */
2914        @ViewDebug.ExportedProperty
2915        float mPivotY = 0f;
2916
2917        /**
2918         * The opacity of the View. This is a value from 0 to 1, where 0 means
2919         * completely transparent and 1 means completely opaque.
2920         */
2921        @ViewDebug.ExportedProperty
2922        float mAlpha = 1f;
2923
2924        /**
2925         * The opacity of the view as manipulated by the Fade transition. This is a hidden
2926         * property only used by transitions, which is composited with the other alpha
2927         * values to calculate the final visual alpha value.
2928         */
2929        float mTransitionAlpha = 1f;
2930    }
2931
2932    TransformationInfo mTransformationInfo;
2933
2934    /**
2935     * Current clip bounds. to which all drawing of this view are constrained.
2936     */
2937    private Rect mClipBounds = null;
2938
2939    private boolean mLastIsOpaque;
2940
2941    /**
2942     * Convenience value to check for float values that are close enough to zero to be considered
2943     * zero.
2944     */
2945    private static final float NONZERO_EPSILON = .001f;
2946
2947    /**
2948     * The distance in pixels from the left edge of this view's parent
2949     * to the left edge of this view.
2950     * {@hide}
2951     */
2952    @ViewDebug.ExportedProperty(category = "layout")
2953    protected int mLeft;
2954    /**
2955     * The distance in pixels from the left edge of this view's parent
2956     * to the right edge of this view.
2957     * {@hide}
2958     */
2959    @ViewDebug.ExportedProperty(category = "layout")
2960    protected int mRight;
2961    /**
2962     * The distance in pixels from the top edge of this view's parent
2963     * to the top edge of this view.
2964     * {@hide}
2965     */
2966    @ViewDebug.ExportedProperty(category = "layout")
2967    protected int mTop;
2968    /**
2969     * The distance in pixels from the top edge of this view's parent
2970     * to the bottom edge of this view.
2971     * {@hide}
2972     */
2973    @ViewDebug.ExportedProperty(category = "layout")
2974    protected int mBottom;
2975
2976    /**
2977     * The offset, in pixels, by which the content of this view is scrolled
2978     * horizontally.
2979     * {@hide}
2980     */
2981    @ViewDebug.ExportedProperty(category = "scrolling")
2982    protected int mScrollX;
2983    /**
2984     * The offset, in pixels, by which the content of this view is scrolled
2985     * vertically.
2986     * {@hide}
2987     */
2988    @ViewDebug.ExportedProperty(category = "scrolling")
2989    protected int mScrollY;
2990
2991    /**
2992     * The left padding in pixels, that is the distance in pixels between the
2993     * left edge of this view and the left edge of its content.
2994     * {@hide}
2995     */
2996    @ViewDebug.ExportedProperty(category = "padding")
2997    protected int mPaddingLeft = 0;
2998    /**
2999     * The right padding in pixels, that is the distance in pixels between the
3000     * right edge of this view and the right edge of its content.
3001     * {@hide}
3002     */
3003    @ViewDebug.ExportedProperty(category = "padding")
3004    protected int mPaddingRight = 0;
3005    /**
3006     * The top padding in pixels, that is the distance in pixels between the
3007     * top edge of this view and the top edge of its content.
3008     * {@hide}
3009     */
3010    @ViewDebug.ExportedProperty(category = "padding")
3011    protected int mPaddingTop;
3012    /**
3013     * The bottom padding in pixels, that is the distance in pixels between the
3014     * bottom edge of this view and the bottom edge of its content.
3015     * {@hide}
3016     */
3017    @ViewDebug.ExportedProperty(category = "padding")
3018    protected int mPaddingBottom;
3019
3020    /**
3021     * The layout insets in pixels, that is the distance in pixels between the
3022     * visible edges of this view its bounds.
3023     */
3024    private Insets mLayoutInsets;
3025
3026    /**
3027     * Briefly describes the view and is primarily used for accessibility support.
3028     */
3029    private CharSequence mContentDescription;
3030
3031    /**
3032     * Specifies the id of a view for which this view serves as a label for
3033     * accessibility purposes.
3034     */
3035    private int mLabelForId = View.NO_ID;
3036
3037    /**
3038     * Predicate for matching labeled view id with its label for
3039     * accessibility purposes.
3040     */
3041    private MatchLabelForPredicate mMatchLabelForPredicate;
3042
3043    /**
3044     * Predicate for matching a view by its id.
3045     */
3046    private MatchIdPredicate mMatchIdPredicate;
3047
3048    /**
3049     * Cache the paddingRight set by the user to append to the scrollbar's size.
3050     *
3051     * @hide
3052     */
3053    @ViewDebug.ExportedProperty(category = "padding")
3054    protected int mUserPaddingRight;
3055
3056    /**
3057     * Cache the paddingBottom set by the user to append to the scrollbar's size.
3058     *
3059     * @hide
3060     */
3061    @ViewDebug.ExportedProperty(category = "padding")
3062    protected int mUserPaddingBottom;
3063
3064    /**
3065     * Cache the paddingLeft set by the user to append to the scrollbar's size.
3066     *
3067     * @hide
3068     */
3069    @ViewDebug.ExportedProperty(category = "padding")
3070    protected int mUserPaddingLeft;
3071
3072    /**
3073     * Cache the paddingStart set by the user to append to the scrollbar's size.
3074     *
3075     */
3076    @ViewDebug.ExportedProperty(category = "padding")
3077    int mUserPaddingStart;
3078
3079    /**
3080     * Cache the paddingEnd set by the user to append to the scrollbar's size.
3081     *
3082     */
3083    @ViewDebug.ExportedProperty(category = "padding")
3084    int mUserPaddingEnd;
3085
3086    /**
3087     * Cache initial left padding.
3088     *
3089     * @hide
3090     */
3091    int mUserPaddingLeftInitial;
3092
3093    /**
3094     * Cache initial right padding.
3095     *
3096     * @hide
3097     */
3098    int mUserPaddingRightInitial;
3099
3100    /**
3101     * Default undefined padding
3102     */
3103    private static final int UNDEFINED_PADDING = Integer.MIN_VALUE;
3104
3105    private boolean mUseBackgroundPadding = false;
3106
3107    /**
3108     * @hide
3109     */
3110    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
3111    /**
3112     * @hide
3113     */
3114    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
3115
3116    private LongSparseLongArray mMeasureCache;
3117
3118    @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_")
3119    private Drawable mBackground;
3120
3121    private int mBackgroundResource;
3122    private boolean mBackgroundSizeChanged;
3123
3124    static class ListenerInfo {
3125        /**
3126         * Listener used to dispatch focus change events.
3127         * This field should be made private, so it is hidden from the SDK.
3128         * {@hide}
3129         */
3130        protected OnFocusChangeListener mOnFocusChangeListener;
3131
3132        /**
3133         * Listeners for layout change events.
3134         */
3135        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
3136
3137        /**
3138         * Listeners for attach events.
3139         */
3140        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
3141
3142        /**
3143         * Listener used to dispatch click events.
3144         * This field should be made private, so it is hidden from the SDK.
3145         * {@hide}
3146         */
3147        public OnClickListener mOnClickListener;
3148
3149        /**
3150         * Listener used to dispatch long click events.
3151         * This field should be made private, so it is hidden from the SDK.
3152         * {@hide}
3153         */
3154        protected OnLongClickListener mOnLongClickListener;
3155
3156        /**
3157         * Listener used to build the context menu.
3158         * This field should be made private, so it is hidden from the SDK.
3159         * {@hide}
3160         */
3161        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
3162
3163        private OnKeyListener mOnKeyListener;
3164
3165        private OnTouchListener mOnTouchListener;
3166
3167        private OnHoverListener mOnHoverListener;
3168
3169        private OnGenericMotionListener mOnGenericMotionListener;
3170
3171        private OnDragListener mOnDragListener;
3172
3173        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
3174    }
3175
3176    ListenerInfo mListenerInfo;
3177
3178    /**
3179     * The application environment this view lives in.
3180     * This field should be made private, so it is hidden from the SDK.
3181     * {@hide}
3182     */
3183    protected Context mContext;
3184
3185    private final Resources mResources;
3186
3187    private ScrollabilityCache mScrollCache;
3188
3189    private int[] mDrawableState = null;
3190
3191    /**
3192     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
3193     * the user may specify which view to go to next.
3194     */
3195    private int mNextFocusLeftId = View.NO_ID;
3196
3197    /**
3198     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
3199     * the user may specify which view to go to next.
3200     */
3201    private int mNextFocusRightId = View.NO_ID;
3202
3203    /**
3204     * When this view has focus and the next focus is {@link #FOCUS_UP},
3205     * the user may specify which view to go to next.
3206     */
3207    private int mNextFocusUpId = View.NO_ID;
3208
3209    /**
3210     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
3211     * the user may specify which view to go to next.
3212     */
3213    private int mNextFocusDownId = View.NO_ID;
3214
3215    /**
3216     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
3217     * the user may specify which view to go to next.
3218     */
3219    int mNextFocusForwardId = View.NO_ID;
3220
3221    private CheckForLongPress mPendingCheckForLongPress;
3222    private CheckForTap mPendingCheckForTap = null;
3223    private PerformClick mPerformClick;
3224    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
3225
3226    private UnsetPressedState mUnsetPressedState;
3227
3228    /**
3229     * Whether the long press's action has been invoked.  The tap's action is invoked on the
3230     * up event while a long press is invoked as soon as the long press duration is reached, so
3231     * a long press could be performed before the tap is checked, in which case the tap's action
3232     * should not be invoked.
3233     */
3234    private boolean mHasPerformedLongPress;
3235
3236    /**
3237     * The minimum height of the view. We'll try our best to have the height
3238     * of this view to at least this amount.
3239     */
3240    @ViewDebug.ExportedProperty(category = "measurement")
3241    private int mMinHeight;
3242
3243    /**
3244     * The minimum width of the view. We'll try our best to have the width
3245     * of this view to at least this amount.
3246     */
3247    @ViewDebug.ExportedProperty(category = "measurement")
3248    private int mMinWidth;
3249
3250    /**
3251     * The delegate to handle touch events that are physically in this view
3252     * but should be handled by another view.
3253     */
3254    private TouchDelegate mTouchDelegate = null;
3255
3256    /**
3257     * Solid color to use as a background when creating the drawing cache. Enables
3258     * the cache to use 16 bit bitmaps instead of 32 bit.
3259     */
3260    private int mDrawingCacheBackgroundColor = 0;
3261
3262    /**
3263     * Special tree observer used when mAttachInfo is null.
3264     */
3265    private ViewTreeObserver mFloatingTreeObserver;
3266
3267    /**
3268     * Cache the touch slop from the context that created the view.
3269     */
3270    private int mTouchSlop;
3271
3272    /**
3273     * Object that handles automatic animation of view properties.
3274     */
3275    private ViewPropertyAnimator mAnimator = null;
3276
3277    /**
3278     * Flag indicating that a drag can cross window boundaries.  When
3279     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
3280     * with this flag set, all visible applications will be able to participate
3281     * in the drag operation and receive the dragged content.
3282     *
3283     * @hide
3284     */
3285    public static final int DRAG_FLAG_GLOBAL = 1;
3286
3287    /**
3288     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
3289     */
3290    private float mVerticalScrollFactor;
3291
3292    /**
3293     * Position of the vertical scroll bar.
3294     */
3295    private int mVerticalScrollbarPosition;
3296
3297    /**
3298     * Position the scroll bar at the default position as determined by the system.
3299     */
3300    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
3301
3302    /**
3303     * Position the scroll bar along the left edge.
3304     */
3305    public static final int SCROLLBAR_POSITION_LEFT = 1;
3306
3307    /**
3308     * Position the scroll bar along the right edge.
3309     */
3310    public static final int SCROLLBAR_POSITION_RIGHT = 2;
3311
3312    /**
3313     * Indicates that the view does not have a layer.
3314     *
3315     * @see #getLayerType()
3316     * @see #setLayerType(int, android.graphics.Paint)
3317     * @see #LAYER_TYPE_SOFTWARE
3318     * @see #LAYER_TYPE_HARDWARE
3319     */
3320    public static final int LAYER_TYPE_NONE = 0;
3321
3322    /**
3323     * <p>Indicates that the view has a software layer. A software layer is backed
3324     * by a bitmap and causes the view to be rendered using Android's software
3325     * rendering pipeline, even if hardware acceleration is enabled.</p>
3326     *
3327     * <p>Software layers have various usages:</p>
3328     * <p>When the application is not using hardware acceleration, a software layer
3329     * is useful to apply a specific color filter and/or blending mode and/or
3330     * translucency to a view and all its children.</p>
3331     * <p>When the application is using hardware acceleration, a software layer
3332     * is useful to render drawing primitives not supported by the hardware
3333     * accelerated pipeline. It can also be used to cache a complex view tree
3334     * into a texture and reduce the complexity of drawing operations. For instance,
3335     * when animating a complex view tree with a translation, a software layer can
3336     * be used to render the view tree only once.</p>
3337     * <p>Software layers should be avoided when the affected view tree updates
3338     * often. Every update will require to re-render the software layer, which can
3339     * potentially be slow (particularly when hardware acceleration is turned on
3340     * since the layer will have to be uploaded into a hardware texture after every
3341     * update.)</p>
3342     *
3343     * @see #getLayerType()
3344     * @see #setLayerType(int, android.graphics.Paint)
3345     * @see #LAYER_TYPE_NONE
3346     * @see #LAYER_TYPE_HARDWARE
3347     */
3348    public static final int LAYER_TYPE_SOFTWARE = 1;
3349
3350    /**
3351     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3352     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3353     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3354     * rendering pipeline, but only if hardware acceleration is turned on for the
3355     * view hierarchy. When hardware acceleration is turned off, hardware layers
3356     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3357     *
3358     * <p>A hardware layer is useful to apply a specific color filter and/or
3359     * blending mode and/or translucency to a view and all its children.</p>
3360     * <p>A hardware layer can be used to cache a complex view tree into a
3361     * texture and reduce the complexity of drawing operations. For instance,
3362     * when animating a complex view tree with a translation, a hardware layer can
3363     * be used to render the view tree only once.</p>
3364     * <p>A hardware layer can also be used to increase the rendering quality when
3365     * rotation transformations are applied on a view. It can also be used to
3366     * prevent potential clipping issues when applying 3D transforms on a view.</p>
3367     *
3368     * @see #getLayerType()
3369     * @see #setLayerType(int, android.graphics.Paint)
3370     * @see #LAYER_TYPE_NONE
3371     * @see #LAYER_TYPE_SOFTWARE
3372     */
3373    public static final int LAYER_TYPE_HARDWARE = 2;
3374
3375    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3376            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
3377            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
3378            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
3379    })
3380    int mLayerType = LAYER_TYPE_NONE;
3381    Paint mLayerPaint;
3382    Rect mLocalDirtyRect;
3383    private HardwareLayer mHardwareLayer;
3384
3385    /**
3386     * Set to true when drawing cache is enabled and cannot be created.
3387     *
3388     * @hide
3389     */
3390    public boolean mCachingFailed;
3391    private Bitmap mDrawingCache;
3392    private Bitmap mUnscaledDrawingCache;
3393
3394    DisplayList mDisplayList;
3395
3396    /**
3397     * Set to true when the view is sending hover accessibility events because it
3398     * is the innermost hovered view.
3399     */
3400    private boolean mSendingHoverAccessibilityEvents;
3401
3402    /**
3403     * Delegate for injecting accessibility functionality.
3404     */
3405    AccessibilityDelegate mAccessibilityDelegate;
3406
3407    /**
3408     * The view's overlay layer. Developers get a reference to the overlay via getOverlay()
3409     * and add/remove objects to/from the overlay directly through the Overlay methods.
3410     */
3411    ViewOverlay mOverlay;
3412
3413    /**
3414     * Consistency verifier for debugging purposes.
3415     * @hide
3416     */
3417    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
3418            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
3419                    new InputEventConsistencyVerifier(this, 0) : null;
3420
3421    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
3422
3423    /**
3424     * Simple constructor to use when creating a view from code.
3425     *
3426     * @param context The Context the view is running in, through which it can
3427     *        access the current theme, resources, etc.
3428     */
3429    public View(Context context) {
3430        mContext = context;
3431        mResources = context != null ? context.getResources() : null;
3432        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
3433        // Set some flags defaults
3434        mPrivateFlags2 =
3435                (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) |
3436                (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) |
3437                (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) |
3438                (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) |
3439                (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) |
3440                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
3441        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
3442        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
3443        mUserPaddingStart = UNDEFINED_PADDING;
3444        mUserPaddingEnd = UNDEFINED_PADDING;
3445
3446        if (!sCompatibilityDone && context != null) {
3447            final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3448
3449            // Older apps may need this compatibility hack for measurement.
3450            sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1;
3451
3452            // Older apps expect onMeasure() to always be called on a layout pass, regardless
3453            // of whether a layout was requested on that View.
3454            sIgnoreMeasureCache = targetSdkVersion < KITKAT;
3455
3456            sCompatibilityDone = true;
3457        }
3458    }
3459
3460    /**
3461     * Constructor that is called when inflating a view from XML. This is called
3462     * when a view is being constructed from an XML file, supplying attributes
3463     * that were specified in the XML file. This version uses a default style of
3464     * 0, so the only attribute values applied are those in the Context's Theme
3465     * and the given AttributeSet.
3466     *
3467     * <p>
3468     * The method onFinishInflate() will be called after all children have been
3469     * added.
3470     *
3471     * @param context The Context the view is running in, through which it can
3472     *        access the current theme, resources, etc.
3473     * @param attrs The attributes of the XML tag that is inflating the view.
3474     * @see #View(Context, AttributeSet, int)
3475     */
3476    public View(Context context, AttributeSet attrs) {
3477        this(context, attrs, 0);
3478    }
3479
3480    /**
3481     * Perform inflation from XML and apply a class-specific base style. This
3482     * constructor of View allows subclasses to use their own base style when
3483     * they are inflating. For example, a Button class's constructor would call
3484     * this version of the super class constructor and supply
3485     * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
3486     * the theme's button style to modify all of the base view attributes (in
3487     * particular its background) as well as the Button class's attributes.
3488     *
3489     * @param context The Context the view is running in, through which it can
3490     *        access the current theme, resources, etc.
3491     * @param attrs The attributes of the XML tag that is inflating the view.
3492     * @param defStyleAttr An attribute in the current theme that contains a
3493     *        reference to a style resource to apply to this view. If 0, no
3494     *        default style will be applied.
3495     * @see #View(Context, AttributeSet)
3496     */
3497    public View(Context context, AttributeSet attrs, int defStyleAttr) {
3498        this(context);
3499
3500        TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
3501                defStyleAttr, 0);
3502
3503        Drawable background = null;
3504
3505        int leftPadding = -1;
3506        int topPadding = -1;
3507        int rightPadding = -1;
3508        int bottomPadding = -1;
3509        int startPadding = UNDEFINED_PADDING;
3510        int endPadding = UNDEFINED_PADDING;
3511
3512        int padding = -1;
3513
3514        int viewFlagValues = 0;
3515        int viewFlagMasks = 0;
3516
3517        boolean setScrollContainer = false;
3518
3519        int x = 0;
3520        int y = 0;
3521
3522        float tx = 0;
3523        float ty = 0;
3524        float rotation = 0;
3525        float rotationX = 0;
3526        float rotationY = 0;
3527        float sx = 1f;
3528        float sy = 1f;
3529        boolean transformSet = false;
3530
3531        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
3532        int overScrollMode = mOverScrollMode;
3533        boolean initializeScrollbars = false;
3534
3535        boolean leftPaddingDefined = false;
3536        boolean rightPaddingDefined = false;
3537        boolean startPaddingDefined = false;
3538        boolean endPaddingDefined = false;
3539
3540        final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3541
3542        final int N = a.getIndexCount();
3543        for (int i = 0; i < N; i++) {
3544            int attr = a.getIndex(i);
3545            switch (attr) {
3546                case com.android.internal.R.styleable.View_background:
3547                    background = a.getDrawable(attr);
3548                    break;
3549                case com.android.internal.R.styleable.View_padding:
3550                    padding = a.getDimensionPixelSize(attr, -1);
3551                    mUserPaddingLeftInitial = padding;
3552                    mUserPaddingRightInitial = padding;
3553                    leftPaddingDefined = true;
3554                    rightPaddingDefined = true;
3555                    break;
3556                 case com.android.internal.R.styleable.View_paddingLeft:
3557                    leftPadding = a.getDimensionPixelSize(attr, -1);
3558                    mUserPaddingLeftInitial = leftPadding;
3559                    leftPaddingDefined = true;
3560                    break;
3561                case com.android.internal.R.styleable.View_paddingTop:
3562                    topPadding = a.getDimensionPixelSize(attr, -1);
3563                    break;
3564                case com.android.internal.R.styleable.View_paddingRight:
3565                    rightPadding = a.getDimensionPixelSize(attr, -1);
3566                    mUserPaddingRightInitial = rightPadding;
3567                    rightPaddingDefined = true;
3568                    break;
3569                case com.android.internal.R.styleable.View_paddingBottom:
3570                    bottomPadding = a.getDimensionPixelSize(attr, -1);
3571                    break;
3572                case com.android.internal.R.styleable.View_paddingStart:
3573                    startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3574                    startPaddingDefined = (startPadding != UNDEFINED_PADDING);
3575                    break;
3576                case com.android.internal.R.styleable.View_paddingEnd:
3577                    endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3578                    endPaddingDefined = (endPadding != UNDEFINED_PADDING);
3579                    break;
3580                case com.android.internal.R.styleable.View_scrollX:
3581                    x = a.getDimensionPixelOffset(attr, 0);
3582                    break;
3583                case com.android.internal.R.styleable.View_scrollY:
3584                    y = a.getDimensionPixelOffset(attr, 0);
3585                    break;
3586                case com.android.internal.R.styleable.View_alpha:
3587                    setAlpha(a.getFloat(attr, 1f));
3588                    break;
3589                case com.android.internal.R.styleable.View_transformPivotX:
3590                    setPivotX(a.getDimensionPixelOffset(attr, 0));
3591                    break;
3592                case com.android.internal.R.styleable.View_transformPivotY:
3593                    setPivotY(a.getDimensionPixelOffset(attr, 0));
3594                    break;
3595                case com.android.internal.R.styleable.View_translationX:
3596                    tx = a.getDimensionPixelOffset(attr, 0);
3597                    transformSet = true;
3598                    break;
3599                case com.android.internal.R.styleable.View_translationY:
3600                    ty = a.getDimensionPixelOffset(attr, 0);
3601                    transformSet = true;
3602                    break;
3603                case com.android.internal.R.styleable.View_rotation:
3604                    rotation = a.getFloat(attr, 0);
3605                    transformSet = true;
3606                    break;
3607                case com.android.internal.R.styleable.View_rotationX:
3608                    rotationX = a.getFloat(attr, 0);
3609                    transformSet = true;
3610                    break;
3611                case com.android.internal.R.styleable.View_rotationY:
3612                    rotationY = a.getFloat(attr, 0);
3613                    transformSet = true;
3614                    break;
3615                case com.android.internal.R.styleable.View_scaleX:
3616                    sx = a.getFloat(attr, 1f);
3617                    transformSet = true;
3618                    break;
3619                case com.android.internal.R.styleable.View_scaleY:
3620                    sy = a.getFloat(attr, 1f);
3621                    transformSet = true;
3622                    break;
3623                case com.android.internal.R.styleable.View_id:
3624                    mID = a.getResourceId(attr, NO_ID);
3625                    break;
3626                case com.android.internal.R.styleable.View_tag:
3627                    mTag = a.getText(attr);
3628                    break;
3629                case com.android.internal.R.styleable.View_fitsSystemWindows:
3630                    if (a.getBoolean(attr, false)) {
3631                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
3632                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
3633                    }
3634                    break;
3635                case com.android.internal.R.styleable.View_focusable:
3636                    if (a.getBoolean(attr, false)) {
3637                        viewFlagValues |= FOCUSABLE;
3638                        viewFlagMasks |= FOCUSABLE_MASK;
3639                    }
3640                    break;
3641                case com.android.internal.R.styleable.View_focusableInTouchMode:
3642                    if (a.getBoolean(attr, false)) {
3643                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
3644                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
3645                    }
3646                    break;
3647                case com.android.internal.R.styleable.View_clickable:
3648                    if (a.getBoolean(attr, false)) {
3649                        viewFlagValues |= CLICKABLE;
3650                        viewFlagMasks |= CLICKABLE;
3651                    }
3652                    break;
3653                case com.android.internal.R.styleable.View_longClickable:
3654                    if (a.getBoolean(attr, false)) {
3655                        viewFlagValues |= LONG_CLICKABLE;
3656                        viewFlagMasks |= LONG_CLICKABLE;
3657                    }
3658                    break;
3659                case com.android.internal.R.styleable.View_saveEnabled:
3660                    if (!a.getBoolean(attr, true)) {
3661                        viewFlagValues |= SAVE_DISABLED;
3662                        viewFlagMasks |= SAVE_DISABLED_MASK;
3663                    }
3664                    break;
3665                case com.android.internal.R.styleable.View_duplicateParentState:
3666                    if (a.getBoolean(attr, false)) {
3667                        viewFlagValues |= DUPLICATE_PARENT_STATE;
3668                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
3669                    }
3670                    break;
3671                case com.android.internal.R.styleable.View_visibility:
3672                    final int visibility = a.getInt(attr, 0);
3673                    if (visibility != 0) {
3674                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
3675                        viewFlagMasks |= VISIBILITY_MASK;
3676                    }
3677                    break;
3678                case com.android.internal.R.styleable.View_layoutDirection:
3679                    // Clear any layout direction flags (included resolved bits) already set
3680                    mPrivateFlags2 &=
3681                            ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK);
3682                    // Set the layout direction flags depending on the value of the attribute
3683                    final int layoutDirection = a.getInt(attr, -1);
3684                    final int value = (layoutDirection != -1) ?
3685                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
3686                    mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT);
3687                    break;
3688                case com.android.internal.R.styleable.View_drawingCacheQuality:
3689                    final int cacheQuality = a.getInt(attr, 0);
3690                    if (cacheQuality != 0) {
3691                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
3692                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
3693                    }
3694                    break;
3695                case com.android.internal.R.styleable.View_contentDescription:
3696                    setContentDescription(a.getString(attr));
3697                    break;
3698                case com.android.internal.R.styleable.View_labelFor:
3699                    setLabelFor(a.getResourceId(attr, NO_ID));
3700                    break;
3701                case com.android.internal.R.styleable.View_soundEffectsEnabled:
3702                    if (!a.getBoolean(attr, true)) {
3703                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
3704                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
3705                    }
3706                    break;
3707                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
3708                    if (!a.getBoolean(attr, true)) {
3709                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
3710                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
3711                    }
3712                    break;
3713                case R.styleable.View_scrollbars:
3714                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
3715                    if (scrollbars != SCROLLBARS_NONE) {
3716                        viewFlagValues |= scrollbars;
3717                        viewFlagMasks |= SCROLLBARS_MASK;
3718                        initializeScrollbars = true;
3719                    }
3720                    break;
3721                //noinspection deprecation
3722                case R.styleable.View_fadingEdge:
3723                    if (targetSdkVersion >= ICE_CREAM_SANDWICH) {
3724                        // Ignore the attribute starting with ICS
3725                        break;
3726                    }
3727                    // With builds < ICS, fall through and apply fading edges
3728                case R.styleable.View_requiresFadingEdge:
3729                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
3730                    if (fadingEdge != FADING_EDGE_NONE) {
3731                        viewFlagValues |= fadingEdge;
3732                        viewFlagMasks |= FADING_EDGE_MASK;
3733                        initializeFadingEdge(a);
3734                    }
3735                    break;
3736                case R.styleable.View_scrollbarStyle:
3737                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
3738                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3739                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
3740                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
3741                    }
3742                    break;
3743                case R.styleable.View_isScrollContainer:
3744                    setScrollContainer = true;
3745                    if (a.getBoolean(attr, false)) {
3746                        setScrollContainer(true);
3747                    }
3748                    break;
3749                case com.android.internal.R.styleable.View_keepScreenOn:
3750                    if (a.getBoolean(attr, false)) {
3751                        viewFlagValues |= KEEP_SCREEN_ON;
3752                        viewFlagMasks |= KEEP_SCREEN_ON;
3753                    }
3754                    break;
3755                case R.styleable.View_filterTouchesWhenObscured:
3756                    if (a.getBoolean(attr, false)) {
3757                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
3758                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
3759                    }
3760                    break;
3761                case R.styleable.View_nextFocusLeft:
3762                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
3763                    break;
3764                case R.styleable.View_nextFocusRight:
3765                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
3766                    break;
3767                case R.styleable.View_nextFocusUp:
3768                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
3769                    break;
3770                case R.styleable.View_nextFocusDown:
3771                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
3772                    break;
3773                case R.styleable.View_nextFocusForward:
3774                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
3775                    break;
3776                case R.styleable.View_minWidth:
3777                    mMinWidth = a.getDimensionPixelSize(attr, 0);
3778                    break;
3779                case R.styleable.View_minHeight:
3780                    mMinHeight = a.getDimensionPixelSize(attr, 0);
3781                    break;
3782                case R.styleable.View_onClick:
3783                    if (context.isRestricted()) {
3784                        throw new IllegalStateException("The android:onClick attribute cannot "
3785                                + "be used within a restricted context");
3786                    }
3787
3788                    final String handlerName = a.getString(attr);
3789                    if (handlerName != null) {
3790                        setOnClickListener(new OnClickListener() {
3791                            private Method mHandler;
3792
3793                            public void onClick(View v) {
3794                                if (mHandler == null) {
3795                                    try {
3796                                        mHandler = getContext().getClass().getMethod(handlerName,
3797                                                View.class);
3798                                    } catch (NoSuchMethodException e) {
3799                                        int id = getId();
3800                                        String idText = id == NO_ID ? "" : " with id '"
3801                                                + getContext().getResources().getResourceEntryName(
3802                                                    id) + "'";
3803                                        throw new IllegalStateException("Could not find a method " +
3804                                                handlerName + "(View) in the activity "
3805                                                + getContext().getClass() + " for onClick handler"
3806                                                + " on view " + View.this.getClass() + idText, e);
3807                                    }
3808                                }
3809
3810                                try {
3811                                    mHandler.invoke(getContext(), View.this);
3812                                } catch (IllegalAccessException e) {
3813                                    throw new IllegalStateException("Could not execute non "
3814                                            + "public method of the activity", e);
3815                                } catch (InvocationTargetException e) {
3816                                    throw new IllegalStateException("Could not execute "
3817                                            + "method of the activity", e);
3818                                }
3819                            }
3820                        });
3821                    }
3822                    break;
3823                case R.styleable.View_overScrollMode:
3824                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
3825                    break;
3826                case R.styleable.View_verticalScrollbarPosition:
3827                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
3828                    break;
3829                case R.styleable.View_layerType:
3830                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
3831                    break;
3832                case R.styleable.View_textDirection:
3833                    // Clear any text direction flag already set
3834                    mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
3835                    // Set the text direction flags depending on the value of the attribute
3836                    final int textDirection = a.getInt(attr, -1);
3837                    if (textDirection != -1) {
3838                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection];
3839                    }
3840                    break;
3841                case R.styleable.View_textAlignment:
3842                    // Clear any text alignment flag already set
3843                    mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
3844                    // Set the text alignment flag depending on the value of the attribute
3845                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
3846                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment];
3847                    break;
3848                case R.styleable.View_importantForAccessibility:
3849                    setImportantForAccessibility(a.getInt(attr,
3850                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
3851                    break;
3852                case R.styleable.View_accessibilityLiveRegion:
3853                    setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT));
3854                    break;
3855            }
3856        }
3857
3858        setOverScrollMode(overScrollMode);
3859
3860        // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet
3861        // the resolved layout direction). Those cached values will be used later during padding
3862        // resolution.
3863        mUserPaddingStart = startPadding;
3864        mUserPaddingEnd = endPadding;
3865
3866        if (background != null) {
3867            setBackground(background);
3868        }
3869
3870        if (padding >= 0) {
3871            leftPadding = padding;
3872            topPadding = padding;
3873            rightPadding = padding;
3874            bottomPadding = padding;
3875            mUserPaddingLeftInitial = padding;
3876            mUserPaddingRightInitial = padding;
3877        }
3878
3879        if (isRtlCompatibilityMode()) {
3880            // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case.
3881            // left / right padding are used if defined (meaning here nothing to do). If they are not
3882            // defined and start / end padding are defined (e.g. in Frameworks resources), then we use
3883            // start / end and resolve them as left / right (layout direction is not taken into account).
3884            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
3885            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
3886            // defined.
3887            if (!leftPaddingDefined && startPaddingDefined) {
3888                leftPadding = startPadding;
3889            }
3890            mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial;
3891            if (!rightPaddingDefined && endPaddingDefined) {
3892                rightPadding = endPadding;
3893            }
3894            mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial;
3895        } else {
3896            // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right
3897            // values defined. Otherwise, left /right values are used.
3898            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
3899            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
3900            // defined.
3901            final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined;
3902
3903            if (leftPaddingDefined && !hasRelativePadding) {
3904                mUserPaddingLeftInitial = leftPadding;
3905            }
3906            if (rightPaddingDefined && !hasRelativePadding) {
3907                mUserPaddingRightInitial = rightPadding;
3908            }
3909        }
3910
3911        internalSetPadding(
3912                mUserPaddingLeftInitial,
3913                topPadding >= 0 ? topPadding : mPaddingTop,
3914                mUserPaddingRightInitial,
3915                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
3916
3917        if (viewFlagMasks != 0) {
3918            setFlags(viewFlagValues, viewFlagMasks);
3919        }
3920
3921        if (initializeScrollbars) {
3922            initializeScrollbars(a);
3923        }
3924
3925        a.recycle();
3926
3927        // Needs to be called after mViewFlags is set
3928        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3929            recomputePadding();
3930        }
3931
3932        if (x != 0 || y != 0) {
3933            scrollTo(x, y);
3934        }
3935
3936        if (transformSet) {
3937            setTranslationX(tx);
3938            setTranslationY(ty);
3939            setRotation(rotation);
3940            setRotationX(rotationX);
3941            setRotationY(rotationY);
3942            setScaleX(sx);
3943            setScaleY(sy);
3944        }
3945
3946        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
3947            setScrollContainer(true);
3948        }
3949
3950        computeOpaqueFlags();
3951    }
3952
3953    /**
3954     * Non-public constructor for use in testing
3955     */
3956    View() {
3957        mResources = null;
3958    }
3959
3960    public String toString() {
3961        StringBuilder out = new StringBuilder(128);
3962        out.append(getClass().getName());
3963        out.append('{');
3964        out.append(Integer.toHexString(System.identityHashCode(this)));
3965        out.append(' ');
3966        switch (mViewFlags&VISIBILITY_MASK) {
3967            case VISIBLE: out.append('V'); break;
3968            case INVISIBLE: out.append('I'); break;
3969            case GONE: out.append('G'); break;
3970            default: out.append('.'); break;
3971        }
3972        out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.');
3973        out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.');
3974        out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D');
3975        out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.');
3976        out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.');
3977        out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.');
3978        out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.');
3979        out.append(' ');
3980        out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.');
3981        out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.');
3982        out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.');
3983        if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) {
3984            out.append('p');
3985        } else {
3986            out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.');
3987        }
3988        out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.');
3989        out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.');
3990        out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.');
3991        out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.');
3992        out.append(' ');
3993        out.append(mLeft);
3994        out.append(',');
3995        out.append(mTop);
3996        out.append('-');
3997        out.append(mRight);
3998        out.append(',');
3999        out.append(mBottom);
4000        final int id = getId();
4001        if (id != NO_ID) {
4002            out.append(" #");
4003            out.append(Integer.toHexString(id));
4004            final Resources r = mResources;
4005            if (id != 0 && r != null) {
4006                try {
4007                    String pkgname;
4008                    switch (id&0xff000000) {
4009                        case 0x7f000000:
4010                            pkgname="app";
4011                            break;
4012                        case 0x01000000:
4013                            pkgname="android";
4014                            break;
4015                        default:
4016                            pkgname = r.getResourcePackageName(id);
4017                            break;
4018                    }
4019                    String typename = r.getResourceTypeName(id);
4020                    String entryname = r.getResourceEntryName(id);
4021                    out.append(" ");
4022                    out.append(pkgname);
4023                    out.append(":");
4024                    out.append(typename);
4025                    out.append("/");
4026                    out.append(entryname);
4027                } catch (Resources.NotFoundException e) {
4028                }
4029            }
4030        }
4031        out.append("}");
4032        return out.toString();
4033    }
4034
4035    /**
4036     * <p>
4037     * Initializes the fading edges from a given set of styled attributes. This
4038     * method should be called by subclasses that need fading edges and when an
4039     * instance of these subclasses is created programmatically rather than
4040     * being inflated from XML. This method is automatically called when the XML
4041     * is inflated.
4042     * </p>
4043     *
4044     * @param a the styled attributes set to initialize the fading edges from
4045     */
4046    protected void initializeFadingEdge(TypedArray a) {
4047        initScrollCache();
4048
4049        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
4050                R.styleable.View_fadingEdgeLength,
4051                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
4052    }
4053
4054    /**
4055     * Returns the size of the vertical faded edges used to indicate that more
4056     * content in this view is visible.
4057     *
4058     * @return The size in pixels of the vertical faded edge or 0 if vertical
4059     *         faded edges are not enabled for this view.
4060     * @attr ref android.R.styleable#View_fadingEdgeLength
4061     */
4062    public int getVerticalFadingEdgeLength() {
4063        if (isVerticalFadingEdgeEnabled()) {
4064            ScrollabilityCache cache = mScrollCache;
4065            if (cache != null) {
4066                return cache.fadingEdgeLength;
4067            }
4068        }
4069        return 0;
4070    }
4071
4072    /**
4073     * Set the size of the faded edge used to indicate that more content in this
4074     * view is available.  Will not change whether the fading edge is enabled; use
4075     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
4076     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
4077     * for the vertical or horizontal fading edges.
4078     *
4079     * @param length The size in pixels of the faded edge used to indicate that more
4080     *        content in this view is visible.
4081     */
4082    public void setFadingEdgeLength(int length) {
4083        initScrollCache();
4084        mScrollCache.fadingEdgeLength = length;
4085    }
4086
4087    /**
4088     * Returns the size of the horizontal faded edges used to indicate that more
4089     * content in this view is visible.
4090     *
4091     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
4092     *         faded edges are not enabled for this view.
4093     * @attr ref android.R.styleable#View_fadingEdgeLength
4094     */
4095    public int getHorizontalFadingEdgeLength() {
4096        if (isHorizontalFadingEdgeEnabled()) {
4097            ScrollabilityCache cache = mScrollCache;
4098            if (cache != null) {
4099                return cache.fadingEdgeLength;
4100            }
4101        }
4102        return 0;
4103    }
4104
4105    /**
4106     * Returns the width of the vertical scrollbar.
4107     *
4108     * @return The width in pixels of the vertical scrollbar or 0 if there
4109     *         is no vertical scrollbar.
4110     */
4111    public int getVerticalScrollbarWidth() {
4112        ScrollabilityCache cache = mScrollCache;
4113        if (cache != null) {
4114            ScrollBarDrawable scrollBar = cache.scrollBar;
4115            if (scrollBar != null) {
4116                int size = scrollBar.getSize(true);
4117                if (size <= 0) {
4118                    size = cache.scrollBarSize;
4119                }
4120                return size;
4121            }
4122            return 0;
4123        }
4124        return 0;
4125    }
4126
4127    /**
4128     * Returns the height of the horizontal scrollbar.
4129     *
4130     * @return The height in pixels of the horizontal scrollbar or 0 if
4131     *         there is no horizontal scrollbar.
4132     */
4133    protected int getHorizontalScrollbarHeight() {
4134        ScrollabilityCache cache = mScrollCache;
4135        if (cache != null) {
4136            ScrollBarDrawable scrollBar = cache.scrollBar;
4137            if (scrollBar != null) {
4138                int size = scrollBar.getSize(false);
4139                if (size <= 0) {
4140                    size = cache.scrollBarSize;
4141                }
4142                return size;
4143            }
4144            return 0;
4145        }
4146        return 0;
4147    }
4148
4149    /**
4150     * <p>
4151     * Initializes the scrollbars from a given set of styled attributes. This
4152     * method should be called by subclasses that need scrollbars and when an
4153     * instance of these subclasses is created programmatically rather than
4154     * being inflated from XML. This method is automatically called when the XML
4155     * is inflated.
4156     * </p>
4157     *
4158     * @param a the styled attributes set to initialize the scrollbars from
4159     */
4160    protected void initializeScrollbars(TypedArray a) {
4161        initScrollCache();
4162
4163        final ScrollabilityCache scrollabilityCache = mScrollCache;
4164
4165        if (scrollabilityCache.scrollBar == null) {
4166            scrollabilityCache.scrollBar = new ScrollBarDrawable();
4167        }
4168
4169        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
4170
4171        if (!fadeScrollbars) {
4172            scrollabilityCache.state = ScrollabilityCache.ON;
4173        }
4174        scrollabilityCache.fadeScrollBars = fadeScrollbars;
4175
4176
4177        scrollabilityCache.scrollBarFadeDuration = a.getInt(
4178                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
4179                        .getScrollBarFadeDuration());
4180        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
4181                R.styleable.View_scrollbarDefaultDelayBeforeFade,
4182                ViewConfiguration.getScrollDefaultDelay());
4183
4184
4185        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
4186                com.android.internal.R.styleable.View_scrollbarSize,
4187                ViewConfiguration.get(mContext).getScaledScrollBarSize());
4188
4189        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
4190        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
4191
4192        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
4193        if (thumb != null) {
4194            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
4195        }
4196
4197        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
4198                false);
4199        if (alwaysDraw) {
4200            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
4201        }
4202
4203        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
4204        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
4205
4206        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
4207        if (thumb != null) {
4208            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
4209        }
4210
4211        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
4212                false);
4213        if (alwaysDraw) {
4214            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
4215        }
4216
4217        // Apply layout direction to the new Drawables if needed
4218        final int layoutDirection = getLayoutDirection();
4219        if (track != null) {
4220            track.setLayoutDirection(layoutDirection);
4221        }
4222        if (thumb != null) {
4223            thumb.setLayoutDirection(layoutDirection);
4224        }
4225
4226        // Re-apply user/background padding so that scrollbar(s) get added
4227        resolvePadding();
4228    }
4229
4230    /**
4231     * <p>
4232     * Initalizes the scrollability cache if necessary.
4233     * </p>
4234     */
4235    private void initScrollCache() {
4236        if (mScrollCache == null) {
4237            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
4238        }
4239    }
4240
4241    private ScrollabilityCache getScrollCache() {
4242        initScrollCache();
4243        return mScrollCache;
4244    }
4245
4246    /**
4247     * Set the position of the vertical scroll bar. Should be one of
4248     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
4249     * {@link #SCROLLBAR_POSITION_RIGHT}.
4250     *
4251     * @param position Where the vertical scroll bar should be positioned.
4252     */
4253    public void setVerticalScrollbarPosition(int position) {
4254        if (mVerticalScrollbarPosition != position) {
4255            mVerticalScrollbarPosition = position;
4256            computeOpaqueFlags();
4257            resolvePadding();
4258        }
4259    }
4260
4261    /**
4262     * @return The position where the vertical scroll bar will show, if applicable.
4263     * @see #setVerticalScrollbarPosition(int)
4264     */
4265    public int getVerticalScrollbarPosition() {
4266        return mVerticalScrollbarPosition;
4267    }
4268
4269    ListenerInfo getListenerInfo() {
4270        if (mListenerInfo != null) {
4271            return mListenerInfo;
4272        }
4273        mListenerInfo = new ListenerInfo();
4274        return mListenerInfo;
4275    }
4276
4277    /**
4278     * Register a callback to be invoked when focus of this view changed.
4279     *
4280     * @param l The callback that will run.
4281     */
4282    public void setOnFocusChangeListener(OnFocusChangeListener l) {
4283        getListenerInfo().mOnFocusChangeListener = l;
4284    }
4285
4286    /**
4287     * Add a listener that will be called when the bounds of the view change due to
4288     * layout processing.
4289     *
4290     * @param listener The listener that will be called when layout bounds change.
4291     */
4292    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
4293        ListenerInfo li = getListenerInfo();
4294        if (li.mOnLayoutChangeListeners == null) {
4295            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
4296        }
4297        if (!li.mOnLayoutChangeListeners.contains(listener)) {
4298            li.mOnLayoutChangeListeners.add(listener);
4299        }
4300    }
4301
4302    /**
4303     * Remove a listener for layout changes.
4304     *
4305     * @param listener The listener for layout bounds change.
4306     */
4307    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
4308        ListenerInfo li = mListenerInfo;
4309        if (li == null || li.mOnLayoutChangeListeners == null) {
4310            return;
4311        }
4312        li.mOnLayoutChangeListeners.remove(listener);
4313    }
4314
4315    /**
4316     * Add a listener for attach state changes.
4317     *
4318     * This listener will be called whenever this view is attached or detached
4319     * from a window. Remove the listener using
4320     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
4321     *
4322     * @param listener Listener to attach
4323     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
4324     */
4325    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4326        ListenerInfo li = getListenerInfo();
4327        if (li.mOnAttachStateChangeListeners == null) {
4328            li.mOnAttachStateChangeListeners
4329                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
4330        }
4331        li.mOnAttachStateChangeListeners.add(listener);
4332    }
4333
4334    /**
4335     * Remove a listener for attach state changes. The listener will receive no further
4336     * notification of window attach/detach events.
4337     *
4338     * @param listener Listener to remove
4339     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
4340     */
4341    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4342        ListenerInfo li = mListenerInfo;
4343        if (li == null || li.mOnAttachStateChangeListeners == null) {
4344            return;
4345        }
4346        li.mOnAttachStateChangeListeners.remove(listener);
4347    }
4348
4349    /**
4350     * Returns the focus-change callback registered for this view.
4351     *
4352     * @return The callback, or null if one is not registered.
4353     */
4354    public OnFocusChangeListener getOnFocusChangeListener() {
4355        ListenerInfo li = mListenerInfo;
4356        return li != null ? li.mOnFocusChangeListener : null;
4357    }
4358
4359    /**
4360     * Register a callback to be invoked when this view is clicked. If this view is not
4361     * clickable, it becomes clickable.
4362     *
4363     * @param l The callback that will run
4364     *
4365     * @see #setClickable(boolean)
4366     */
4367    public void setOnClickListener(OnClickListener l) {
4368        if (!isClickable()) {
4369            setClickable(true);
4370        }
4371        getListenerInfo().mOnClickListener = l;
4372    }
4373
4374    /**
4375     * Return whether this view has an attached OnClickListener.  Returns
4376     * true if there is a listener, false if there is none.
4377     */
4378    public boolean hasOnClickListeners() {
4379        ListenerInfo li = mListenerInfo;
4380        return (li != null && li.mOnClickListener != null);
4381    }
4382
4383    /**
4384     * Register a callback to be invoked when this view is clicked and held. If this view is not
4385     * long clickable, it becomes long clickable.
4386     *
4387     * @param l The callback that will run
4388     *
4389     * @see #setLongClickable(boolean)
4390     */
4391    public void setOnLongClickListener(OnLongClickListener l) {
4392        if (!isLongClickable()) {
4393            setLongClickable(true);
4394        }
4395        getListenerInfo().mOnLongClickListener = l;
4396    }
4397
4398    /**
4399     * Register a callback to be invoked when the context menu for this view is
4400     * being built. If this view is not long clickable, it becomes long clickable.
4401     *
4402     * @param l The callback that will run
4403     *
4404     */
4405    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
4406        if (!isLongClickable()) {
4407            setLongClickable(true);
4408        }
4409        getListenerInfo().mOnCreateContextMenuListener = l;
4410    }
4411
4412    /**
4413     * Call this view's OnClickListener, if it is defined.  Performs all normal
4414     * actions associated with clicking: reporting accessibility event, playing
4415     * a sound, etc.
4416     *
4417     * @return True there was an assigned OnClickListener that was called, false
4418     *         otherwise is returned.
4419     */
4420    public boolean performClick() {
4421        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
4422
4423        ListenerInfo li = mListenerInfo;
4424        if (li != null && li.mOnClickListener != null) {
4425            playSoundEffect(SoundEffectConstants.CLICK);
4426            li.mOnClickListener.onClick(this);
4427            return true;
4428        }
4429
4430        return false;
4431    }
4432
4433    /**
4434     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
4435     * this only calls the listener, and does not do any associated clicking
4436     * actions like reporting an accessibility event.
4437     *
4438     * @return True there was an assigned OnClickListener that was called, false
4439     *         otherwise is returned.
4440     */
4441    public boolean callOnClick() {
4442        ListenerInfo li = mListenerInfo;
4443        if (li != null && li.mOnClickListener != null) {
4444            li.mOnClickListener.onClick(this);
4445            return true;
4446        }
4447        return false;
4448    }
4449
4450    /**
4451     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
4452     * OnLongClickListener did not consume the event.
4453     *
4454     * @return True if one of the above receivers consumed the event, false otherwise.
4455     */
4456    public boolean performLongClick() {
4457        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
4458
4459        boolean handled = false;
4460        ListenerInfo li = mListenerInfo;
4461        if (li != null && li.mOnLongClickListener != null) {
4462            handled = li.mOnLongClickListener.onLongClick(View.this);
4463        }
4464        if (!handled) {
4465            handled = showContextMenu();
4466        }
4467        if (handled) {
4468            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
4469        }
4470        return handled;
4471    }
4472
4473    /**
4474     * Performs button-related actions during a touch down event.
4475     *
4476     * @param event The event.
4477     * @return True if the down was consumed.
4478     *
4479     * @hide
4480     */
4481    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
4482        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
4483            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
4484                return true;
4485            }
4486        }
4487        return false;
4488    }
4489
4490    /**
4491     * Bring up the context menu for this view.
4492     *
4493     * @return Whether a context menu was displayed.
4494     */
4495    public boolean showContextMenu() {
4496        return getParent().showContextMenuForChild(this);
4497    }
4498
4499    /**
4500     * Bring up the context menu for this view, referring to the item under the specified point.
4501     *
4502     * @param x The referenced x coordinate.
4503     * @param y The referenced y coordinate.
4504     * @param metaState The keyboard modifiers that were pressed.
4505     * @return Whether a context menu was displayed.
4506     *
4507     * @hide
4508     */
4509    public boolean showContextMenu(float x, float y, int metaState) {
4510        return showContextMenu();
4511    }
4512
4513    /**
4514     * Start an action mode.
4515     *
4516     * @param callback Callback that will control the lifecycle of the action mode
4517     * @return The new action mode if it is started, null otherwise
4518     *
4519     * @see ActionMode
4520     */
4521    public ActionMode startActionMode(ActionMode.Callback callback) {
4522        ViewParent parent = getParent();
4523        if (parent == null) return null;
4524        return parent.startActionModeForChild(this, callback);
4525    }
4526
4527    /**
4528     * Register a callback to be invoked when a hardware key is pressed in this view.
4529     * Key presses in software input methods will generally not trigger the methods of
4530     * this listener.
4531     * @param l the key listener to attach to this view
4532     */
4533    public void setOnKeyListener(OnKeyListener l) {
4534        getListenerInfo().mOnKeyListener = l;
4535    }
4536
4537    /**
4538     * Register a callback to be invoked when a touch event is sent to this view.
4539     * @param l the touch listener to attach to this view
4540     */
4541    public void setOnTouchListener(OnTouchListener l) {
4542        getListenerInfo().mOnTouchListener = l;
4543    }
4544
4545    /**
4546     * Register a callback to be invoked when a generic motion event is sent to this view.
4547     * @param l the generic motion listener to attach to this view
4548     */
4549    public void setOnGenericMotionListener(OnGenericMotionListener l) {
4550        getListenerInfo().mOnGenericMotionListener = l;
4551    }
4552
4553    /**
4554     * Register a callback to be invoked when a hover event is sent to this view.
4555     * @param l the hover listener to attach to this view
4556     */
4557    public void setOnHoverListener(OnHoverListener l) {
4558        getListenerInfo().mOnHoverListener = l;
4559    }
4560
4561    /**
4562     * Register a drag event listener callback object for this View. The parameter is
4563     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
4564     * View, the system calls the
4565     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
4566     * @param l An implementation of {@link android.view.View.OnDragListener}.
4567     */
4568    public void setOnDragListener(OnDragListener l) {
4569        getListenerInfo().mOnDragListener = l;
4570    }
4571
4572    /**
4573     * Give this view focus. This will cause
4574     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
4575     *
4576     * Note: this does not check whether this {@link View} should get focus, it just
4577     * gives it focus no matter what.  It should only be called internally by framework
4578     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
4579     *
4580     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
4581     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
4582     *        focus moved when requestFocus() is called. It may not always
4583     *        apply, in which case use the default View.FOCUS_DOWN.
4584     * @param previouslyFocusedRect The rectangle of the view that had focus
4585     *        prior in this View's coordinate system.
4586     */
4587    void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
4588        if (DBG) {
4589            System.out.println(this + " requestFocus()");
4590        }
4591
4592        if ((mPrivateFlags & PFLAG_FOCUSED) == 0) {
4593            mPrivateFlags |= PFLAG_FOCUSED;
4594
4595            View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null;
4596
4597            if (mParent != null) {
4598                mParent.requestChildFocus(this, this);
4599            }
4600
4601            if (mAttachInfo != null) {
4602                mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this);
4603            }
4604
4605            onFocusChanged(true, direction, previouslyFocusedRect);
4606            refreshDrawableState();
4607        }
4608    }
4609
4610    /**
4611     * Request that a rectangle of this view be visible on the screen,
4612     * scrolling if necessary just enough.
4613     *
4614     * <p>A View should call this if it maintains some notion of which part
4615     * of its content is interesting.  For example, a text editing view
4616     * should call this when its cursor moves.
4617     *
4618     * @param rectangle The rectangle.
4619     * @return Whether any parent scrolled.
4620     */
4621    public boolean requestRectangleOnScreen(Rect rectangle) {
4622        return requestRectangleOnScreen(rectangle, false);
4623    }
4624
4625    /**
4626     * Request that a rectangle of this view be visible on the screen,
4627     * scrolling if necessary just enough.
4628     *
4629     * <p>A View should call this if it maintains some notion of which part
4630     * of its content is interesting.  For example, a text editing view
4631     * should call this when its cursor moves.
4632     *
4633     * <p>When <code>immediate</code> is set to true, scrolling will not be
4634     * animated.
4635     *
4636     * @param rectangle The rectangle.
4637     * @param immediate True to forbid animated scrolling, false otherwise
4638     * @return Whether any parent scrolled.
4639     */
4640    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
4641        if (mParent == null) {
4642            return false;
4643        }
4644
4645        View child = this;
4646
4647        RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF();
4648        position.set(rectangle);
4649
4650        ViewParent parent = mParent;
4651        boolean scrolled = false;
4652        while (parent != null) {
4653            rectangle.set((int) position.left, (int) position.top,
4654                    (int) position.right, (int) position.bottom);
4655
4656            scrolled |= parent.requestChildRectangleOnScreen(child,
4657                    rectangle, immediate);
4658
4659            if (!child.hasIdentityMatrix()) {
4660                child.getMatrix().mapRect(position);
4661            }
4662
4663            position.offset(child.mLeft, child.mTop);
4664
4665            if (!(parent instanceof View)) {
4666                break;
4667            }
4668
4669            View parentView = (View) parent;
4670
4671            position.offset(-parentView.getScrollX(), -parentView.getScrollY());
4672
4673            child = parentView;
4674            parent = child.getParent();
4675        }
4676
4677        return scrolled;
4678    }
4679
4680    /**
4681     * Called when this view wants to give up focus. If focus is cleared
4682     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
4683     * <p>
4684     * <strong>Note:</strong> When a View clears focus the framework is trying
4685     * to give focus to the first focusable View from the top. Hence, if this
4686     * View is the first from the top that can take focus, then all callbacks
4687     * related to clearing focus will be invoked after wich the framework will
4688     * give focus to this view.
4689     * </p>
4690     */
4691    public void clearFocus() {
4692        if (DBG) {
4693            System.out.println(this + " clearFocus()");
4694        }
4695
4696        clearFocusInternal(true, true);
4697    }
4698
4699    /**
4700     * Clears focus from the view, optionally propagating the change up through
4701     * the parent hierarchy and requesting that the root view place new focus.
4702     *
4703     * @param propagate whether to propagate the change up through the parent
4704     *            hierarchy
4705     * @param refocus when propagate is true, specifies whether to request the
4706     *            root view place new focus
4707     */
4708    void clearFocusInternal(boolean propagate, boolean refocus) {
4709        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
4710            mPrivateFlags &= ~PFLAG_FOCUSED;
4711
4712            if (propagate && mParent != null) {
4713                mParent.clearChildFocus(this);
4714            }
4715
4716            onFocusChanged(false, 0, null);
4717
4718            refreshDrawableState();
4719
4720            if (propagate && (!refocus || !rootViewRequestFocus())) {
4721                notifyGlobalFocusCleared(this);
4722            }
4723        }
4724    }
4725
4726    void notifyGlobalFocusCleared(View oldFocus) {
4727        if (oldFocus != null && mAttachInfo != null) {
4728            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
4729        }
4730    }
4731
4732    boolean rootViewRequestFocus() {
4733        final View root = getRootView();
4734        return root != null && root.requestFocus();
4735    }
4736
4737    /**
4738     * Called internally by the view system when a new view is getting focus.
4739     * This is what clears the old focus.
4740     * <p>
4741     * <b>NOTE:</b> The parent view's focused child must be updated manually
4742     * after calling this method. Otherwise, the view hierarchy may be left in
4743     * an inconstent state.
4744     */
4745    void unFocus() {
4746        if (DBG) {
4747            System.out.println(this + " unFocus()");
4748        }
4749
4750        clearFocusInternal(false, false);
4751    }
4752
4753    /**
4754     * Returns true if this view has focus iteself, or is the ancestor of the
4755     * view that has focus.
4756     *
4757     * @return True if this view has or contains focus, false otherwise.
4758     */
4759    @ViewDebug.ExportedProperty(category = "focus")
4760    public boolean hasFocus() {
4761        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
4762    }
4763
4764    /**
4765     * Returns true if this view is focusable or if it contains a reachable View
4766     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
4767     * is a View whose parents do not block descendants focus.
4768     *
4769     * Only {@link #VISIBLE} views are considered focusable.
4770     *
4771     * @return True if the view is focusable or if the view contains a focusable
4772     *         View, false otherwise.
4773     *
4774     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
4775     */
4776    public boolean hasFocusable() {
4777        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
4778    }
4779
4780    /**
4781     * Called by the view system when the focus state of this view changes.
4782     * When the focus change event is caused by directional navigation, direction
4783     * and previouslyFocusedRect provide insight into where the focus is coming from.
4784     * When overriding, be sure to call up through to the super class so that
4785     * the standard focus handling will occur.
4786     *
4787     * @param gainFocus True if the View has focus; false otherwise.
4788     * @param direction The direction focus has moved when requestFocus()
4789     *                  is called to give this view focus. Values are
4790     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
4791     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
4792     *                  It may not always apply, in which case use the default.
4793     * @param previouslyFocusedRect The rectangle, in this view's coordinate
4794     *        system, of the previously focused view.  If applicable, this will be
4795     *        passed in as finer grained information about where the focus is coming
4796     *        from (in addition to direction).  Will be <code>null</code> otherwise.
4797     */
4798    protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
4799        if (gainFocus) {
4800            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
4801        } else {
4802            notifyViewAccessibilityStateChangedIfNeeded(
4803                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
4804        }
4805
4806        InputMethodManager imm = InputMethodManager.peekInstance();
4807        if (!gainFocus) {
4808            if (isPressed()) {
4809                setPressed(false);
4810            }
4811            if (imm != null && mAttachInfo != null
4812                    && mAttachInfo.mHasWindowFocus) {
4813                imm.focusOut(this);
4814            }
4815            onFocusLost();
4816        } else if (imm != null && mAttachInfo != null
4817                && mAttachInfo.mHasWindowFocus) {
4818            imm.focusIn(this);
4819        }
4820
4821        invalidate(true);
4822        ListenerInfo li = mListenerInfo;
4823        if (li != null && li.mOnFocusChangeListener != null) {
4824            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
4825        }
4826
4827        if (mAttachInfo != null) {
4828            mAttachInfo.mKeyDispatchState.reset(this);
4829        }
4830    }
4831
4832    /**
4833     * Sends an accessibility event of the given type. If accessibility is
4834     * not enabled this method has no effect. The default implementation calls
4835     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
4836     * to populate information about the event source (this View), then calls
4837     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
4838     * populate the text content of the event source including its descendants,
4839     * and last calls
4840     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
4841     * on its parent to resuest sending of the event to interested parties.
4842     * <p>
4843     * If an {@link AccessibilityDelegate} has been specified via calling
4844     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4845     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
4846     * responsible for handling this call.
4847     * </p>
4848     *
4849     * @param eventType The type of the event to send, as defined by several types from
4850     * {@link android.view.accessibility.AccessibilityEvent}, such as
4851     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
4852     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
4853     *
4854     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4855     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4856     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
4857     * @see AccessibilityDelegate
4858     */
4859    public void sendAccessibilityEvent(int eventType) {
4860        // Excluded views do not send accessibility events.
4861        if (!includeForAccessibility()) {
4862            return;
4863        }
4864        if (mAccessibilityDelegate != null) {
4865            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
4866        } else {
4867            sendAccessibilityEventInternal(eventType);
4868        }
4869    }
4870
4871    /**
4872     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
4873     * {@link AccessibilityEvent} to make an announcement which is related to some
4874     * sort of a context change for which none of the events representing UI transitions
4875     * is a good fit. For example, announcing a new page in a book. If accessibility
4876     * is not enabled this method does nothing.
4877     *
4878     * @param text The announcement text.
4879     */
4880    public void announceForAccessibility(CharSequence text) {
4881        if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) {
4882            AccessibilityEvent event = AccessibilityEvent.obtain(
4883                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
4884            onInitializeAccessibilityEvent(event);
4885            event.getText().add(text);
4886            event.setContentDescription(null);
4887            mParent.requestSendAccessibilityEvent(this, event);
4888        }
4889    }
4890
4891    /**
4892     * @see #sendAccessibilityEvent(int)
4893     *
4894     * Note: Called from the default {@link AccessibilityDelegate}.
4895     */
4896    void sendAccessibilityEventInternal(int eventType) {
4897        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4898            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
4899        }
4900    }
4901
4902    /**
4903     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
4904     * takes as an argument an empty {@link AccessibilityEvent} and does not
4905     * perform a check whether accessibility is enabled.
4906     * <p>
4907     * If an {@link AccessibilityDelegate} has been specified via calling
4908     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4909     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
4910     * is responsible for handling this call.
4911     * </p>
4912     *
4913     * @param event The event to send.
4914     *
4915     * @see #sendAccessibilityEvent(int)
4916     */
4917    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
4918        if (mAccessibilityDelegate != null) {
4919            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
4920        } else {
4921            sendAccessibilityEventUncheckedInternal(event);
4922        }
4923    }
4924
4925    /**
4926     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
4927     *
4928     * Note: Called from the default {@link AccessibilityDelegate}.
4929     */
4930    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
4931        if (!isShown()) {
4932            return;
4933        }
4934        onInitializeAccessibilityEvent(event);
4935        // Only a subset of accessibility events populates text content.
4936        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
4937            dispatchPopulateAccessibilityEvent(event);
4938        }
4939        // In the beginning we called #isShown(), so we know that getParent() is not null.
4940        getParent().requestSendAccessibilityEvent(this, event);
4941    }
4942
4943    /**
4944     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
4945     * to its children for adding their text content to the event. Note that the
4946     * event text is populated in a separate dispatch path since we add to the
4947     * event not only the text of the source but also the text of all its descendants.
4948     * A typical implementation will call
4949     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
4950     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4951     * on each child. Override this method if custom population of the event text
4952     * content is required.
4953     * <p>
4954     * If an {@link AccessibilityDelegate} has been specified via calling
4955     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4956     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
4957     * is responsible for handling this call.
4958     * </p>
4959     * <p>
4960     * <em>Note:</em> Accessibility events of certain types are not dispatched for
4961     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
4962     * </p>
4963     *
4964     * @param event The event.
4965     *
4966     * @return True if the event population was completed.
4967     */
4968    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
4969        if (mAccessibilityDelegate != null) {
4970            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
4971        } else {
4972            return dispatchPopulateAccessibilityEventInternal(event);
4973        }
4974    }
4975
4976    /**
4977     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4978     *
4979     * Note: Called from the default {@link AccessibilityDelegate}.
4980     */
4981    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4982        onPopulateAccessibilityEvent(event);
4983        return false;
4984    }
4985
4986    /**
4987     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4988     * giving a chance to this View to populate the accessibility event with its
4989     * text content. While this method is free to modify event
4990     * attributes other than text content, doing so should normally be performed in
4991     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
4992     * <p>
4993     * Example: Adding formatted date string to an accessibility event in addition
4994     *          to the text added by the super implementation:
4995     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4996     *     super.onPopulateAccessibilityEvent(event);
4997     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
4998     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
4999     *         mCurrentDate.getTimeInMillis(), flags);
5000     *     event.getText().add(selectedDateUtterance);
5001     * }</pre>
5002     * <p>
5003     * If an {@link AccessibilityDelegate} has been specified via calling
5004     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5005     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
5006     * is responsible for handling this call.
5007     * </p>
5008     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
5009     * information to the event, in case the default implementation has basic information to add.
5010     * </p>
5011     *
5012     * @param event The accessibility event which to populate.
5013     *
5014     * @see #sendAccessibilityEvent(int)
5015     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5016     */
5017    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
5018        if (mAccessibilityDelegate != null) {
5019            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
5020        } else {
5021            onPopulateAccessibilityEventInternal(event);
5022        }
5023    }
5024
5025    /**
5026     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
5027     *
5028     * Note: Called from the default {@link AccessibilityDelegate}.
5029     */
5030    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
5031    }
5032
5033    /**
5034     * Initializes an {@link AccessibilityEvent} with information about
5035     * this View which is the event source. In other words, the source of
5036     * an accessibility event is the view whose state change triggered firing
5037     * the event.
5038     * <p>
5039     * Example: Setting the password property of an event in addition
5040     *          to properties set by the super implementation:
5041     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
5042     *     super.onInitializeAccessibilityEvent(event);
5043     *     event.setPassword(true);
5044     * }</pre>
5045     * <p>
5046     * If an {@link AccessibilityDelegate} has been specified via calling
5047     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5048     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
5049     * is responsible for handling this call.
5050     * </p>
5051     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
5052     * information to the event, in case the default implementation has basic information to add.
5053     * </p>
5054     * @param event The event to initialize.
5055     *
5056     * @see #sendAccessibilityEvent(int)
5057     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5058     */
5059    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
5060        if (mAccessibilityDelegate != null) {
5061            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
5062        } else {
5063            onInitializeAccessibilityEventInternal(event);
5064        }
5065    }
5066
5067    /**
5068     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
5069     *
5070     * Note: Called from the default {@link AccessibilityDelegate}.
5071     */
5072    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
5073        event.setSource(this);
5074        event.setClassName(View.class.getName());
5075        event.setPackageName(getContext().getPackageName());
5076        event.setEnabled(isEnabled());
5077        event.setContentDescription(mContentDescription);
5078
5079        switch (event.getEventType()) {
5080            case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
5081                ArrayList<View> focusablesTempList = (mAttachInfo != null)
5082                        ? mAttachInfo.mTempArrayList : new ArrayList<View>();
5083                getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
5084                event.setItemCount(focusablesTempList.size());
5085                event.setCurrentItemIndex(focusablesTempList.indexOf(this));
5086                if (mAttachInfo != null) {
5087                    focusablesTempList.clear();
5088                }
5089            } break;
5090            case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: {
5091                CharSequence text = getIterableTextForAccessibility();
5092                if (text != null && text.length() > 0) {
5093                    event.setFromIndex(getAccessibilitySelectionStart());
5094                    event.setToIndex(getAccessibilitySelectionEnd());
5095                    event.setItemCount(text.length());
5096                }
5097            } break;
5098        }
5099    }
5100
5101    /**
5102     * Returns an {@link AccessibilityNodeInfo} representing this view from the
5103     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
5104     * This method is responsible for obtaining an accessibility node info from a
5105     * pool of reusable instances and calling
5106     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
5107     * initialize the former.
5108     * <p>
5109     * Note: The client is responsible for recycling the obtained instance by calling
5110     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
5111     * </p>
5112     *
5113     * @return A populated {@link AccessibilityNodeInfo}.
5114     *
5115     * @see AccessibilityNodeInfo
5116     */
5117    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
5118        if (mAccessibilityDelegate != null) {
5119            return mAccessibilityDelegate.createAccessibilityNodeInfo(this);
5120        } else {
5121            return createAccessibilityNodeInfoInternal();
5122        }
5123    }
5124
5125    /**
5126     * @see #createAccessibilityNodeInfo()
5127     */
5128    AccessibilityNodeInfo createAccessibilityNodeInfoInternal() {
5129        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
5130        if (provider != null) {
5131            return provider.createAccessibilityNodeInfo(View.NO_ID);
5132        } else {
5133            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
5134            onInitializeAccessibilityNodeInfo(info);
5135            return info;
5136        }
5137    }
5138
5139    /**
5140     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
5141     * The base implementation sets:
5142     * <ul>
5143     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
5144     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
5145     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
5146     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
5147     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
5148     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
5149     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
5150     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
5151     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
5152     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
5153     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
5154     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
5155     * </ul>
5156     * <p>
5157     * Subclasses should override this method, call the super implementation,
5158     * and set additional attributes.
5159     * </p>
5160     * <p>
5161     * If an {@link AccessibilityDelegate} has been specified via calling
5162     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5163     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
5164     * is responsible for handling this call.
5165     * </p>
5166     *
5167     * @param info The instance to initialize.
5168     */
5169    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
5170        if (mAccessibilityDelegate != null) {
5171            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
5172        } else {
5173            onInitializeAccessibilityNodeInfoInternal(info);
5174        }
5175    }
5176
5177    /**
5178     * Gets the location of this view in screen coordintates.
5179     *
5180     * @param outRect The output location
5181     */
5182    void getBoundsOnScreen(Rect outRect) {
5183        if (mAttachInfo == null) {
5184            return;
5185        }
5186
5187        RectF position = mAttachInfo.mTmpTransformRect;
5188        position.set(0, 0, mRight - mLeft, mBottom - mTop);
5189
5190        if (!hasIdentityMatrix()) {
5191            getMatrix().mapRect(position);
5192        }
5193
5194        position.offset(mLeft, mTop);
5195
5196        ViewParent parent = mParent;
5197        while (parent instanceof View) {
5198            View parentView = (View) parent;
5199
5200            position.offset(-parentView.mScrollX, -parentView.mScrollY);
5201
5202            if (!parentView.hasIdentityMatrix()) {
5203                parentView.getMatrix().mapRect(position);
5204            }
5205
5206            position.offset(parentView.mLeft, parentView.mTop);
5207
5208            parent = parentView.mParent;
5209        }
5210
5211        if (parent instanceof ViewRootImpl) {
5212            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
5213            position.offset(0, -viewRootImpl.mCurScrollY);
5214        }
5215
5216        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
5217
5218        outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f),
5219                (int) (position.right + 0.5f), (int) (position.bottom + 0.5f));
5220    }
5221
5222    /**
5223     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
5224     *
5225     * Note: Called from the default {@link AccessibilityDelegate}.
5226     */
5227    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
5228        Rect bounds = mAttachInfo.mTmpInvalRect;
5229
5230        getDrawingRect(bounds);
5231        info.setBoundsInParent(bounds);
5232
5233        getBoundsOnScreen(bounds);
5234        info.setBoundsInScreen(bounds);
5235
5236        ViewParent parent = getParentForAccessibility();
5237        if (parent instanceof View) {
5238            info.setParent((View) parent);
5239        }
5240
5241        if (mID != View.NO_ID) {
5242            View rootView = getRootView();
5243            if (rootView == null) {
5244                rootView = this;
5245            }
5246            View label = rootView.findLabelForView(this, mID);
5247            if (label != null) {
5248                info.setLabeledBy(label);
5249            }
5250
5251            if ((mAttachInfo.mAccessibilityFetchFlags
5252                    & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0
5253                    && Resources.resourceHasPackage(mID)) {
5254                try {
5255                    String viewId = getResources().getResourceName(mID);
5256                    info.setViewIdResourceName(viewId);
5257                } catch (Resources.NotFoundException nfe) {
5258                    /* ignore */
5259                }
5260            }
5261        }
5262
5263        if (mLabelForId != View.NO_ID) {
5264            View rootView = getRootView();
5265            if (rootView == null) {
5266                rootView = this;
5267            }
5268            View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId);
5269            if (labeled != null) {
5270                info.setLabelFor(labeled);
5271            }
5272        }
5273
5274        info.setVisibleToUser(isVisibleToUser());
5275
5276        info.setPackageName(mContext.getPackageName());
5277        info.setClassName(View.class.getName());
5278        info.setContentDescription(getContentDescription());
5279
5280        info.setEnabled(isEnabled());
5281        info.setClickable(isClickable());
5282        info.setFocusable(isFocusable());
5283        info.setFocused(isFocused());
5284        info.setAccessibilityFocused(isAccessibilityFocused());
5285        info.setSelected(isSelected());
5286        info.setLongClickable(isLongClickable());
5287        info.setLiveRegion(getAccessibilityLiveRegion());
5288
5289        // TODO: These make sense only if we are in an AdapterView but all
5290        // views can be selected. Maybe from accessibility perspective
5291        // we should report as selectable view in an AdapterView.
5292        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
5293        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
5294
5295        if (isFocusable()) {
5296            if (isFocused()) {
5297                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
5298            } else {
5299                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
5300            }
5301        }
5302
5303        if (!isAccessibilityFocused()) {
5304            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
5305        } else {
5306            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
5307        }
5308
5309        if (isClickable() && isEnabled()) {
5310            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
5311        }
5312
5313        if (isLongClickable() && isEnabled()) {
5314            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
5315        }
5316
5317        CharSequence text = getIterableTextForAccessibility();
5318        if (text != null && text.length() > 0) {
5319            info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd());
5320
5321            info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION);
5322            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
5323            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
5324            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
5325                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
5326                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
5327        }
5328    }
5329
5330    private View findLabelForView(View view, int labeledId) {
5331        if (mMatchLabelForPredicate == null) {
5332            mMatchLabelForPredicate = new MatchLabelForPredicate();
5333        }
5334        mMatchLabelForPredicate.mLabeledId = labeledId;
5335        return findViewByPredicateInsideOut(view, mMatchLabelForPredicate);
5336    }
5337
5338    /**
5339     * Computes whether this view is visible to the user. Such a view is
5340     * attached, visible, all its predecessors are visible, it is not clipped
5341     * entirely by its predecessors, and has an alpha greater than zero.
5342     *
5343     * @return Whether the view is visible on the screen.
5344     *
5345     * @hide
5346     */
5347    protected boolean isVisibleToUser() {
5348        return isVisibleToUser(null);
5349    }
5350
5351    /**
5352     * Computes whether the given portion of this view is visible to the user.
5353     * Such a view is attached, visible, all its predecessors are visible,
5354     * has an alpha greater than zero, and the specified portion is not
5355     * clipped entirely by its predecessors.
5356     *
5357     * @param boundInView the portion of the view to test; coordinates should be relative; may be
5358     *                    <code>null</code>, and the entire view will be tested in this case.
5359     *                    When <code>true</code> is returned by the function, the actual visible
5360     *                    region will be stored in this parameter; that is, if boundInView is fully
5361     *                    contained within the view, no modification will be made, otherwise regions
5362     *                    outside of the visible area of the view will be clipped.
5363     *
5364     * @return Whether the specified portion of the view is visible on the screen.
5365     *
5366     * @hide
5367     */
5368    protected boolean isVisibleToUser(Rect boundInView) {
5369        if (mAttachInfo != null) {
5370            // Attached to invisible window means this view is not visible.
5371            if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
5372                return false;
5373            }
5374            // An invisible predecessor or one with alpha zero means
5375            // that this view is not visible to the user.
5376            Object current = this;
5377            while (current instanceof View) {
5378                View view = (View) current;
5379                // We have attach info so this view is attached and there is no
5380                // need to check whether we reach to ViewRootImpl on the way up.
5381                if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 ||
5382                        view.getVisibility() != VISIBLE) {
5383                    return false;
5384                }
5385                current = view.mParent;
5386            }
5387            // Check if the view is entirely covered by its predecessors.
5388            Rect visibleRect = mAttachInfo.mTmpInvalRect;
5389            Point offset = mAttachInfo.mPoint;
5390            if (!getGlobalVisibleRect(visibleRect, offset)) {
5391                return false;
5392            }
5393            // Check if the visible portion intersects the rectangle of interest.
5394            if (boundInView != null) {
5395                visibleRect.offset(-offset.x, -offset.y);
5396                return boundInView.intersect(visibleRect);
5397            }
5398            return true;
5399        }
5400        return false;
5401    }
5402
5403    /**
5404     * Returns the delegate for implementing accessibility support via
5405     * composition. For more details see {@link AccessibilityDelegate}.
5406     *
5407     * @return The delegate, or null if none set.
5408     *
5409     * @hide
5410     */
5411    public AccessibilityDelegate getAccessibilityDelegate() {
5412        return mAccessibilityDelegate;
5413    }
5414
5415    /**
5416     * Sets a delegate for implementing accessibility support via composition as
5417     * opposed to inheritance. The delegate's primary use is for implementing
5418     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
5419     *
5420     * @param delegate The delegate instance.
5421     *
5422     * @see AccessibilityDelegate
5423     */
5424    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
5425        mAccessibilityDelegate = delegate;
5426    }
5427
5428    /**
5429     * Gets the provider for managing a virtual view hierarchy rooted at this View
5430     * and reported to {@link android.accessibilityservice.AccessibilityService}s
5431     * that explore the window content.
5432     * <p>
5433     * If this method returns an instance, this instance is responsible for managing
5434     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
5435     * View including the one representing the View itself. Similarly the returned
5436     * instance is responsible for performing accessibility actions on any virtual
5437     * view or the root view itself.
5438     * </p>
5439     * <p>
5440     * If an {@link AccessibilityDelegate} has been specified via calling
5441     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5442     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
5443     * is responsible for handling this call.
5444     * </p>
5445     *
5446     * @return The provider.
5447     *
5448     * @see AccessibilityNodeProvider
5449     */
5450    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
5451        if (mAccessibilityDelegate != null) {
5452            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
5453        } else {
5454            return null;
5455        }
5456    }
5457
5458    /**
5459     * Gets the unique identifier of this view on the screen for accessibility purposes.
5460     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
5461     *
5462     * @return The view accessibility id.
5463     *
5464     * @hide
5465     */
5466    public int getAccessibilityViewId() {
5467        if (mAccessibilityViewId == NO_ID) {
5468            mAccessibilityViewId = sNextAccessibilityViewId++;
5469        }
5470        return mAccessibilityViewId;
5471    }
5472
5473    /**
5474     * Gets the unique identifier of the window in which this View reseides.
5475     *
5476     * @return The window accessibility id.
5477     *
5478     * @hide
5479     */
5480    public int getAccessibilityWindowId() {
5481        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID;
5482    }
5483
5484    /**
5485     * Gets the {@link View} description. It briefly describes the view and is
5486     * primarily used for accessibility support. Set this property to enable
5487     * better accessibility support for your application. This is especially
5488     * true for views that do not have textual representation (For example,
5489     * ImageButton).
5490     *
5491     * @return The content description.
5492     *
5493     * @attr ref android.R.styleable#View_contentDescription
5494     */
5495    @ViewDebug.ExportedProperty(category = "accessibility")
5496    public CharSequence getContentDescription() {
5497        return mContentDescription;
5498    }
5499
5500    /**
5501     * Sets the {@link View} description. It briefly describes the view and is
5502     * primarily used for accessibility support. Set this property to enable
5503     * better accessibility support for your application. This is especially
5504     * true for views that do not have textual representation (For example,
5505     * ImageButton).
5506     *
5507     * @param contentDescription The content description.
5508     *
5509     * @attr ref android.R.styleable#View_contentDescription
5510     */
5511    @RemotableViewMethod
5512    public void setContentDescription(CharSequence contentDescription) {
5513        if (mContentDescription == null) {
5514            if (contentDescription == null) {
5515                return;
5516            }
5517        } else if (mContentDescription.equals(contentDescription)) {
5518            return;
5519        }
5520        mContentDescription = contentDescription;
5521        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
5522        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
5523            setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
5524            notifySubtreeAccessibilityStateChangedIfNeeded();
5525        } else {
5526            notifyViewAccessibilityStateChangedIfNeeded(
5527                    AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION);
5528        }
5529    }
5530
5531    /**
5532     * Gets the id of a view for which this view serves as a label for
5533     * accessibility purposes.
5534     *
5535     * @return The labeled view id.
5536     */
5537    @ViewDebug.ExportedProperty(category = "accessibility")
5538    public int getLabelFor() {
5539        return mLabelForId;
5540    }
5541
5542    /**
5543     * Sets the id of a view for which this view serves as a label for
5544     * accessibility purposes.
5545     *
5546     * @param id The labeled view id.
5547     */
5548    @RemotableViewMethod
5549    public void setLabelFor(int id) {
5550        mLabelForId = id;
5551        if (mLabelForId != View.NO_ID
5552                && mID == View.NO_ID) {
5553            mID = generateViewId();
5554        }
5555    }
5556
5557    /**
5558     * Invoked whenever this view loses focus, either by losing window focus or by losing
5559     * focus within its window. This method can be used to clear any state tied to the
5560     * focus. For instance, if a button is held pressed with the trackball and the window
5561     * loses focus, this method can be used to cancel the press.
5562     *
5563     * Subclasses of View overriding this method should always call super.onFocusLost().
5564     *
5565     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
5566     * @see #onWindowFocusChanged(boolean)
5567     *
5568     * @hide pending API council approval
5569     */
5570    protected void onFocusLost() {
5571        resetPressedState();
5572    }
5573
5574    private void resetPressedState() {
5575        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
5576            return;
5577        }
5578
5579        if (isPressed()) {
5580            setPressed(false);
5581
5582            if (!mHasPerformedLongPress) {
5583                removeLongPressCallback();
5584            }
5585        }
5586    }
5587
5588    /**
5589     * Returns true if this view has focus
5590     *
5591     * @return True if this view has focus, false otherwise.
5592     */
5593    @ViewDebug.ExportedProperty(category = "focus")
5594    public boolean isFocused() {
5595        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
5596    }
5597
5598    /**
5599     * Find the view in the hierarchy rooted at this view that currently has
5600     * focus.
5601     *
5602     * @return The view that currently has focus, or null if no focused view can
5603     *         be found.
5604     */
5605    public View findFocus() {
5606        return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
5607    }
5608
5609    /**
5610     * Indicates whether this view is one of the set of scrollable containers in
5611     * its window.
5612     *
5613     * @return whether this view is one of the set of scrollable containers in
5614     * its window
5615     *
5616     * @attr ref android.R.styleable#View_isScrollContainer
5617     */
5618    public boolean isScrollContainer() {
5619        return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0;
5620    }
5621
5622    /**
5623     * Change whether this view is one of the set of scrollable containers in
5624     * its window.  This will be used to determine whether the window can
5625     * resize or must pan when a soft input area is open -- scrollable
5626     * containers allow the window to use resize mode since the container
5627     * will appropriately shrink.
5628     *
5629     * @attr ref android.R.styleable#View_isScrollContainer
5630     */
5631    public void setScrollContainer(boolean isScrollContainer) {
5632        if (isScrollContainer) {
5633            if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) {
5634                mAttachInfo.mScrollContainers.add(this);
5635                mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
5636            }
5637            mPrivateFlags |= PFLAG_SCROLL_CONTAINER;
5638        } else {
5639            if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
5640                mAttachInfo.mScrollContainers.remove(this);
5641            }
5642            mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED);
5643        }
5644    }
5645
5646    /**
5647     * Returns the quality of the drawing cache.
5648     *
5649     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5650     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5651     *
5652     * @see #setDrawingCacheQuality(int)
5653     * @see #setDrawingCacheEnabled(boolean)
5654     * @see #isDrawingCacheEnabled()
5655     *
5656     * @attr ref android.R.styleable#View_drawingCacheQuality
5657     */
5658    public int getDrawingCacheQuality() {
5659        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
5660    }
5661
5662    /**
5663     * Set the drawing cache quality of this view. This value is used only when the
5664     * drawing cache is enabled
5665     *
5666     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5667     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5668     *
5669     * @see #getDrawingCacheQuality()
5670     * @see #setDrawingCacheEnabled(boolean)
5671     * @see #isDrawingCacheEnabled()
5672     *
5673     * @attr ref android.R.styleable#View_drawingCacheQuality
5674     */
5675    public void setDrawingCacheQuality(int quality) {
5676        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
5677    }
5678
5679    /**
5680     * Returns whether the screen should remain on, corresponding to the current
5681     * value of {@link #KEEP_SCREEN_ON}.
5682     *
5683     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
5684     *
5685     * @see #setKeepScreenOn(boolean)
5686     *
5687     * @attr ref android.R.styleable#View_keepScreenOn
5688     */
5689    public boolean getKeepScreenOn() {
5690        return (mViewFlags & KEEP_SCREEN_ON) != 0;
5691    }
5692
5693    /**
5694     * Controls whether the screen should remain on, modifying the
5695     * value of {@link #KEEP_SCREEN_ON}.
5696     *
5697     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
5698     *
5699     * @see #getKeepScreenOn()
5700     *
5701     * @attr ref android.R.styleable#View_keepScreenOn
5702     */
5703    public void setKeepScreenOn(boolean keepScreenOn) {
5704        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
5705    }
5706
5707    /**
5708     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5709     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5710     *
5711     * @attr ref android.R.styleable#View_nextFocusLeft
5712     */
5713    public int getNextFocusLeftId() {
5714        return mNextFocusLeftId;
5715    }
5716
5717    /**
5718     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5719     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
5720     * decide automatically.
5721     *
5722     * @attr ref android.R.styleable#View_nextFocusLeft
5723     */
5724    public void setNextFocusLeftId(int nextFocusLeftId) {
5725        mNextFocusLeftId = nextFocusLeftId;
5726    }
5727
5728    /**
5729     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5730     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5731     *
5732     * @attr ref android.R.styleable#View_nextFocusRight
5733     */
5734    public int getNextFocusRightId() {
5735        return mNextFocusRightId;
5736    }
5737
5738    /**
5739     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5740     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
5741     * decide automatically.
5742     *
5743     * @attr ref android.R.styleable#View_nextFocusRight
5744     */
5745    public void setNextFocusRightId(int nextFocusRightId) {
5746        mNextFocusRightId = nextFocusRightId;
5747    }
5748
5749    /**
5750     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5751     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5752     *
5753     * @attr ref android.R.styleable#View_nextFocusUp
5754     */
5755    public int getNextFocusUpId() {
5756        return mNextFocusUpId;
5757    }
5758
5759    /**
5760     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5761     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
5762     * decide automatically.
5763     *
5764     * @attr ref android.R.styleable#View_nextFocusUp
5765     */
5766    public void setNextFocusUpId(int nextFocusUpId) {
5767        mNextFocusUpId = nextFocusUpId;
5768    }
5769
5770    /**
5771     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5772     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5773     *
5774     * @attr ref android.R.styleable#View_nextFocusDown
5775     */
5776    public int getNextFocusDownId() {
5777        return mNextFocusDownId;
5778    }
5779
5780    /**
5781     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5782     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
5783     * decide automatically.
5784     *
5785     * @attr ref android.R.styleable#View_nextFocusDown
5786     */
5787    public void setNextFocusDownId(int nextFocusDownId) {
5788        mNextFocusDownId = nextFocusDownId;
5789    }
5790
5791    /**
5792     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5793     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5794     *
5795     * @attr ref android.R.styleable#View_nextFocusForward
5796     */
5797    public int getNextFocusForwardId() {
5798        return mNextFocusForwardId;
5799    }
5800
5801    /**
5802     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5803     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
5804     * decide automatically.
5805     *
5806     * @attr ref android.R.styleable#View_nextFocusForward
5807     */
5808    public void setNextFocusForwardId(int nextFocusForwardId) {
5809        mNextFocusForwardId = nextFocusForwardId;
5810    }
5811
5812    /**
5813     * Returns the visibility of this view and all of its ancestors
5814     *
5815     * @return True if this view and all of its ancestors are {@link #VISIBLE}
5816     */
5817    public boolean isShown() {
5818        View current = this;
5819        //noinspection ConstantConditions
5820        do {
5821            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
5822                return false;
5823            }
5824            ViewParent parent = current.mParent;
5825            if (parent == null) {
5826                return false; // We are not attached to the view root
5827            }
5828            if (!(parent instanceof View)) {
5829                return true;
5830            }
5831            current = (View) parent;
5832        } while (current != null);
5833
5834        return false;
5835    }
5836
5837    /**
5838     * Called by the view hierarchy when the content insets for a window have
5839     * changed, to allow it to adjust its content to fit within those windows.
5840     * The content insets tell you the space that the status bar, input method,
5841     * and other system windows infringe on the application's window.
5842     *
5843     * <p>You do not normally need to deal with this function, since the default
5844     * window decoration given to applications takes care of applying it to the
5845     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
5846     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
5847     * and your content can be placed under those system elements.  You can then
5848     * use this method within your view hierarchy if you have parts of your UI
5849     * which you would like to ensure are not being covered.
5850     *
5851     * <p>The default implementation of this method simply applies the content
5852     * insets to the view's padding, consuming that content (modifying the
5853     * insets to be 0), and returning true.  This behavior is off by default, but can
5854     * be enabled through {@link #setFitsSystemWindows(boolean)}.
5855     *
5856     * <p>This function's traversal down the hierarchy is depth-first.  The same content
5857     * insets object is propagated down the hierarchy, so any changes made to it will
5858     * be seen by all following views (including potentially ones above in
5859     * the hierarchy since this is a depth-first traversal).  The first view
5860     * that returns true will abort the entire traversal.
5861     *
5862     * <p>The default implementation works well for a situation where it is
5863     * used with a container that covers the entire window, allowing it to
5864     * apply the appropriate insets to its content on all edges.  If you need
5865     * a more complicated layout (such as two different views fitting system
5866     * windows, one on the top of the window, and one on the bottom),
5867     * you can override the method and handle the insets however you would like.
5868     * Note that the insets provided by the framework are always relative to the
5869     * far edges of the window, not accounting for the location of the called view
5870     * within that window.  (In fact when this method is called you do not yet know
5871     * where the layout will place the view, as it is done before layout happens.)
5872     *
5873     * <p>Note: unlike many View methods, there is no dispatch phase to this
5874     * call.  If you are overriding it in a ViewGroup and want to allow the
5875     * call to continue to your children, you must be sure to call the super
5876     * implementation.
5877     *
5878     * <p>Here is a sample layout that makes use of fitting system windows
5879     * to have controls for a video view placed inside of the window decorations
5880     * that it hides and shows.  This can be used with code like the second
5881     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
5882     *
5883     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
5884     *
5885     * @param insets Current content insets of the window.  Prior to
5886     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
5887     * the insets or else you and Android will be unhappy.
5888     *
5889     * @return {@code true} if this view applied the insets and it should not
5890     * continue propagating further down the hierarchy, {@code false} otherwise.
5891     * @see #getFitsSystemWindows()
5892     * @see #setFitsSystemWindows(boolean)
5893     * @see #setSystemUiVisibility(int)
5894     */
5895    protected boolean fitSystemWindows(Rect insets) {
5896        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
5897            mUserPaddingStart = UNDEFINED_PADDING;
5898            mUserPaddingEnd = UNDEFINED_PADDING;
5899            Rect localInsets = sThreadLocal.get();
5900            if (localInsets == null) {
5901                localInsets = new Rect();
5902                sThreadLocal.set(localInsets);
5903            }
5904            boolean res = computeFitSystemWindows(insets, localInsets);
5905            mUserPaddingLeftInitial = localInsets.left;
5906            mUserPaddingRightInitial = localInsets.right;
5907            internalSetPadding(localInsets.left, localInsets.top,
5908                    localInsets.right, localInsets.bottom);
5909            return res;
5910        }
5911        return false;
5912    }
5913
5914    /**
5915     * @hide Compute the insets that should be consumed by this view and the ones
5916     * that should propagate to those under it.
5917     */
5918    protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) {
5919        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
5920                || mAttachInfo == null
5921                || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0
5922                        && !mAttachInfo.mOverscanRequested)) {
5923            outLocalInsets.set(inoutInsets);
5924            inoutInsets.set(0, 0, 0, 0);
5925            return true;
5926        } else {
5927            // The application wants to take care of fitting system window for
5928            // the content...  however we still need to take care of any overscan here.
5929            final Rect overscan = mAttachInfo.mOverscanInsets;
5930            outLocalInsets.set(overscan);
5931            inoutInsets.left -= overscan.left;
5932            inoutInsets.top -= overscan.top;
5933            inoutInsets.right -= overscan.right;
5934            inoutInsets.bottom -= overscan.bottom;
5935            return false;
5936        }
5937    }
5938
5939    /**
5940     * Sets whether or not this view should account for system screen decorations
5941     * such as the status bar and inset its content; that is, controlling whether
5942     * the default implementation of {@link #fitSystemWindows(Rect)} will be
5943     * executed.  See that method for more details.
5944     *
5945     * <p>Note that if you are providing your own implementation of
5946     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
5947     * flag to true -- your implementation will be overriding the default
5948     * implementation that checks this flag.
5949     *
5950     * @param fitSystemWindows If true, then the default implementation of
5951     * {@link #fitSystemWindows(Rect)} will be executed.
5952     *
5953     * @attr ref android.R.styleable#View_fitsSystemWindows
5954     * @see #getFitsSystemWindows()
5955     * @see #fitSystemWindows(Rect)
5956     * @see #setSystemUiVisibility(int)
5957     */
5958    public void setFitsSystemWindows(boolean fitSystemWindows) {
5959        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
5960    }
5961
5962    /**
5963     * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method
5964     * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)}
5965     * will be executed.
5966     *
5967     * @return {@code true} if the default implementation of
5968     * {@link #fitSystemWindows(Rect)} will be executed.
5969     *
5970     * @attr ref android.R.styleable#View_fitsSystemWindows
5971     * @see #setFitsSystemWindows(boolean)
5972     * @see #fitSystemWindows(Rect)
5973     * @see #setSystemUiVisibility(int)
5974     */
5975    public boolean getFitsSystemWindows() {
5976        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
5977    }
5978
5979    /** @hide */
5980    public boolean fitsSystemWindows() {
5981        return getFitsSystemWindows();
5982    }
5983
5984    /**
5985     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
5986     */
5987    public void requestFitSystemWindows() {
5988        if (mParent != null) {
5989            mParent.requestFitSystemWindows();
5990        }
5991    }
5992
5993    /**
5994     * For use by PhoneWindow to make its own system window fitting optional.
5995     * @hide
5996     */
5997    public void makeOptionalFitsSystemWindows() {
5998        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
5999    }
6000
6001    /**
6002     * Returns the visibility status for this view.
6003     *
6004     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
6005     * @attr ref android.R.styleable#View_visibility
6006     */
6007    @ViewDebug.ExportedProperty(mapping = {
6008        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
6009        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
6010        @ViewDebug.IntToString(from = GONE,      to = "GONE")
6011    })
6012    public int getVisibility() {
6013        return mViewFlags & VISIBILITY_MASK;
6014    }
6015
6016    /**
6017     * Set the enabled state of this view.
6018     *
6019     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
6020     * @attr ref android.R.styleable#View_visibility
6021     */
6022    @RemotableViewMethod
6023    public void setVisibility(int visibility) {
6024        setFlags(visibility, VISIBILITY_MASK);
6025        if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false);
6026    }
6027
6028    /**
6029     * Returns the enabled status for this view. The interpretation of the
6030     * enabled state varies by subclass.
6031     *
6032     * @return True if this view is enabled, false otherwise.
6033     */
6034    @ViewDebug.ExportedProperty
6035    public boolean isEnabled() {
6036        return (mViewFlags & ENABLED_MASK) == ENABLED;
6037    }
6038
6039    /**
6040     * Set the enabled state of this view. The interpretation of the enabled
6041     * state varies by subclass.
6042     *
6043     * @param enabled True if this view is enabled, false otherwise.
6044     */
6045    @RemotableViewMethod
6046    public void setEnabled(boolean enabled) {
6047        if (enabled == isEnabled()) return;
6048
6049        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
6050
6051        /*
6052         * The View most likely has to change its appearance, so refresh
6053         * the drawable state.
6054         */
6055        refreshDrawableState();
6056
6057        // Invalidate too, since the default behavior for views is to be
6058        // be drawn at 50% alpha rather than to change the drawable.
6059        invalidate(true);
6060
6061        if (!enabled) {
6062            cancelPendingInputEvents();
6063        }
6064    }
6065
6066    /**
6067     * Set whether this view can receive the focus.
6068     *
6069     * Setting this to false will also ensure that this view is not focusable
6070     * in touch mode.
6071     *
6072     * @param focusable If true, this view can receive the focus.
6073     *
6074     * @see #setFocusableInTouchMode(boolean)
6075     * @attr ref android.R.styleable#View_focusable
6076     */
6077    public void setFocusable(boolean focusable) {
6078        if (!focusable) {
6079            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
6080        }
6081        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
6082    }
6083
6084    /**
6085     * Set whether this view can receive focus while in touch mode.
6086     *
6087     * Setting this to true will also ensure that this view is focusable.
6088     *
6089     * @param focusableInTouchMode If true, this view can receive the focus while
6090     *   in touch mode.
6091     *
6092     * @see #setFocusable(boolean)
6093     * @attr ref android.R.styleable#View_focusableInTouchMode
6094     */
6095    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
6096        // Focusable in touch mode should always be set before the focusable flag
6097        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
6098        // which, in touch mode, will not successfully request focus on this view
6099        // because the focusable in touch mode flag is not set
6100        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
6101        if (focusableInTouchMode) {
6102            setFlags(FOCUSABLE, FOCUSABLE_MASK);
6103        }
6104    }
6105
6106    /**
6107     * Set whether this view should have sound effects enabled for events such as
6108     * clicking and touching.
6109     *
6110     * <p>You may wish to disable sound effects for a view if you already play sounds,
6111     * for instance, a dial key that plays dtmf tones.
6112     *
6113     * @param soundEffectsEnabled whether sound effects are enabled for this view.
6114     * @see #isSoundEffectsEnabled()
6115     * @see #playSoundEffect(int)
6116     * @attr ref android.R.styleable#View_soundEffectsEnabled
6117     */
6118    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
6119        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
6120    }
6121
6122    /**
6123     * @return whether this view should have sound effects enabled for events such as
6124     *     clicking and touching.
6125     *
6126     * @see #setSoundEffectsEnabled(boolean)
6127     * @see #playSoundEffect(int)
6128     * @attr ref android.R.styleable#View_soundEffectsEnabled
6129     */
6130    @ViewDebug.ExportedProperty
6131    public boolean isSoundEffectsEnabled() {
6132        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
6133    }
6134
6135    /**
6136     * Set whether this view should have haptic feedback for events such as
6137     * long presses.
6138     *
6139     * <p>You may wish to disable haptic feedback if your view already controls
6140     * its own haptic feedback.
6141     *
6142     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
6143     * @see #isHapticFeedbackEnabled()
6144     * @see #performHapticFeedback(int)
6145     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
6146     */
6147    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
6148        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
6149    }
6150
6151    /**
6152     * @return whether this view should have haptic feedback enabled for events
6153     * long presses.
6154     *
6155     * @see #setHapticFeedbackEnabled(boolean)
6156     * @see #performHapticFeedback(int)
6157     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
6158     */
6159    @ViewDebug.ExportedProperty
6160    public boolean isHapticFeedbackEnabled() {
6161        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
6162    }
6163
6164    /**
6165     * Returns the layout direction for this view.
6166     *
6167     * @return One of {@link #LAYOUT_DIRECTION_LTR},
6168     *   {@link #LAYOUT_DIRECTION_RTL},
6169     *   {@link #LAYOUT_DIRECTION_INHERIT} or
6170     *   {@link #LAYOUT_DIRECTION_LOCALE}.
6171     *
6172     * @attr ref android.R.styleable#View_layoutDirection
6173     *
6174     * @hide
6175     */
6176    @ViewDebug.ExportedProperty(category = "layout", mapping = {
6177        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
6178        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
6179        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
6180        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
6181    })
6182    public int getRawLayoutDirection() {
6183        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
6184    }
6185
6186    /**
6187     * Set the layout direction for this view. This will propagate a reset of layout direction
6188     * resolution to the view's children and resolve layout direction for this view.
6189     *
6190     * @param layoutDirection the layout direction to set. Should be one of:
6191     *
6192     * {@link #LAYOUT_DIRECTION_LTR},
6193     * {@link #LAYOUT_DIRECTION_RTL},
6194     * {@link #LAYOUT_DIRECTION_INHERIT},
6195     * {@link #LAYOUT_DIRECTION_LOCALE}.
6196     *
6197     * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution
6198     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
6199     * will return the default {@link #LAYOUT_DIRECTION_LTR}.
6200     *
6201     * @attr ref android.R.styleable#View_layoutDirection
6202     */
6203    @RemotableViewMethod
6204    public void setLayoutDirection(int layoutDirection) {
6205        if (getRawLayoutDirection() != layoutDirection) {
6206            // Reset the current layout direction and the resolved one
6207            mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK;
6208            resetRtlProperties();
6209            // Set the new layout direction (filtered)
6210            mPrivateFlags2 |=
6211                    ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK);
6212            // We need to resolve all RTL properties as they all depend on layout direction
6213            resolveRtlPropertiesIfNeeded();
6214            requestLayout();
6215            invalidate(true);
6216        }
6217    }
6218
6219    /**
6220     * Returns the resolved layout direction for this view.
6221     *
6222     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
6223     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
6224     *
6225     * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version
6226     * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}.
6227     *
6228     * @attr ref android.R.styleable#View_layoutDirection
6229     */
6230    @ViewDebug.ExportedProperty(category = "layout", mapping = {
6231        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
6232        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
6233    })
6234    public int getLayoutDirection() {
6235        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
6236        if (targetSdkVersion < JELLY_BEAN_MR1) {
6237            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
6238            return LAYOUT_DIRECTION_RESOLVED_DEFAULT;
6239        }
6240        return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ==
6241                PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
6242    }
6243
6244    /**
6245     * Indicates whether or not this view's layout is right-to-left. This is resolved from
6246     * layout attribute and/or the inherited value from the parent
6247     *
6248     * @return true if the layout is right-to-left.
6249     *
6250     * @hide
6251     */
6252    @ViewDebug.ExportedProperty(category = "layout")
6253    public boolean isLayoutRtl() {
6254        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
6255    }
6256
6257    /**
6258     * Indicates whether the view is currently tracking transient state that the
6259     * app should not need to concern itself with saving and restoring, but that
6260     * the framework should take special note to preserve when possible.
6261     *
6262     * <p>A view with transient state cannot be trivially rebound from an external
6263     * data source, such as an adapter binding item views in a list. This may be
6264     * because the view is performing an animation, tracking user selection
6265     * of content, or similar.</p>
6266     *
6267     * @return true if the view has transient state
6268     */
6269    @ViewDebug.ExportedProperty(category = "layout")
6270    public boolean hasTransientState() {
6271        return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE;
6272    }
6273
6274    /**
6275     * Set whether this view is currently tracking transient state that the
6276     * framework should attempt to preserve when possible. This flag is reference counted,
6277     * so every call to setHasTransientState(true) should be paired with a later call
6278     * to setHasTransientState(false).
6279     *
6280     * <p>A view with transient state cannot be trivially rebound from an external
6281     * data source, such as an adapter binding item views in a list. This may be
6282     * because the view is performing an animation, tracking user selection
6283     * of content, or similar.</p>
6284     *
6285     * @param hasTransientState true if this view has transient state
6286     */
6287    public void setHasTransientState(boolean hasTransientState) {
6288        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
6289                mTransientStateCount - 1;
6290        if (mTransientStateCount < 0) {
6291            mTransientStateCount = 0;
6292            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
6293                    "unmatched pair of setHasTransientState calls");
6294        } else if ((hasTransientState && mTransientStateCount == 1) ||
6295                (!hasTransientState && mTransientStateCount == 0)) {
6296            // update flag if we've just incremented up from 0 or decremented down to 0
6297            mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) |
6298                    (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0);
6299            if (mParent != null) {
6300                try {
6301                    mParent.childHasTransientStateChanged(this, hasTransientState);
6302                } catch (AbstractMethodError e) {
6303                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
6304                            " does not fully implement ViewParent", e);
6305                }
6306            }
6307        }
6308    }
6309
6310    /**
6311     * Returns true if this view is currently attached to a window.
6312     */
6313    public boolean isAttachedToWindow() {
6314        return mAttachInfo != null;
6315    }
6316
6317    /**
6318     * Returns true if this view has been through at least one layout since it
6319     * was last attached to or detached from a window.
6320     */
6321    public boolean isLaidOut() {
6322        return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT;
6323    }
6324
6325    /**
6326     * If this view doesn't do any drawing on its own, set this flag to
6327     * allow further optimizations. By default, this flag is not set on
6328     * View, but could be set on some View subclasses such as ViewGroup.
6329     *
6330     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
6331     * you should clear this flag.
6332     *
6333     * @param willNotDraw whether or not this View draw on its own
6334     */
6335    public void setWillNotDraw(boolean willNotDraw) {
6336        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
6337    }
6338
6339    /**
6340     * Returns whether or not this View draws on its own.
6341     *
6342     * @return true if this view has nothing to draw, false otherwise
6343     */
6344    @ViewDebug.ExportedProperty(category = "drawing")
6345    public boolean willNotDraw() {
6346        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
6347    }
6348
6349    /**
6350     * When a View's drawing cache is enabled, drawing is redirected to an
6351     * offscreen bitmap. Some views, like an ImageView, must be able to
6352     * bypass this mechanism if they already draw a single bitmap, to avoid
6353     * unnecessary usage of the memory.
6354     *
6355     * @param willNotCacheDrawing true if this view does not cache its
6356     *        drawing, false otherwise
6357     */
6358    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
6359        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
6360    }
6361
6362    /**
6363     * Returns whether or not this View can cache its drawing or not.
6364     *
6365     * @return true if this view does not cache its drawing, false otherwise
6366     */
6367    @ViewDebug.ExportedProperty(category = "drawing")
6368    public boolean willNotCacheDrawing() {
6369        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
6370    }
6371
6372    /**
6373     * Indicates whether this view reacts to click events or not.
6374     *
6375     * @return true if the view is clickable, false otherwise
6376     *
6377     * @see #setClickable(boolean)
6378     * @attr ref android.R.styleable#View_clickable
6379     */
6380    @ViewDebug.ExportedProperty
6381    public boolean isClickable() {
6382        return (mViewFlags & CLICKABLE) == CLICKABLE;
6383    }
6384
6385    /**
6386     * Enables or disables click events for this view. When a view
6387     * is clickable it will change its state to "pressed" on every click.
6388     * Subclasses should set the view clickable to visually react to
6389     * user's clicks.
6390     *
6391     * @param clickable true to make the view clickable, false otherwise
6392     *
6393     * @see #isClickable()
6394     * @attr ref android.R.styleable#View_clickable
6395     */
6396    public void setClickable(boolean clickable) {
6397        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
6398    }
6399
6400    /**
6401     * Indicates whether this view reacts to long click events or not.
6402     *
6403     * @return true if the view is long clickable, false otherwise
6404     *
6405     * @see #setLongClickable(boolean)
6406     * @attr ref android.R.styleable#View_longClickable
6407     */
6408    public boolean isLongClickable() {
6409        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
6410    }
6411
6412    /**
6413     * Enables or disables long click events for this view. When a view is long
6414     * clickable it reacts to the user holding down the button for a longer
6415     * duration than a tap. This event can either launch the listener or a
6416     * context menu.
6417     *
6418     * @param longClickable true to make the view long clickable, false otherwise
6419     * @see #isLongClickable()
6420     * @attr ref android.R.styleable#View_longClickable
6421     */
6422    public void setLongClickable(boolean longClickable) {
6423        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
6424    }
6425
6426    /**
6427     * Sets the pressed state for this view.
6428     *
6429     * @see #isClickable()
6430     * @see #setClickable(boolean)
6431     *
6432     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
6433     *        the View's internal state from a previously set "pressed" state.
6434     */
6435    public void setPressed(boolean pressed) {
6436        final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
6437
6438        if (pressed) {
6439            mPrivateFlags |= PFLAG_PRESSED;
6440        } else {
6441            mPrivateFlags &= ~PFLAG_PRESSED;
6442        }
6443
6444        if (needsRefresh) {
6445            refreshDrawableState();
6446        }
6447        dispatchSetPressed(pressed);
6448    }
6449
6450    /**
6451     * Dispatch setPressed to all of this View's children.
6452     *
6453     * @see #setPressed(boolean)
6454     *
6455     * @param pressed The new pressed state
6456     */
6457    protected void dispatchSetPressed(boolean pressed) {
6458    }
6459
6460    /**
6461     * Indicates whether the view is currently in pressed state. Unless
6462     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
6463     * the pressed state.
6464     *
6465     * @see #setPressed(boolean)
6466     * @see #isClickable()
6467     * @see #setClickable(boolean)
6468     *
6469     * @return true if the view is currently pressed, false otherwise
6470     */
6471    public boolean isPressed() {
6472        return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED;
6473    }
6474
6475    /**
6476     * Indicates whether this view will save its state (that is,
6477     * whether its {@link #onSaveInstanceState} method will be called).
6478     *
6479     * @return Returns true if the view state saving is enabled, else false.
6480     *
6481     * @see #setSaveEnabled(boolean)
6482     * @attr ref android.R.styleable#View_saveEnabled
6483     */
6484    public boolean isSaveEnabled() {
6485        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
6486    }
6487
6488    /**
6489     * Controls whether the saving of this view's state is
6490     * enabled (that is, whether its {@link #onSaveInstanceState} method
6491     * will be called).  Note that even if freezing is enabled, the
6492     * view still must have an id assigned to it (via {@link #setId(int)})
6493     * for its state to be saved.  This flag can only disable the
6494     * saving of this view; any child views may still have their state saved.
6495     *
6496     * @param enabled Set to false to <em>disable</em> state saving, or true
6497     * (the default) to allow it.
6498     *
6499     * @see #isSaveEnabled()
6500     * @see #setId(int)
6501     * @see #onSaveInstanceState()
6502     * @attr ref android.R.styleable#View_saveEnabled
6503     */
6504    public void setSaveEnabled(boolean enabled) {
6505        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
6506    }
6507
6508    /**
6509     * Gets whether the framework should discard touches when the view's
6510     * window is obscured by another visible window.
6511     * Refer to the {@link View} security documentation for more details.
6512     *
6513     * @return True if touch filtering is enabled.
6514     *
6515     * @see #setFilterTouchesWhenObscured(boolean)
6516     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
6517     */
6518    @ViewDebug.ExportedProperty
6519    public boolean getFilterTouchesWhenObscured() {
6520        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
6521    }
6522
6523    /**
6524     * Sets whether the framework should discard touches when the view's
6525     * window is obscured by another visible window.
6526     * Refer to the {@link View} security documentation for more details.
6527     *
6528     * @param enabled True if touch filtering should be enabled.
6529     *
6530     * @see #getFilterTouchesWhenObscured
6531     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
6532     */
6533    public void setFilterTouchesWhenObscured(boolean enabled) {
6534        setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
6535                FILTER_TOUCHES_WHEN_OBSCURED);
6536    }
6537
6538    /**
6539     * Indicates whether the entire hierarchy under this view will save its
6540     * state when a state saving traversal occurs from its parent.  The default
6541     * is true; if false, these views will not be saved unless
6542     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
6543     *
6544     * @return Returns true if the view state saving from parent is enabled, else false.
6545     *
6546     * @see #setSaveFromParentEnabled(boolean)
6547     */
6548    public boolean isSaveFromParentEnabled() {
6549        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
6550    }
6551
6552    /**
6553     * Controls whether the entire hierarchy under this view will save its
6554     * state when a state saving traversal occurs from its parent.  The default
6555     * is true; if false, these views will not be saved unless
6556     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
6557     *
6558     * @param enabled Set to false to <em>disable</em> state saving, or true
6559     * (the default) to allow it.
6560     *
6561     * @see #isSaveFromParentEnabled()
6562     * @see #setId(int)
6563     * @see #onSaveInstanceState()
6564     */
6565    public void setSaveFromParentEnabled(boolean enabled) {
6566        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
6567    }
6568
6569
6570    /**
6571     * Returns whether this View is able to take focus.
6572     *
6573     * @return True if this view can take focus, or false otherwise.
6574     * @attr ref android.R.styleable#View_focusable
6575     */
6576    @ViewDebug.ExportedProperty(category = "focus")
6577    public final boolean isFocusable() {
6578        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
6579    }
6580
6581    /**
6582     * When a view is focusable, it may not want to take focus when in touch mode.
6583     * For example, a button would like focus when the user is navigating via a D-pad
6584     * so that the user can click on it, but once the user starts touching the screen,
6585     * the button shouldn't take focus
6586     * @return Whether the view is focusable in touch mode.
6587     * @attr ref android.R.styleable#View_focusableInTouchMode
6588     */
6589    @ViewDebug.ExportedProperty
6590    public final boolean isFocusableInTouchMode() {
6591        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
6592    }
6593
6594    /**
6595     * Find the nearest view in the specified direction that can take focus.
6596     * This does not actually give focus to that view.
6597     *
6598     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6599     *
6600     * @return The nearest focusable in the specified direction, or null if none
6601     *         can be found.
6602     */
6603    public View focusSearch(int direction) {
6604        if (mParent != null) {
6605            return mParent.focusSearch(this, direction);
6606        } else {
6607            return null;
6608        }
6609    }
6610
6611    /**
6612     * This method is the last chance for the focused view and its ancestors to
6613     * respond to an arrow key. This is called when the focused view did not
6614     * consume the key internally, nor could the view system find a new view in
6615     * the requested direction to give focus to.
6616     *
6617     * @param focused The currently focused view.
6618     * @param direction The direction focus wants to move. One of FOCUS_UP,
6619     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
6620     * @return True if the this view consumed this unhandled move.
6621     */
6622    public boolean dispatchUnhandledMove(View focused, int direction) {
6623        return false;
6624    }
6625
6626    /**
6627     * If a user manually specified the next view id for a particular direction,
6628     * use the root to look up the view.
6629     * @param root The root view of the hierarchy containing this view.
6630     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
6631     * or FOCUS_BACKWARD.
6632     * @return The user specified next view, or null if there is none.
6633     */
6634    View findUserSetNextFocus(View root, int direction) {
6635        switch (direction) {
6636            case FOCUS_LEFT:
6637                if (mNextFocusLeftId == View.NO_ID) return null;
6638                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
6639            case FOCUS_RIGHT:
6640                if (mNextFocusRightId == View.NO_ID) return null;
6641                return findViewInsideOutShouldExist(root, mNextFocusRightId);
6642            case FOCUS_UP:
6643                if (mNextFocusUpId == View.NO_ID) return null;
6644                return findViewInsideOutShouldExist(root, mNextFocusUpId);
6645            case FOCUS_DOWN:
6646                if (mNextFocusDownId == View.NO_ID) return null;
6647                return findViewInsideOutShouldExist(root, mNextFocusDownId);
6648            case FOCUS_FORWARD:
6649                if (mNextFocusForwardId == View.NO_ID) return null;
6650                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
6651            case FOCUS_BACKWARD: {
6652                if (mID == View.NO_ID) return null;
6653                final int id = mID;
6654                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
6655                    @Override
6656                    public boolean apply(View t) {
6657                        return t.mNextFocusForwardId == id;
6658                    }
6659                });
6660            }
6661        }
6662        return null;
6663    }
6664
6665    private View findViewInsideOutShouldExist(View root, int id) {
6666        if (mMatchIdPredicate == null) {
6667            mMatchIdPredicate = new MatchIdPredicate();
6668        }
6669        mMatchIdPredicate.mId = id;
6670        View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate);
6671        if (result == null) {
6672            Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id);
6673        }
6674        return result;
6675    }
6676
6677    /**
6678     * Find and return all focusable views that are descendants of this view,
6679     * possibly including this view if it is focusable itself.
6680     *
6681     * @param direction The direction of the focus
6682     * @return A list of focusable views
6683     */
6684    public ArrayList<View> getFocusables(int direction) {
6685        ArrayList<View> result = new ArrayList<View>(24);
6686        addFocusables(result, direction);
6687        return result;
6688    }
6689
6690    /**
6691     * Add any focusable views that are descendants of this view (possibly
6692     * including this view if it is focusable itself) to views.  If we are in touch mode,
6693     * only add views that are also focusable in touch mode.
6694     *
6695     * @param views Focusable views found so far
6696     * @param direction The direction of the focus
6697     */
6698    public void addFocusables(ArrayList<View> views, int direction) {
6699        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
6700    }
6701
6702    /**
6703     * Adds any focusable views that are descendants of this view (possibly
6704     * including this view if it is focusable itself) to views. This method
6705     * adds all focusable views regardless if we are in touch mode or
6706     * only views focusable in touch mode if we are in touch mode or
6707     * only views that can take accessibility focus if accessibility is enabeld
6708     * depending on the focusable mode paramater.
6709     *
6710     * @param views Focusable views found so far or null if all we are interested is
6711     *        the number of focusables.
6712     * @param direction The direction of the focus.
6713     * @param focusableMode The type of focusables to be added.
6714     *
6715     * @see #FOCUSABLES_ALL
6716     * @see #FOCUSABLES_TOUCH_MODE
6717     */
6718    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
6719        if (views == null) {
6720            return;
6721        }
6722        if (!isFocusable()) {
6723            return;
6724        }
6725        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
6726                && isInTouchMode() && !isFocusableInTouchMode()) {
6727            return;
6728        }
6729        views.add(this);
6730    }
6731
6732    /**
6733     * Finds the Views that contain given text. The containment is case insensitive.
6734     * The search is performed by either the text that the View renders or the content
6735     * description that describes the view for accessibility purposes and the view does
6736     * not render or both. Clients can specify how the search is to be performed via
6737     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
6738     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
6739     *
6740     * @param outViews The output list of matching Views.
6741     * @param searched The text to match against.
6742     *
6743     * @see #FIND_VIEWS_WITH_TEXT
6744     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
6745     * @see #setContentDescription(CharSequence)
6746     */
6747    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) {
6748        if (getAccessibilityNodeProvider() != null) {
6749            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
6750                outViews.add(this);
6751            }
6752        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
6753                && (searched != null && searched.length() > 0)
6754                && (mContentDescription != null && mContentDescription.length() > 0)) {
6755            String searchedLowerCase = searched.toString().toLowerCase();
6756            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
6757            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
6758                outViews.add(this);
6759            }
6760        }
6761    }
6762
6763    /**
6764     * Find and return all touchable views that are descendants of this view,
6765     * possibly including this view if it is touchable itself.
6766     *
6767     * @return A list of touchable views
6768     */
6769    public ArrayList<View> getTouchables() {
6770        ArrayList<View> result = new ArrayList<View>();
6771        addTouchables(result);
6772        return result;
6773    }
6774
6775    /**
6776     * Add any touchable views that are descendants of this view (possibly
6777     * including this view if it is touchable itself) to views.
6778     *
6779     * @param views Touchable views found so far
6780     */
6781    public void addTouchables(ArrayList<View> views) {
6782        final int viewFlags = mViewFlags;
6783
6784        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
6785                && (viewFlags & ENABLED_MASK) == ENABLED) {
6786            views.add(this);
6787        }
6788    }
6789
6790    /**
6791     * Returns whether this View is accessibility focused.
6792     *
6793     * @return True if this View is accessibility focused.
6794     * @hide
6795     */
6796    public boolean isAccessibilityFocused() {
6797        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
6798    }
6799
6800    /**
6801     * Call this to try to give accessibility focus to this view.
6802     *
6803     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
6804     * returns false or the view is no visible or the view already has accessibility
6805     * focus.
6806     *
6807     * See also {@link #focusSearch(int)}, which is what you call to say that you
6808     * have focus, and you want your parent to look for the next one.
6809     *
6810     * @return Whether this view actually took accessibility focus.
6811     *
6812     * @hide
6813     */
6814    public boolean requestAccessibilityFocus() {
6815        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
6816        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
6817            return false;
6818        }
6819        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6820            return false;
6821        }
6822        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
6823            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
6824            ViewRootImpl viewRootImpl = getViewRootImpl();
6825            if (viewRootImpl != null) {
6826                viewRootImpl.setAccessibilityFocus(this, null);
6827            }
6828            invalidate();
6829            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
6830            return true;
6831        }
6832        return false;
6833    }
6834
6835    /**
6836     * Call this to try to clear accessibility focus of this view.
6837     *
6838     * See also {@link #focusSearch(int)}, which is what you call to say that you
6839     * have focus, and you want your parent to look for the next one.
6840     *
6841     * @hide
6842     */
6843    public void clearAccessibilityFocus() {
6844        clearAccessibilityFocusNoCallbacks();
6845        // Clear the global reference of accessibility focus if this
6846        // view or any of its descendants had accessibility focus.
6847        ViewRootImpl viewRootImpl = getViewRootImpl();
6848        if (viewRootImpl != null) {
6849            View focusHost = viewRootImpl.getAccessibilityFocusedHost();
6850            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
6851                viewRootImpl.setAccessibilityFocus(null, null);
6852            }
6853        }
6854    }
6855
6856    private void sendAccessibilityHoverEvent(int eventType) {
6857        // Since we are not delivering to a client accessibility events from not
6858        // important views (unless the clinet request that) we need to fire the
6859        // event from the deepest view exposed to the client. As a consequence if
6860        // the user crosses a not exposed view the client will see enter and exit
6861        // of the exposed predecessor followed by and enter and exit of that same
6862        // predecessor when entering and exiting the not exposed descendant. This
6863        // is fine since the client has a clear idea which view is hovered at the
6864        // price of a couple more events being sent. This is a simple and
6865        // working solution.
6866        View source = this;
6867        while (true) {
6868            if (source.includeForAccessibility()) {
6869                source.sendAccessibilityEvent(eventType);
6870                return;
6871            }
6872            ViewParent parent = source.getParent();
6873            if (parent instanceof View) {
6874                source = (View) parent;
6875            } else {
6876                return;
6877            }
6878        }
6879    }
6880
6881    /**
6882     * Clears accessibility focus without calling any callback methods
6883     * normally invoked in {@link #clearAccessibilityFocus()}. This method
6884     * is used for clearing accessibility focus when giving this focus to
6885     * another view.
6886     */
6887    void clearAccessibilityFocusNoCallbacks() {
6888        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
6889            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
6890            invalidate();
6891            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
6892        }
6893    }
6894
6895    /**
6896     * Call this to try to give focus to a specific view or to one of its
6897     * descendants.
6898     *
6899     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6900     * false), or if it is focusable and it is not focusable in touch mode
6901     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6902     *
6903     * See also {@link #focusSearch(int)}, which is what you call to say that you
6904     * have focus, and you want your parent to look for the next one.
6905     *
6906     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
6907     * {@link #FOCUS_DOWN} and <code>null</code>.
6908     *
6909     * @return Whether this view or one of its descendants actually took focus.
6910     */
6911    public final boolean requestFocus() {
6912        return requestFocus(View.FOCUS_DOWN);
6913    }
6914
6915    /**
6916     * Call this to try to give focus to a specific view or to one of its
6917     * descendants and give it a hint about what direction focus is heading.
6918     *
6919     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6920     * false), or if it is focusable and it is not focusable in touch mode
6921     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6922     *
6923     * See also {@link #focusSearch(int)}, which is what you call to say that you
6924     * have focus, and you want your parent to look for the next one.
6925     *
6926     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
6927     * <code>null</code> set for the previously focused rectangle.
6928     *
6929     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6930     * @return Whether this view or one of its descendants actually took focus.
6931     */
6932    public final boolean requestFocus(int direction) {
6933        return requestFocus(direction, null);
6934    }
6935
6936    /**
6937     * Call this to try to give focus to a specific view or to one of its descendants
6938     * and give it hints about the direction and a specific rectangle that the focus
6939     * is coming from.  The rectangle can help give larger views a finer grained hint
6940     * about where focus is coming from, and therefore, where to show selection, or
6941     * forward focus change internally.
6942     *
6943     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6944     * false), or if it is focusable and it is not focusable in touch mode
6945     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6946     *
6947     * A View will not take focus if it is not visible.
6948     *
6949     * A View will not take focus if one of its parents has
6950     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
6951     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
6952     *
6953     * See also {@link #focusSearch(int)}, which is what you call to say that you
6954     * have focus, and you want your parent to look for the next one.
6955     *
6956     * You may wish to override this method if your custom {@link View} has an internal
6957     * {@link View} that it wishes to forward the request to.
6958     *
6959     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6960     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
6961     *        to give a finer grained hint about where focus is coming from.  May be null
6962     *        if there is no hint.
6963     * @return Whether this view or one of its descendants actually took focus.
6964     */
6965    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
6966        return requestFocusNoSearch(direction, previouslyFocusedRect);
6967    }
6968
6969    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
6970        // need to be focusable
6971        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
6972                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6973            return false;
6974        }
6975
6976        // need to be focusable in touch mode if in touch mode
6977        if (isInTouchMode() &&
6978            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
6979               return false;
6980        }
6981
6982        // need to not have any parents blocking us
6983        if (hasAncestorThatBlocksDescendantFocus()) {
6984            return false;
6985        }
6986
6987        handleFocusGainInternal(direction, previouslyFocusedRect);
6988        return true;
6989    }
6990
6991    /**
6992     * Call this to try to give focus to a specific view or to one of its descendants. This is a
6993     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
6994     * touch mode to request focus when they are touched.
6995     *
6996     * @return Whether this view or one of its descendants actually took focus.
6997     *
6998     * @see #isInTouchMode()
6999     *
7000     */
7001    public final boolean requestFocusFromTouch() {
7002        // Leave touch mode if we need to
7003        if (isInTouchMode()) {
7004            ViewRootImpl viewRoot = getViewRootImpl();
7005            if (viewRoot != null) {
7006                viewRoot.ensureTouchMode(false);
7007            }
7008        }
7009        return requestFocus(View.FOCUS_DOWN);
7010    }
7011
7012    /**
7013     * @return Whether any ancestor of this view blocks descendant focus.
7014     */
7015    private boolean hasAncestorThatBlocksDescendantFocus() {
7016        ViewParent ancestor = mParent;
7017        while (ancestor instanceof ViewGroup) {
7018            final ViewGroup vgAncestor = (ViewGroup) ancestor;
7019            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
7020                return true;
7021            } else {
7022                ancestor = vgAncestor.getParent();
7023            }
7024        }
7025        return false;
7026    }
7027
7028    /**
7029     * Gets the mode for determining whether this View is important for accessibility
7030     * which is if it fires accessibility events and if it is reported to
7031     * accessibility services that query the screen.
7032     *
7033     * @return The mode for determining whether a View is important for accessibility.
7034     *
7035     * @attr ref android.R.styleable#View_importantForAccessibility
7036     *
7037     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
7038     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
7039     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
7040     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
7041     */
7042    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
7043            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
7044            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
7045            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"),
7046            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS,
7047                    to = "noHideDescendants")
7048        })
7049    public int getImportantForAccessibility() {
7050        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
7051                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
7052    }
7053
7054    /**
7055     * Sets the live region mode for this view. This indicates to accessibility
7056     * services whether they should automatically notify the user about changes
7057     * to the view's content description or text, or to the content descriptions
7058     * or text of the view's children (where applicable).
7059     * <p>
7060     * For example, in a login screen with a TextView that displays an "incorrect
7061     * password" notification, that view should be marked as a live region with
7062     * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
7063     * <p>
7064     * To disable change notifications for this view, use
7065     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region
7066     * mode for most views.
7067     * <p>
7068     * To indicate that the user should be notified of changes, use
7069     * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
7070     * <p>
7071     * If the view's changes should interrupt ongoing speech and notify the user
7072     * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}.
7073     *
7074     * @param mode The live region mode for this view, one of:
7075     *        <ul>
7076     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE}
7077     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE}
7078     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}
7079     *        </ul>
7080     * @attr ref android.R.styleable#View_accessibilityLiveRegion
7081     */
7082    public void setAccessibilityLiveRegion(int mode) {
7083        if (mode != getAccessibilityLiveRegion()) {
7084            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
7085            mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT)
7086                    & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
7087            notifyViewAccessibilityStateChangedIfNeeded(
7088                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7089        }
7090    }
7091
7092    /**
7093     * Gets the live region mode for this View.
7094     *
7095     * @return The live region mode for the view.
7096     *
7097     * @attr ref android.R.styleable#View_accessibilityLiveRegion
7098     *
7099     * @see #setAccessibilityLiveRegion(int)
7100     */
7101    public int getAccessibilityLiveRegion() {
7102        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK)
7103                >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
7104    }
7105
7106    /**
7107     * Sets how to determine whether this view is important for accessibility
7108     * which is if it fires accessibility events and if it is reported to
7109     * accessibility services that query the screen.
7110     *
7111     * @param mode How to determine whether this view is important for accessibility.
7112     *
7113     * @attr ref android.R.styleable#View_importantForAccessibility
7114     *
7115     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
7116     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
7117     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
7118     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
7119     */
7120    public void setImportantForAccessibility(int mode) {
7121        final int oldMode = getImportantForAccessibility();
7122        if (mode != oldMode) {
7123            // If we're moving between AUTO and another state, we might not need
7124            // to send a subtree changed notification. We'll store the computed
7125            // importance, since we'll need to check it later to make sure.
7126            final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO
7127                    || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO;
7128            final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility();
7129            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
7130            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
7131                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
7132            if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) {
7133                notifySubtreeAccessibilityStateChangedIfNeeded();
7134            } else {
7135                notifyViewAccessibilityStateChangedIfNeeded(
7136                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7137            }
7138        }
7139    }
7140
7141    /**
7142     * Gets whether this view should be exposed for accessibility.
7143     *
7144     * @return Whether the view is exposed for accessibility.
7145     *
7146     * @hide
7147     */
7148    public boolean isImportantForAccessibility() {
7149        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
7150                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
7151        if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO
7152                || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
7153            return false;
7154        }
7155
7156        // Check parent mode to ensure we're not hidden.
7157        ViewParent parent = mParent;
7158        while (parent instanceof View) {
7159            if (((View) parent).getImportantForAccessibility()
7160                    == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
7161                return false;
7162            }
7163            parent = parent.getParent();
7164        }
7165
7166        return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility()
7167                || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null
7168                || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE;
7169    }
7170
7171    /**
7172     * Gets the parent for accessibility purposes. Note that the parent for
7173     * accessibility is not necessary the immediate parent. It is the first
7174     * predecessor that is important for accessibility.
7175     *
7176     * @return The parent for accessibility purposes.
7177     */
7178    public ViewParent getParentForAccessibility() {
7179        if (mParent instanceof View) {
7180            View parentView = (View) mParent;
7181            if (parentView.includeForAccessibility()) {
7182                return mParent;
7183            } else {
7184                return mParent.getParentForAccessibility();
7185            }
7186        }
7187        return null;
7188    }
7189
7190    /**
7191     * Adds the children of a given View for accessibility. Since some Views are
7192     * not important for accessibility the children for accessibility are not
7193     * necessarily direct children of the view, rather they are the first level of
7194     * descendants important for accessibility.
7195     *
7196     * @param children The list of children for accessibility.
7197     */
7198    public void addChildrenForAccessibility(ArrayList<View> children) {
7199        if (includeForAccessibility()) {
7200            children.add(this);
7201        }
7202    }
7203
7204    /**
7205     * Whether to regard this view for accessibility. A view is regarded for
7206     * accessibility if it is important for accessibility or the querying
7207     * accessibility service has explicitly requested that view not
7208     * important for accessibility are regarded.
7209     *
7210     * @return Whether to regard the view for accessibility.
7211     *
7212     * @hide
7213     */
7214    public boolean includeForAccessibility() {
7215        //noinspection SimplifiableIfStatement
7216        if (mAttachInfo != null) {
7217            return (mAttachInfo.mAccessibilityFetchFlags
7218                    & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0
7219                    || isImportantForAccessibility();
7220        }
7221        return false;
7222    }
7223
7224    /**
7225     * Returns whether the View is considered actionable from
7226     * accessibility perspective. Such view are important for
7227     * accessibility.
7228     *
7229     * @return True if the view is actionable for accessibility.
7230     *
7231     * @hide
7232     */
7233    public boolean isActionableForAccessibility() {
7234        return (isClickable() || isLongClickable() || isFocusable());
7235    }
7236
7237    /**
7238     * Returns whether the View has registered callbacks wich makes it
7239     * important for accessibility.
7240     *
7241     * @return True if the view is actionable for accessibility.
7242     */
7243    private boolean hasListenersForAccessibility() {
7244        ListenerInfo info = getListenerInfo();
7245        return mTouchDelegate != null || info.mOnKeyListener != null
7246                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
7247                || info.mOnHoverListener != null || info.mOnDragListener != null;
7248    }
7249
7250    /**
7251     * Notifies that the accessibility state of this view changed. The change
7252     * is local to this view and does not represent structural changes such
7253     * as children and parent. For example, the view became focusable. The
7254     * notification is at at most once every
7255     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
7256     * to avoid unnecessary load to the system. Also once a view has a pending
7257     * notifucation this method is a NOP until the notification has been sent.
7258     *
7259     * @hide
7260     */
7261    public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) {
7262        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
7263            return;
7264        }
7265        if (mSendViewStateChangedAccessibilityEvent == null) {
7266            mSendViewStateChangedAccessibilityEvent =
7267                    new SendViewStateChangedAccessibilityEvent();
7268        }
7269        mSendViewStateChangedAccessibilityEvent.runOrPost(changeType);
7270    }
7271
7272    /**
7273     * Notifies that the accessibility state of this view changed. The change
7274     * is *not* local to this view and does represent structural changes such
7275     * as children and parent. For example, the view size changed. The
7276     * notification is at at most once every
7277     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
7278     * to avoid unnecessary load to the system. Also once a view has a pending
7279     * notifucation this method is a NOP until the notification has been sent.
7280     *
7281     * @hide
7282     */
7283    public void notifySubtreeAccessibilityStateChangedIfNeeded() {
7284        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
7285            return;
7286        }
7287        if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) {
7288            mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
7289            if (mParent != null) {
7290                try {
7291                    mParent.notifySubtreeAccessibilityStateChanged(
7292                            this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
7293                } catch (AbstractMethodError e) {
7294                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
7295                            " does not fully implement ViewParent", e);
7296                }
7297            }
7298        }
7299    }
7300
7301    /**
7302     * Reset the flag indicating the accessibility state of the subtree rooted
7303     * at this view changed.
7304     */
7305    void resetSubtreeAccessibilityStateChanged() {
7306        mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
7307    }
7308
7309    /**
7310     * Performs the specified accessibility action on the view. For
7311     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
7312     * <p>
7313     * If an {@link AccessibilityDelegate} has been specified via calling
7314     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
7315     * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
7316     * is responsible for handling this call.
7317     * </p>
7318     *
7319     * @param action The action to perform.
7320     * @param arguments Optional action arguments.
7321     * @return Whether the action was performed.
7322     */
7323    public boolean performAccessibilityAction(int action, Bundle arguments) {
7324      if (mAccessibilityDelegate != null) {
7325          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
7326      } else {
7327          return performAccessibilityActionInternal(action, arguments);
7328      }
7329    }
7330
7331   /**
7332    * @see #performAccessibilityAction(int, Bundle)
7333    *
7334    * Note: Called from the default {@link AccessibilityDelegate}.
7335    */
7336    boolean performAccessibilityActionInternal(int action, Bundle arguments) {
7337        switch (action) {
7338            case AccessibilityNodeInfo.ACTION_CLICK: {
7339                if (isClickable()) {
7340                    performClick();
7341                    return true;
7342                }
7343            } break;
7344            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
7345                if (isLongClickable()) {
7346                    performLongClick();
7347                    return true;
7348                }
7349            } break;
7350            case AccessibilityNodeInfo.ACTION_FOCUS: {
7351                if (!hasFocus()) {
7352                    // Get out of touch mode since accessibility
7353                    // wants to move focus around.
7354                    getViewRootImpl().ensureTouchMode(false);
7355                    return requestFocus();
7356                }
7357            } break;
7358            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
7359                if (hasFocus()) {
7360                    clearFocus();
7361                    return !isFocused();
7362                }
7363            } break;
7364            case AccessibilityNodeInfo.ACTION_SELECT: {
7365                if (!isSelected()) {
7366                    setSelected(true);
7367                    return isSelected();
7368                }
7369            } break;
7370            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
7371                if (isSelected()) {
7372                    setSelected(false);
7373                    return !isSelected();
7374                }
7375            } break;
7376            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
7377                if (!isAccessibilityFocused()) {
7378                    return requestAccessibilityFocus();
7379                }
7380            } break;
7381            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
7382                if (isAccessibilityFocused()) {
7383                    clearAccessibilityFocus();
7384                    return true;
7385                }
7386            } break;
7387            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
7388                if (arguments != null) {
7389                    final int granularity = arguments.getInt(
7390                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
7391                    final boolean extendSelection = arguments.getBoolean(
7392                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
7393                    return traverseAtGranularity(granularity, true, extendSelection);
7394                }
7395            } break;
7396            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
7397                if (arguments != null) {
7398                    final int granularity = arguments.getInt(
7399                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
7400                    final boolean extendSelection = arguments.getBoolean(
7401                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
7402                    return traverseAtGranularity(granularity, false, extendSelection);
7403                }
7404            } break;
7405            case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
7406                CharSequence text = getIterableTextForAccessibility();
7407                if (text == null) {
7408                    return false;
7409                }
7410                final int start = (arguments != null) ? arguments.getInt(
7411                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1;
7412                final int end = (arguments != null) ? arguments.getInt(
7413                AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1;
7414                // Only cursor position can be specified (selection length == 0)
7415                if ((getAccessibilitySelectionStart() != start
7416                        || getAccessibilitySelectionEnd() != end)
7417                        && (start == end)) {
7418                    setAccessibilitySelection(start, end);
7419                    notifyViewAccessibilityStateChangedIfNeeded(
7420                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7421                    return true;
7422                }
7423            } break;
7424        }
7425        return false;
7426    }
7427
7428    private boolean traverseAtGranularity(int granularity, boolean forward,
7429            boolean extendSelection) {
7430        CharSequence text = getIterableTextForAccessibility();
7431        if (text == null || text.length() == 0) {
7432            return false;
7433        }
7434        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
7435        if (iterator == null) {
7436            return false;
7437        }
7438        int current = getAccessibilitySelectionEnd();
7439        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7440            current = forward ? 0 : text.length();
7441        }
7442        final int[] range = forward ? iterator.following(current) : iterator.preceding(current);
7443        if (range == null) {
7444            return false;
7445        }
7446        final int segmentStart = range[0];
7447        final int segmentEnd = range[1];
7448        int selectionStart;
7449        int selectionEnd;
7450        if (extendSelection && isAccessibilitySelectionExtendable()) {
7451            selectionStart = getAccessibilitySelectionStart();
7452            if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7453                selectionStart = forward ? segmentStart : segmentEnd;
7454            }
7455            selectionEnd = forward ? segmentEnd : segmentStart;
7456        } else {
7457            selectionStart = selectionEnd= forward ? segmentEnd : segmentStart;
7458        }
7459        setAccessibilitySelection(selectionStart, selectionEnd);
7460        final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY
7461                : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY;
7462        sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd);
7463        return true;
7464    }
7465
7466    /**
7467     * Gets the text reported for accessibility purposes.
7468     *
7469     * @return The accessibility text.
7470     *
7471     * @hide
7472     */
7473    public CharSequence getIterableTextForAccessibility() {
7474        return getContentDescription();
7475    }
7476
7477    /**
7478     * Gets whether accessibility selection can be extended.
7479     *
7480     * @return If selection is extensible.
7481     *
7482     * @hide
7483     */
7484    public boolean isAccessibilitySelectionExtendable() {
7485        return false;
7486    }
7487
7488    /**
7489     * @hide
7490     */
7491    public int getAccessibilitySelectionStart() {
7492        return mAccessibilityCursorPosition;
7493    }
7494
7495    /**
7496     * @hide
7497     */
7498    public int getAccessibilitySelectionEnd() {
7499        return getAccessibilitySelectionStart();
7500    }
7501
7502    /**
7503     * @hide
7504     */
7505    public void setAccessibilitySelection(int start, int end) {
7506        if (start ==  end && end == mAccessibilityCursorPosition) {
7507            return;
7508        }
7509        if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) {
7510            mAccessibilityCursorPosition = start;
7511        } else {
7512            mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
7513        }
7514        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
7515    }
7516
7517    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
7518            int fromIndex, int toIndex) {
7519        if (mParent == null) {
7520            return;
7521        }
7522        AccessibilityEvent event = AccessibilityEvent.obtain(
7523                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
7524        onInitializeAccessibilityEvent(event);
7525        onPopulateAccessibilityEvent(event);
7526        event.setFromIndex(fromIndex);
7527        event.setToIndex(toIndex);
7528        event.setAction(action);
7529        event.setMovementGranularity(granularity);
7530        mParent.requestSendAccessibilityEvent(this, event);
7531    }
7532
7533    /**
7534     * @hide
7535     */
7536    public TextSegmentIterator getIteratorForGranularity(int granularity) {
7537        switch (granularity) {
7538            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
7539                CharSequence text = getIterableTextForAccessibility();
7540                if (text != null && text.length() > 0) {
7541                    CharacterTextSegmentIterator iterator =
7542                        CharacterTextSegmentIterator.getInstance(
7543                                mContext.getResources().getConfiguration().locale);
7544                    iterator.initialize(text.toString());
7545                    return iterator;
7546                }
7547            } break;
7548            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
7549                CharSequence text = getIterableTextForAccessibility();
7550                if (text != null && text.length() > 0) {
7551                    WordTextSegmentIterator iterator =
7552                        WordTextSegmentIterator.getInstance(
7553                                mContext.getResources().getConfiguration().locale);
7554                    iterator.initialize(text.toString());
7555                    return iterator;
7556                }
7557            } break;
7558            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
7559                CharSequence text = getIterableTextForAccessibility();
7560                if (text != null && text.length() > 0) {
7561                    ParagraphTextSegmentIterator iterator =
7562                        ParagraphTextSegmentIterator.getInstance();
7563                    iterator.initialize(text.toString());
7564                    return iterator;
7565                }
7566            } break;
7567        }
7568        return null;
7569    }
7570
7571    /**
7572     * @hide
7573     */
7574    public void dispatchStartTemporaryDetach() {
7575        clearDisplayList();
7576
7577        onStartTemporaryDetach();
7578    }
7579
7580    /**
7581     * This is called when a container is going to temporarily detach a child, with
7582     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
7583     * It will either be followed by {@link #onFinishTemporaryDetach()} or
7584     * {@link #onDetachedFromWindow()} when the container is done.
7585     */
7586    public void onStartTemporaryDetach() {
7587        removeUnsetPressCallback();
7588        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
7589    }
7590
7591    /**
7592     * @hide
7593     */
7594    public void dispatchFinishTemporaryDetach() {
7595        onFinishTemporaryDetach();
7596    }
7597
7598    /**
7599     * Called after {@link #onStartTemporaryDetach} when the container is done
7600     * changing the view.
7601     */
7602    public void onFinishTemporaryDetach() {
7603    }
7604
7605    /**
7606     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
7607     * for this view's window.  Returns null if the view is not currently attached
7608     * to the window.  Normally you will not need to use this directly, but
7609     * just use the standard high-level event callbacks like
7610     * {@link #onKeyDown(int, KeyEvent)}.
7611     */
7612    public KeyEvent.DispatcherState getKeyDispatcherState() {
7613        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
7614    }
7615
7616    /**
7617     * Dispatch a key event before it is processed by any input method
7618     * associated with the view hierarchy.  This can be used to intercept
7619     * key events in special situations before the IME consumes them; a
7620     * typical example would be handling the BACK key to update the application's
7621     * UI instead of allowing the IME to see it and close itself.
7622     *
7623     * @param event The key event to be dispatched.
7624     * @return True if the event was handled, false otherwise.
7625     */
7626    public boolean dispatchKeyEventPreIme(KeyEvent event) {
7627        return onKeyPreIme(event.getKeyCode(), event);
7628    }
7629
7630    /**
7631     * Dispatch a key event to the next view on the focus path. This path runs
7632     * from the top of the view tree down to the currently focused view. If this
7633     * view has focus, it will dispatch to itself. Otherwise it will dispatch
7634     * the next node down the focus path. This method also fires any key
7635     * listeners.
7636     *
7637     * @param event The key event to be dispatched.
7638     * @return True if the event was handled, false otherwise.
7639     */
7640    public boolean dispatchKeyEvent(KeyEvent event) {
7641        if (mInputEventConsistencyVerifier != null) {
7642            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
7643        }
7644
7645        // Give any attached key listener a first crack at the event.
7646        //noinspection SimplifiableIfStatement
7647        ListenerInfo li = mListenerInfo;
7648        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
7649                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
7650            return true;
7651        }
7652
7653        if (event.dispatch(this, mAttachInfo != null
7654                ? mAttachInfo.mKeyDispatchState : null, this)) {
7655            return true;
7656        }
7657
7658        if (mInputEventConsistencyVerifier != null) {
7659            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7660        }
7661        return false;
7662    }
7663
7664    /**
7665     * Dispatches a key shortcut event.
7666     *
7667     * @param event The key event to be dispatched.
7668     * @return True if the event was handled by the view, false otherwise.
7669     */
7670    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
7671        return onKeyShortcut(event.getKeyCode(), event);
7672    }
7673
7674    /**
7675     * Pass the touch screen motion event down to the target view, or this
7676     * view if it is the target.
7677     *
7678     * @param event The motion event to be dispatched.
7679     * @return True if the event was handled by the view, false otherwise.
7680     */
7681    public boolean dispatchTouchEvent(MotionEvent event) {
7682        if (mInputEventConsistencyVerifier != null) {
7683            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
7684        }
7685
7686        if (onFilterTouchEventForSecurity(event)) {
7687            //noinspection SimplifiableIfStatement
7688            ListenerInfo li = mListenerInfo;
7689            if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
7690                    && li.mOnTouchListener.onTouch(this, event)) {
7691                return true;
7692            }
7693
7694            if (onTouchEvent(event)) {
7695                return true;
7696            }
7697        }
7698
7699        if (mInputEventConsistencyVerifier != null) {
7700            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7701        }
7702        return false;
7703    }
7704
7705    /**
7706     * Filter the touch event to apply security policies.
7707     *
7708     * @param event The motion event to be filtered.
7709     * @return True if the event should be dispatched, false if the event should be dropped.
7710     *
7711     * @see #getFilterTouchesWhenObscured
7712     */
7713    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
7714        //noinspection RedundantIfStatement
7715        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
7716                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
7717            // Window is obscured, drop this touch.
7718            return false;
7719        }
7720        return true;
7721    }
7722
7723    /**
7724     * Pass a trackball motion event down to the focused view.
7725     *
7726     * @param event The motion event to be dispatched.
7727     * @return True if the event was handled by the view, false otherwise.
7728     */
7729    public boolean dispatchTrackballEvent(MotionEvent event) {
7730        if (mInputEventConsistencyVerifier != null) {
7731            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
7732        }
7733
7734        return onTrackballEvent(event);
7735    }
7736
7737    /**
7738     * Dispatch a generic motion event.
7739     * <p>
7740     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
7741     * are delivered to the view under the pointer.  All other generic motion events are
7742     * delivered to the focused view.  Hover events are handled specially and are delivered
7743     * to {@link #onHoverEvent(MotionEvent)}.
7744     * </p>
7745     *
7746     * @param event The motion event to be dispatched.
7747     * @return True if the event was handled by the view, false otherwise.
7748     */
7749    public boolean dispatchGenericMotionEvent(MotionEvent event) {
7750        if (mInputEventConsistencyVerifier != null) {
7751            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
7752        }
7753
7754        final int source = event.getSource();
7755        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
7756            final int action = event.getAction();
7757            if (action == MotionEvent.ACTION_HOVER_ENTER
7758                    || action == MotionEvent.ACTION_HOVER_MOVE
7759                    || action == MotionEvent.ACTION_HOVER_EXIT) {
7760                if (dispatchHoverEvent(event)) {
7761                    return true;
7762                }
7763            } else if (dispatchGenericPointerEvent(event)) {
7764                return true;
7765            }
7766        } else if (dispatchGenericFocusedEvent(event)) {
7767            return true;
7768        }
7769
7770        if (dispatchGenericMotionEventInternal(event)) {
7771            return true;
7772        }
7773
7774        if (mInputEventConsistencyVerifier != null) {
7775            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7776        }
7777        return false;
7778    }
7779
7780    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
7781        //noinspection SimplifiableIfStatement
7782        ListenerInfo li = mListenerInfo;
7783        if (li != null && li.mOnGenericMotionListener != null
7784                && (mViewFlags & ENABLED_MASK) == ENABLED
7785                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
7786            return true;
7787        }
7788
7789        if (onGenericMotionEvent(event)) {
7790            return true;
7791        }
7792
7793        if (mInputEventConsistencyVerifier != null) {
7794            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7795        }
7796        return false;
7797    }
7798
7799    /**
7800     * Dispatch a hover event.
7801     * <p>
7802     * Do not call this method directly.
7803     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7804     * </p>
7805     *
7806     * @param event The motion event to be dispatched.
7807     * @return True if the event was handled by the view, false otherwise.
7808     */
7809    protected boolean dispatchHoverEvent(MotionEvent event) {
7810        ListenerInfo li = mListenerInfo;
7811        //noinspection SimplifiableIfStatement
7812        if (li != null && li.mOnHoverListener != null
7813                && (mViewFlags & ENABLED_MASK) == ENABLED
7814                && li.mOnHoverListener.onHover(this, event)) {
7815            return true;
7816        }
7817
7818        return onHoverEvent(event);
7819    }
7820
7821    /**
7822     * Returns true if the view has a child to which it has recently sent
7823     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
7824     * it does not have a hovered child, then it must be the innermost hovered view.
7825     * @hide
7826     */
7827    protected boolean hasHoveredChild() {
7828        return false;
7829    }
7830
7831    /**
7832     * Dispatch a generic motion event to the view under the first pointer.
7833     * <p>
7834     * Do not call this method directly.
7835     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7836     * </p>
7837     *
7838     * @param event The motion event to be dispatched.
7839     * @return True if the event was handled by the view, false otherwise.
7840     */
7841    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
7842        return false;
7843    }
7844
7845    /**
7846     * Dispatch a generic motion event to the currently focused view.
7847     * <p>
7848     * Do not call this method directly.
7849     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7850     * </p>
7851     *
7852     * @param event The motion event to be dispatched.
7853     * @return True if the event was handled by the view, false otherwise.
7854     */
7855    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
7856        return false;
7857    }
7858
7859    /**
7860     * Dispatch a pointer event.
7861     * <p>
7862     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
7863     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
7864     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
7865     * and should not be expected to handle other pointing device features.
7866     * </p>
7867     *
7868     * @param event The motion event to be dispatched.
7869     * @return True if the event was handled by the view, false otherwise.
7870     * @hide
7871     */
7872    public final boolean dispatchPointerEvent(MotionEvent event) {
7873        if (event.isTouchEvent()) {
7874            return dispatchTouchEvent(event);
7875        } else {
7876            return dispatchGenericMotionEvent(event);
7877        }
7878    }
7879
7880    /**
7881     * Called when the window containing this view gains or loses window focus.
7882     * ViewGroups should override to route to their children.
7883     *
7884     * @param hasFocus True if the window containing this view now has focus,
7885     *        false otherwise.
7886     */
7887    public void dispatchWindowFocusChanged(boolean hasFocus) {
7888        onWindowFocusChanged(hasFocus);
7889    }
7890
7891    /**
7892     * Called when the window containing this view gains or loses focus.  Note
7893     * that this is separate from view focus: to receive key events, both
7894     * your view and its window must have focus.  If a window is displayed
7895     * on top of yours that takes input focus, then your own window will lose
7896     * focus but the view focus will remain unchanged.
7897     *
7898     * @param hasWindowFocus True if the window containing this view now has
7899     *        focus, false otherwise.
7900     */
7901    public void onWindowFocusChanged(boolean hasWindowFocus) {
7902        InputMethodManager imm = InputMethodManager.peekInstance();
7903        if (!hasWindowFocus) {
7904            if (isPressed()) {
7905                setPressed(false);
7906            }
7907            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
7908                imm.focusOut(this);
7909            }
7910            removeLongPressCallback();
7911            removeTapCallback();
7912            onFocusLost();
7913        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
7914            imm.focusIn(this);
7915        }
7916        refreshDrawableState();
7917    }
7918
7919    /**
7920     * Returns true if this view is in a window that currently has window focus.
7921     * Note that this is not the same as the view itself having focus.
7922     *
7923     * @return True if this view is in a window that currently has window focus.
7924     */
7925    public boolean hasWindowFocus() {
7926        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
7927    }
7928
7929    /**
7930     * Dispatch a view visibility change down the view hierarchy.
7931     * ViewGroups should override to route to their children.
7932     * @param changedView The view whose visibility changed. Could be 'this' or
7933     * an ancestor view.
7934     * @param visibility The new visibility of changedView: {@link #VISIBLE},
7935     * {@link #INVISIBLE} or {@link #GONE}.
7936     */
7937    protected void dispatchVisibilityChanged(View changedView, int visibility) {
7938        onVisibilityChanged(changedView, visibility);
7939    }
7940
7941    /**
7942     * Called when the visibility of the view or an ancestor of the view is changed.
7943     * @param changedView The view whose visibility changed. Could be 'this' or
7944     * an ancestor view.
7945     * @param visibility The new visibility of changedView: {@link #VISIBLE},
7946     * {@link #INVISIBLE} or {@link #GONE}.
7947     */
7948    protected void onVisibilityChanged(View changedView, int visibility) {
7949        if (visibility == VISIBLE) {
7950            if (mAttachInfo != null) {
7951                initialAwakenScrollBars();
7952            } else {
7953                mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
7954            }
7955        }
7956    }
7957
7958    /**
7959     * Dispatch a hint about whether this view is displayed. For instance, when
7960     * a View moves out of the screen, it might receives a display hint indicating
7961     * the view is not displayed. Applications should not <em>rely</em> on this hint
7962     * as there is no guarantee that they will receive one.
7963     *
7964     * @param hint A hint about whether or not this view is displayed:
7965     * {@link #VISIBLE} or {@link #INVISIBLE}.
7966     */
7967    public void dispatchDisplayHint(int hint) {
7968        onDisplayHint(hint);
7969    }
7970
7971    /**
7972     * Gives this view a hint about whether is displayed or not. For instance, when
7973     * a View moves out of the screen, it might receives a display hint indicating
7974     * the view is not displayed. Applications should not <em>rely</em> on this hint
7975     * as there is no guarantee that they will receive one.
7976     *
7977     * @param hint A hint about whether or not this view is displayed:
7978     * {@link #VISIBLE} or {@link #INVISIBLE}.
7979     */
7980    protected void onDisplayHint(int hint) {
7981    }
7982
7983    /**
7984     * Dispatch a window visibility change down the view hierarchy.
7985     * ViewGroups should override to route to their children.
7986     *
7987     * @param visibility The new visibility of the window.
7988     *
7989     * @see #onWindowVisibilityChanged(int)
7990     */
7991    public void dispatchWindowVisibilityChanged(int visibility) {
7992        onWindowVisibilityChanged(visibility);
7993    }
7994
7995    /**
7996     * Called when the window containing has change its visibility
7997     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
7998     * that this tells you whether or not your window is being made visible
7999     * to the window manager; this does <em>not</em> tell you whether or not
8000     * your window is obscured by other windows on the screen, even if it
8001     * is itself visible.
8002     *
8003     * @param visibility The new visibility of the window.
8004     */
8005    protected void onWindowVisibilityChanged(int visibility) {
8006        if (visibility == VISIBLE) {
8007            initialAwakenScrollBars();
8008        }
8009    }
8010
8011    /**
8012     * Returns the current visibility of the window this view is attached to
8013     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
8014     *
8015     * @return Returns the current visibility of the view's window.
8016     */
8017    public int getWindowVisibility() {
8018        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
8019    }
8020
8021    /**
8022     * Retrieve the overall visible display size in which the window this view is
8023     * attached to has been positioned in.  This takes into account screen
8024     * decorations above the window, for both cases where the window itself
8025     * is being position inside of them or the window is being placed under
8026     * then and covered insets are used for the window to position its content
8027     * inside.  In effect, this tells you the available area where content can
8028     * be placed and remain visible to users.
8029     *
8030     * <p>This function requires an IPC back to the window manager to retrieve
8031     * the requested information, so should not be used in performance critical
8032     * code like drawing.
8033     *
8034     * @param outRect Filled in with the visible display frame.  If the view
8035     * is not attached to a window, this is simply the raw display size.
8036     */
8037    public void getWindowVisibleDisplayFrame(Rect outRect) {
8038        if (mAttachInfo != null) {
8039            try {
8040                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
8041            } catch (RemoteException e) {
8042                return;
8043            }
8044            // XXX This is really broken, and probably all needs to be done
8045            // in the window manager, and we need to know more about whether
8046            // we want the area behind or in front of the IME.
8047            final Rect insets = mAttachInfo.mVisibleInsets;
8048            outRect.left += insets.left;
8049            outRect.top += insets.top;
8050            outRect.right -= insets.right;
8051            outRect.bottom -= insets.bottom;
8052            return;
8053        }
8054        // The view is not attached to a display so we don't have a context.
8055        // Make a best guess about the display size.
8056        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
8057        d.getRectSize(outRect);
8058    }
8059
8060    /**
8061     * Dispatch a notification about a resource configuration change down
8062     * the view hierarchy.
8063     * ViewGroups should override to route to their children.
8064     *
8065     * @param newConfig The new resource configuration.
8066     *
8067     * @see #onConfigurationChanged(android.content.res.Configuration)
8068     */
8069    public void dispatchConfigurationChanged(Configuration newConfig) {
8070        onConfigurationChanged(newConfig);
8071    }
8072
8073    /**
8074     * Called when the current configuration of the resources being used
8075     * by the application have changed.  You can use this to decide when
8076     * to reload resources that can changed based on orientation and other
8077     * configuration characterstics.  You only need to use this if you are
8078     * not relying on the normal {@link android.app.Activity} mechanism of
8079     * recreating the activity instance upon a configuration change.
8080     *
8081     * @param newConfig The new resource configuration.
8082     */
8083    protected void onConfigurationChanged(Configuration newConfig) {
8084    }
8085
8086    /**
8087     * Private function to aggregate all per-view attributes in to the view
8088     * root.
8089     */
8090    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
8091        performCollectViewAttributes(attachInfo, visibility);
8092    }
8093
8094    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
8095        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
8096            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
8097                attachInfo.mKeepScreenOn = true;
8098            }
8099            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
8100            ListenerInfo li = mListenerInfo;
8101            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
8102                attachInfo.mHasSystemUiListeners = true;
8103            }
8104        }
8105    }
8106
8107    void needGlobalAttributesUpdate(boolean force) {
8108        final AttachInfo ai = mAttachInfo;
8109        if (ai != null && !ai.mRecomputeGlobalAttributes) {
8110            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
8111                    || ai.mHasSystemUiListeners) {
8112                ai.mRecomputeGlobalAttributes = true;
8113            }
8114        }
8115    }
8116
8117    /**
8118     * Returns whether the device is currently in touch mode.  Touch mode is entered
8119     * once the user begins interacting with the device by touch, and affects various
8120     * things like whether focus is always visible to the user.
8121     *
8122     * @return Whether the device is in touch mode.
8123     */
8124    @ViewDebug.ExportedProperty
8125    public boolean isInTouchMode() {
8126        if (mAttachInfo != null) {
8127            return mAttachInfo.mInTouchMode;
8128        } else {
8129            return ViewRootImpl.isInTouchMode();
8130        }
8131    }
8132
8133    /**
8134     * Returns the context the view is running in, through which it can
8135     * access the current theme, resources, etc.
8136     *
8137     * @return The view's Context.
8138     */
8139    @ViewDebug.CapturedViewProperty
8140    public final Context getContext() {
8141        return mContext;
8142    }
8143
8144    /**
8145     * Handle a key event before it is processed by any input method
8146     * associated with the view hierarchy.  This can be used to intercept
8147     * key events in special situations before the IME consumes them; a
8148     * typical example would be handling the BACK key to update the application's
8149     * UI instead of allowing the IME to see it and close itself.
8150     *
8151     * @param keyCode The value in event.getKeyCode().
8152     * @param event Description of the key event.
8153     * @return If you handled the event, return true. If you want to allow the
8154     *         event to be handled by the next receiver, return false.
8155     */
8156    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
8157        return false;
8158    }
8159
8160    /**
8161     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
8162     * KeyEvent.Callback.onKeyDown()}: perform press of the view
8163     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
8164     * is released, if the view is enabled and clickable.
8165     *
8166     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8167     * although some may elect to do so in some situations. Do not rely on this to
8168     * catch software key presses.
8169     *
8170     * @param keyCode A key code that represents the button pressed, from
8171     *                {@link android.view.KeyEvent}.
8172     * @param event   The KeyEvent object that defines the button action.
8173     */
8174    public boolean onKeyDown(int keyCode, KeyEvent event) {
8175        boolean result = false;
8176
8177        if (KeyEvent.isConfirmKey(keyCode)) {
8178            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
8179                return true;
8180            }
8181            // Long clickable items don't necessarily have to be clickable
8182            if (((mViewFlags & CLICKABLE) == CLICKABLE ||
8183                    (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
8184                    (event.getRepeatCount() == 0)) {
8185                setPressed(true);
8186                checkForLongClick(0);
8187                return true;
8188            }
8189        }
8190        return result;
8191    }
8192
8193    /**
8194     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
8195     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
8196     * the event).
8197     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8198     * although some may elect to do so in some situations. Do not rely on this to
8199     * catch software key presses.
8200     */
8201    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
8202        return false;
8203    }
8204
8205    /**
8206     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
8207     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
8208     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
8209     * {@link KeyEvent#KEYCODE_ENTER} is released.
8210     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8211     * although some may elect to do so in some situations. Do not rely on this to
8212     * catch software key presses.
8213     *
8214     * @param keyCode A key code that represents the button pressed, from
8215     *                {@link android.view.KeyEvent}.
8216     * @param event   The KeyEvent object that defines the button action.
8217     */
8218    public boolean onKeyUp(int keyCode, KeyEvent event) {
8219        if (KeyEvent.isConfirmKey(keyCode)) {
8220            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
8221                return true;
8222            }
8223            if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
8224                setPressed(false);
8225
8226                if (!mHasPerformedLongPress) {
8227                    // This is a tap, so remove the longpress check
8228                    removeLongPressCallback();
8229                    return performClick();
8230                }
8231            }
8232        }
8233        return false;
8234    }
8235
8236    /**
8237     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
8238     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
8239     * the event).
8240     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8241     * although some may elect to do so in some situations. Do not rely on this to
8242     * catch software key presses.
8243     *
8244     * @param keyCode     A key code that represents the button pressed, from
8245     *                    {@link android.view.KeyEvent}.
8246     * @param repeatCount The number of times the action was made.
8247     * @param event       The KeyEvent object that defines the button action.
8248     */
8249    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
8250        return false;
8251    }
8252
8253    /**
8254     * Called on the focused view when a key shortcut event is not handled.
8255     * Override this method to implement local key shortcuts for the View.
8256     * Key shortcuts can also be implemented by setting the
8257     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
8258     *
8259     * @param keyCode The value in event.getKeyCode().
8260     * @param event Description of the key event.
8261     * @return If you handled the event, return true. If you want to allow the
8262     *         event to be handled by the next receiver, return false.
8263     */
8264    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
8265        return false;
8266    }
8267
8268    /**
8269     * Check whether the called view is a text editor, in which case it
8270     * would make sense to automatically display a soft input window for
8271     * it.  Subclasses should override this if they implement
8272     * {@link #onCreateInputConnection(EditorInfo)} to return true if
8273     * a call on that method would return a non-null InputConnection, and
8274     * they are really a first-class editor that the user would normally
8275     * start typing on when the go into a window containing your view.
8276     *
8277     * <p>The default implementation always returns false.  This does
8278     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
8279     * will not be called or the user can not otherwise perform edits on your
8280     * view; it is just a hint to the system that this is not the primary
8281     * purpose of this view.
8282     *
8283     * @return Returns true if this view is a text editor, else false.
8284     */
8285    public boolean onCheckIsTextEditor() {
8286        return false;
8287    }
8288
8289    /**
8290     * Create a new InputConnection for an InputMethod to interact
8291     * with the view.  The default implementation returns null, since it doesn't
8292     * support input methods.  You can override this to implement such support.
8293     * This is only needed for views that take focus and text input.
8294     *
8295     * <p>When implementing this, you probably also want to implement
8296     * {@link #onCheckIsTextEditor()} to indicate you will return a
8297     * non-null InputConnection.
8298     *
8299     * @param outAttrs Fill in with attribute information about the connection.
8300     */
8301    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
8302        return null;
8303    }
8304
8305    /**
8306     * Called by the {@link android.view.inputmethod.InputMethodManager}
8307     * when a view who is not the current
8308     * input connection target is trying to make a call on the manager.  The
8309     * default implementation returns false; you can override this to return
8310     * true for certain views if you are performing InputConnection proxying
8311     * to them.
8312     * @param view The View that is making the InputMethodManager call.
8313     * @return Return true to allow the call, false to reject.
8314     */
8315    public boolean checkInputConnectionProxy(View view) {
8316        return false;
8317    }
8318
8319    /**
8320     * Show the context menu for this view. It is not safe to hold on to the
8321     * menu after returning from this method.
8322     *
8323     * You should normally not overload this method. Overload
8324     * {@link #onCreateContextMenu(ContextMenu)} or define an
8325     * {@link OnCreateContextMenuListener} to add items to the context menu.
8326     *
8327     * @param menu The context menu to populate
8328     */
8329    public void createContextMenu(ContextMenu menu) {
8330        ContextMenuInfo menuInfo = getContextMenuInfo();
8331
8332        // Sets the current menu info so all items added to menu will have
8333        // my extra info set.
8334        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
8335
8336        onCreateContextMenu(menu);
8337        ListenerInfo li = mListenerInfo;
8338        if (li != null && li.mOnCreateContextMenuListener != null) {
8339            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
8340        }
8341
8342        // Clear the extra information so subsequent items that aren't mine don't
8343        // have my extra info.
8344        ((MenuBuilder)menu).setCurrentMenuInfo(null);
8345
8346        if (mParent != null) {
8347            mParent.createContextMenu(menu);
8348        }
8349    }
8350
8351    /**
8352     * Views should implement this if they have extra information to associate
8353     * with the context menu. The return result is supplied as a parameter to
8354     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
8355     * callback.
8356     *
8357     * @return Extra information about the item for which the context menu
8358     *         should be shown. This information will vary across different
8359     *         subclasses of View.
8360     */
8361    protected ContextMenuInfo getContextMenuInfo() {
8362        return null;
8363    }
8364
8365    /**
8366     * Views should implement this if the view itself is going to add items to
8367     * the context menu.
8368     *
8369     * @param menu the context menu to populate
8370     */
8371    protected void onCreateContextMenu(ContextMenu menu) {
8372    }
8373
8374    /**
8375     * Implement this method to handle trackball motion events.  The
8376     * <em>relative</em> movement of the trackball since the last event
8377     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
8378     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
8379     * that a movement of 1 corresponds to the user pressing one DPAD key (so
8380     * they will often be fractional values, representing the more fine-grained
8381     * movement information available from a trackball).
8382     *
8383     * @param event The motion event.
8384     * @return True if the event was handled, false otherwise.
8385     */
8386    public boolean onTrackballEvent(MotionEvent event) {
8387        return false;
8388    }
8389
8390    /**
8391     * Implement this method to handle generic motion events.
8392     * <p>
8393     * Generic motion events describe joystick movements, mouse hovers, track pad
8394     * touches, scroll wheel movements and other input events.  The
8395     * {@link MotionEvent#getSource() source} of the motion event specifies
8396     * the class of input that was received.  Implementations of this method
8397     * must examine the bits in the source before processing the event.
8398     * The following code example shows how this is done.
8399     * </p><p>
8400     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
8401     * are delivered to the view under the pointer.  All other generic motion events are
8402     * delivered to the focused view.
8403     * </p>
8404     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
8405     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {
8406     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
8407     *             // process the joystick movement...
8408     *             return true;
8409     *         }
8410     *     }
8411     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
8412     *         switch (event.getAction()) {
8413     *             case MotionEvent.ACTION_HOVER_MOVE:
8414     *                 // process the mouse hover movement...
8415     *                 return true;
8416     *             case MotionEvent.ACTION_SCROLL:
8417     *                 // process the scroll wheel movement...
8418     *                 return true;
8419     *         }
8420     *     }
8421     *     return super.onGenericMotionEvent(event);
8422     * }</pre>
8423     *
8424     * @param event The generic motion event being processed.
8425     * @return True if the event was handled, false otherwise.
8426     */
8427    public boolean onGenericMotionEvent(MotionEvent event) {
8428        return false;
8429    }
8430
8431    /**
8432     * Implement this method to handle hover events.
8433     * <p>
8434     * This method is called whenever a pointer is hovering into, over, or out of the
8435     * bounds of a view and the view is not currently being touched.
8436     * Hover events are represented as pointer events with action
8437     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
8438     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
8439     * </p>
8440     * <ul>
8441     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
8442     * when the pointer enters the bounds of the view.</li>
8443     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
8444     * when the pointer has already entered the bounds of the view and has moved.</li>
8445     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
8446     * when the pointer has exited the bounds of the view or when the pointer is
8447     * about to go down due to a button click, tap, or similar user action that
8448     * causes the view to be touched.</li>
8449     * </ul>
8450     * <p>
8451     * The view should implement this method to return true to indicate that it is
8452     * handling the hover event, such as by changing its drawable state.
8453     * </p><p>
8454     * The default implementation calls {@link #setHovered} to update the hovered state
8455     * of the view when a hover enter or hover exit event is received, if the view
8456     * is enabled and is clickable.  The default implementation also sends hover
8457     * accessibility events.
8458     * </p>
8459     *
8460     * @param event The motion event that describes the hover.
8461     * @return True if the view handled the hover event.
8462     *
8463     * @see #isHovered
8464     * @see #setHovered
8465     * @see #onHoverChanged
8466     */
8467    public boolean onHoverEvent(MotionEvent event) {
8468        // The root view may receive hover (or touch) events that are outside the bounds of
8469        // the window.  This code ensures that we only send accessibility events for
8470        // hovers that are actually within the bounds of the root view.
8471        final int action = event.getActionMasked();
8472        if (!mSendingHoverAccessibilityEvents) {
8473            if ((action == MotionEvent.ACTION_HOVER_ENTER
8474                    || action == MotionEvent.ACTION_HOVER_MOVE)
8475                    && !hasHoveredChild()
8476                    && pointInView(event.getX(), event.getY())) {
8477                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
8478                mSendingHoverAccessibilityEvents = true;
8479            }
8480        } else {
8481            if (action == MotionEvent.ACTION_HOVER_EXIT
8482                    || (action == MotionEvent.ACTION_MOVE
8483                            && !pointInView(event.getX(), event.getY()))) {
8484                mSendingHoverAccessibilityEvents = false;
8485                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
8486                // If the window does not have input focus we take away accessibility
8487                // focus as soon as the user stop hovering over the view.
8488                if (mAttachInfo != null && !mAttachInfo.mHasWindowFocus) {
8489                    getViewRootImpl().setAccessibilityFocus(null, null);
8490                }
8491            }
8492        }
8493
8494        if (isHoverable()) {
8495            switch (action) {
8496                case MotionEvent.ACTION_HOVER_ENTER:
8497                    setHovered(true);
8498                    break;
8499                case MotionEvent.ACTION_HOVER_EXIT:
8500                    setHovered(false);
8501                    break;
8502            }
8503
8504            // Dispatch the event to onGenericMotionEvent before returning true.
8505            // This is to provide compatibility with existing applications that
8506            // handled HOVER_MOVE events in onGenericMotionEvent and that would
8507            // break because of the new default handling for hoverable views
8508            // in onHoverEvent.
8509            // Note that onGenericMotionEvent will be called by default when
8510            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
8511            dispatchGenericMotionEventInternal(event);
8512            // The event was already handled by calling setHovered(), so always
8513            // return true.
8514            return true;
8515        }
8516
8517        return false;
8518    }
8519
8520    /**
8521     * Returns true if the view should handle {@link #onHoverEvent}
8522     * by calling {@link #setHovered} to change its hovered state.
8523     *
8524     * @return True if the view is hoverable.
8525     */
8526    private boolean isHoverable() {
8527        final int viewFlags = mViewFlags;
8528        if ((viewFlags & ENABLED_MASK) == DISABLED) {
8529            return false;
8530        }
8531
8532        return (viewFlags & CLICKABLE) == CLICKABLE
8533                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
8534    }
8535
8536    /**
8537     * Returns true if the view is currently hovered.
8538     *
8539     * @return True if the view is currently hovered.
8540     *
8541     * @see #setHovered
8542     * @see #onHoverChanged
8543     */
8544    @ViewDebug.ExportedProperty
8545    public boolean isHovered() {
8546        return (mPrivateFlags & PFLAG_HOVERED) != 0;
8547    }
8548
8549    /**
8550     * Sets whether the view is currently hovered.
8551     * <p>
8552     * Calling this method also changes the drawable state of the view.  This
8553     * enables the view to react to hover by using different drawable resources
8554     * to change its appearance.
8555     * </p><p>
8556     * The {@link #onHoverChanged} method is called when the hovered state changes.
8557     * </p>
8558     *
8559     * @param hovered True if the view is hovered.
8560     *
8561     * @see #isHovered
8562     * @see #onHoverChanged
8563     */
8564    public void setHovered(boolean hovered) {
8565        if (hovered) {
8566            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
8567                mPrivateFlags |= PFLAG_HOVERED;
8568                refreshDrawableState();
8569                onHoverChanged(true);
8570            }
8571        } else {
8572            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
8573                mPrivateFlags &= ~PFLAG_HOVERED;
8574                refreshDrawableState();
8575                onHoverChanged(false);
8576            }
8577        }
8578    }
8579
8580    /**
8581     * Implement this method to handle hover state changes.
8582     * <p>
8583     * This method is called whenever the hover state changes as a result of a
8584     * call to {@link #setHovered}.
8585     * </p>
8586     *
8587     * @param hovered The current hover state, as returned by {@link #isHovered}.
8588     *
8589     * @see #isHovered
8590     * @see #setHovered
8591     */
8592    public void onHoverChanged(boolean hovered) {
8593    }
8594
8595    /**
8596     * Implement this method to handle touch screen motion events.
8597     * <p>
8598     * If this method is used to detect click actions, it is recommended that
8599     * the actions be performed by implementing and calling
8600     * {@link #performClick()}. This will ensure consistent system behavior,
8601     * including:
8602     * <ul>
8603     * <li>obeying click sound preferences
8604     * <li>dispatching OnClickListener calls
8605     * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when
8606     * accessibility features are enabled
8607     * </ul>
8608     *
8609     * @param event The motion event.
8610     * @return True if the event was handled, false otherwise.
8611     */
8612    public boolean onTouchEvent(MotionEvent event) {
8613        final int viewFlags = mViewFlags;
8614
8615        if ((viewFlags & ENABLED_MASK) == DISABLED) {
8616            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
8617                setPressed(false);
8618            }
8619            // A disabled view that is clickable still consumes the touch
8620            // events, it just doesn't respond to them.
8621            return (((viewFlags & CLICKABLE) == CLICKABLE ||
8622                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
8623        }
8624
8625        if (mTouchDelegate != null) {
8626            if (mTouchDelegate.onTouchEvent(event)) {
8627                return true;
8628            }
8629        }
8630
8631        if (((viewFlags & CLICKABLE) == CLICKABLE ||
8632                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
8633            switch (event.getAction()) {
8634                case MotionEvent.ACTION_UP:
8635                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
8636                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
8637                        // take focus if we don't have it already and we should in
8638                        // touch mode.
8639                        boolean focusTaken = false;
8640                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
8641                            focusTaken = requestFocus();
8642                        }
8643
8644                        if (prepressed) {
8645                            // The button is being released before we actually
8646                            // showed it as pressed.  Make it show the pressed
8647                            // state now (before scheduling the click) to ensure
8648                            // the user sees it.
8649                            setPressed(true);
8650                       }
8651
8652                        if (!mHasPerformedLongPress) {
8653                            // This is a tap, so remove the longpress check
8654                            removeLongPressCallback();
8655
8656                            // Only perform take click actions if we were in the pressed state
8657                            if (!focusTaken) {
8658                                // Use a Runnable and post this rather than calling
8659                                // performClick directly. This lets other visual state
8660                                // of the view update before click actions start.
8661                                if (mPerformClick == null) {
8662                                    mPerformClick = new PerformClick();
8663                                }
8664                                if (!post(mPerformClick)) {
8665                                    performClick();
8666                                }
8667                            }
8668                        }
8669
8670                        if (mUnsetPressedState == null) {
8671                            mUnsetPressedState = new UnsetPressedState();
8672                        }
8673
8674                        if (prepressed) {
8675                            postDelayed(mUnsetPressedState,
8676                                    ViewConfiguration.getPressedStateDuration());
8677                        } else if (!post(mUnsetPressedState)) {
8678                            // If the post failed, unpress right now
8679                            mUnsetPressedState.run();
8680                        }
8681                        removeTapCallback();
8682                    }
8683                    break;
8684
8685                case MotionEvent.ACTION_DOWN:
8686                    mHasPerformedLongPress = false;
8687
8688                    if (performButtonActionOnTouchDown(event)) {
8689                        break;
8690                    }
8691
8692                    // Walk up the hierarchy to determine if we're inside a scrolling container.
8693                    boolean isInScrollingContainer = isInScrollingContainer();
8694
8695                    // For views inside a scrolling container, delay the pressed feedback for
8696                    // a short period in case this is a scroll.
8697                    if (isInScrollingContainer) {
8698                        mPrivateFlags |= PFLAG_PREPRESSED;
8699                        if (mPendingCheckForTap == null) {
8700                            mPendingCheckForTap = new CheckForTap();
8701                        }
8702                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
8703                    } else {
8704                        // Not inside a scrolling container, so show the feedback right away
8705                        setPressed(true);
8706                        checkForLongClick(0);
8707                    }
8708                    break;
8709
8710                case MotionEvent.ACTION_CANCEL:
8711                    setPressed(false);
8712                    removeTapCallback();
8713                    removeLongPressCallback();
8714                    break;
8715
8716                case MotionEvent.ACTION_MOVE:
8717                    final int x = (int) event.getX();
8718                    final int y = (int) event.getY();
8719
8720                    // Be lenient about moving outside of buttons
8721                    if (!pointInView(x, y, mTouchSlop)) {
8722                        // Outside button
8723                        removeTapCallback();
8724                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
8725                            // Remove any future long press/tap checks
8726                            removeLongPressCallback();
8727
8728                            setPressed(false);
8729                        }
8730                    }
8731                    break;
8732            }
8733            return true;
8734        }
8735
8736        return false;
8737    }
8738
8739    /**
8740     * @hide
8741     */
8742    public boolean isInScrollingContainer() {
8743        ViewParent p = getParent();
8744        while (p != null && p instanceof ViewGroup) {
8745            if (((ViewGroup) p).shouldDelayChildPressedState()) {
8746                return true;
8747            }
8748            p = p.getParent();
8749        }
8750        return false;
8751    }
8752
8753    /**
8754     * Remove the longpress detection timer.
8755     */
8756    private void removeLongPressCallback() {
8757        if (mPendingCheckForLongPress != null) {
8758          removeCallbacks(mPendingCheckForLongPress);
8759        }
8760    }
8761
8762    /**
8763     * Remove the pending click action
8764     */
8765    private void removePerformClickCallback() {
8766        if (mPerformClick != null) {
8767            removeCallbacks(mPerformClick);
8768        }
8769    }
8770
8771    /**
8772     * Remove the prepress detection timer.
8773     */
8774    private void removeUnsetPressCallback() {
8775        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
8776            setPressed(false);
8777            removeCallbacks(mUnsetPressedState);
8778        }
8779    }
8780
8781    /**
8782     * Remove the tap detection timer.
8783     */
8784    private void removeTapCallback() {
8785        if (mPendingCheckForTap != null) {
8786            mPrivateFlags &= ~PFLAG_PREPRESSED;
8787            removeCallbacks(mPendingCheckForTap);
8788        }
8789    }
8790
8791    /**
8792     * Cancels a pending long press.  Your subclass can use this if you
8793     * want the context menu to come up if the user presses and holds
8794     * at the same place, but you don't want it to come up if they press
8795     * and then move around enough to cause scrolling.
8796     */
8797    public void cancelLongPress() {
8798        removeLongPressCallback();
8799
8800        /*
8801         * The prepressed state handled by the tap callback is a display
8802         * construct, but the tap callback will post a long press callback
8803         * less its own timeout. Remove it here.
8804         */
8805        removeTapCallback();
8806    }
8807
8808    /**
8809     * Remove the pending callback for sending a
8810     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
8811     */
8812    private void removeSendViewScrolledAccessibilityEventCallback() {
8813        if (mSendViewScrolledAccessibilityEvent != null) {
8814            removeCallbacks(mSendViewScrolledAccessibilityEvent);
8815            mSendViewScrolledAccessibilityEvent.mIsPending = false;
8816        }
8817    }
8818
8819    /**
8820     * Sets the TouchDelegate for this View.
8821     */
8822    public void setTouchDelegate(TouchDelegate delegate) {
8823        mTouchDelegate = delegate;
8824    }
8825
8826    /**
8827     * Gets the TouchDelegate for this View.
8828     */
8829    public TouchDelegate getTouchDelegate() {
8830        return mTouchDelegate;
8831    }
8832
8833    /**
8834     * Set flags controlling behavior of this view.
8835     *
8836     * @param flags Constant indicating the value which should be set
8837     * @param mask Constant indicating the bit range that should be changed
8838     */
8839    void setFlags(int flags, int mask) {
8840        final boolean accessibilityEnabled =
8841                AccessibilityManager.getInstance(mContext).isEnabled();
8842        final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility();
8843
8844        int old = mViewFlags;
8845        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
8846
8847        int changed = mViewFlags ^ old;
8848        if (changed == 0) {
8849            return;
8850        }
8851        int privateFlags = mPrivateFlags;
8852
8853        /* Check if the FOCUSABLE bit has changed */
8854        if (((changed & FOCUSABLE_MASK) != 0) &&
8855                ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) {
8856            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
8857                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
8858                /* Give up focus if we are no longer focusable */
8859                clearFocus();
8860            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
8861                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
8862                /*
8863                 * Tell the view system that we are now available to take focus
8864                 * if no one else already has it.
8865                 */
8866                if (mParent != null) mParent.focusableViewAvailable(this);
8867            }
8868        }
8869
8870        final int newVisibility = flags & VISIBILITY_MASK;
8871        if (newVisibility == VISIBLE) {
8872            if ((changed & VISIBILITY_MASK) != 0) {
8873                /*
8874                 * If this view is becoming visible, invalidate it in case it changed while
8875                 * it was not visible. Marking it drawn ensures that the invalidation will
8876                 * go through.
8877                 */
8878                mPrivateFlags |= PFLAG_DRAWN;
8879                invalidate(true);
8880
8881                needGlobalAttributesUpdate(true);
8882
8883                // a view becoming visible is worth notifying the parent
8884                // about in case nothing has focus.  even if this specific view
8885                // isn't focusable, it may contain something that is, so let
8886                // the root view try to give this focus if nothing else does.
8887                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
8888                    mParent.focusableViewAvailable(this);
8889                }
8890            }
8891        }
8892
8893        /* Check if the GONE bit has changed */
8894        if ((changed & GONE) != 0) {
8895            needGlobalAttributesUpdate(false);
8896            requestLayout();
8897
8898            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
8899                if (hasFocus()) clearFocus();
8900                clearAccessibilityFocus();
8901                destroyDrawingCache();
8902                if (mParent instanceof View) {
8903                    // GONE views noop invalidation, so invalidate the parent
8904                    ((View) mParent).invalidate(true);
8905                }
8906                // Mark the view drawn to ensure that it gets invalidated properly the next
8907                // time it is visible and gets invalidated
8908                mPrivateFlags |= PFLAG_DRAWN;
8909            }
8910            if (mAttachInfo != null) {
8911                mAttachInfo.mViewVisibilityChanged = true;
8912            }
8913        }
8914
8915        /* Check if the VISIBLE bit has changed */
8916        if ((changed & INVISIBLE) != 0) {
8917            needGlobalAttributesUpdate(false);
8918            /*
8919             * If this view is becoming invisible, set the DRAWN flag so that
8920             * the next invalidate() will not be skipped.
8921             */
8922            mPrivateFlags |= PFLAG_DRAWN;
8923
8924            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) {
8925                // root view becoming invisible shouldn't clear focus and accessibility focus
8926                if (getRootView() != this) {
8927                    if (hasFocus()) clearFocus();
8928                    clearAccessibilityFocus();
8929                }
8930            }
8931            if (mAttachInfo != null) {
8932                mAttachInfo.mViewVisibilityChanged = true;
8933            }
8934        }
8935
8936        if ((changed & VISIBILITY_MASK) != 0) {
8937            // If the view is invisible, cleanup its display list to free up resources
8938            if (newVisibility != VISIBLE) {
8939                cleanupDraw();
8940            }
8941
8942            if (mParent instanceof ViewGroup) {
8943                ((ViewGroup) mParent).onChildVisibilityChanged(this,
8944                        (changed & VISIBILITY_MASK), newVisibility);
8945                ((View) mParent).invalidate(true);
8946            } else if (mParent != null) {
8947                mParent.invalidateChild(this, null);
8948            }
8949            dispatchVisibilityChanged(this, newVisibility);
8950        }
8951
8952        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
8953            destroyDrawingCache();
8954        }
8955
8956        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
8957            destroyDrawingCache();
8958            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
8959            invalidateParentCaches();
8960        }
8961
8962        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
8963            destroyDrawingCache();
8964            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
8965        }
8966
8967        if ((changed & DRAW_MASK) != 0) {
8968            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
8969                if (mBackground != null) {
8970                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
8971                    mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
8972                } else {
8973                    mPrivateFlags |= PFLAG_SKIP_DRAW;
8974                }
8975            } else {
8976                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
8977            }
8978            requestLayout();
8979            invalidate(true);
8980        }
8981
8982        if ((changed & KEEP_SCREEN_ON) != 0) {
8983            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
8984                mParent.recomputeViewAttributes(this);
8985            }
8986        }
8987
8988        if (accessibilityEnabled) {
8989            if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0
8990                    || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0) {
8991                if (oldIncludeForAccessibility != includeForAccessibility()) {
8992                    notifySubtreeAccessibilityStateChangedIfNeeded();
8993                } else {
8994                    notifyViewAccessibilityStateChangedIfNeeded(
8995                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
8996                }
8997            } else if ((changed & ENABLED_MASK) != 0) {
8998                notifyViewAccessibilityStateChangedIfNeeded(
8999                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9000            }
9001        }
9002    }
9003
9004    /**
9005     * Change the view's z order in the tree, so it's on top of other sibling
9006     * views. This ordering change may affect layout, if the parent container
9007     * uses an order-dependent layout scheme (e.g., LinearLayout). Prior
9008     * to {@link android.os.Build.VERSION_CODES#KITKAT} this
9009     * method should be followed by calls to {@link #requestLayout()} and
9010     * {@link View#invalidate()} on the view's parent to force the parent to redraw
9011     * with the new child ordering.
9012     *
9013     * @see ViewGroup#bringChildToFront(View)
9014     */
9015    public void bringToFront() {
9016        if (mParent != null) {
9017            mParent.bringChildToFront(this);
9018        }
9019    }
9020
9021    /**
9022     * This is called in response to an internal scroll in this view (i.e., the
9023     * view scrolled its own contents). This is typically as a result of
9024     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
9025     * called.
9026     *
9027     * @param l Current horizontal scroll origin.
9028     * @param t Current vertical scroll origin.
9029     * @param oldl Previous horizontal scroll origin.
9030     * @param oldt Previous vertical scroll origin.
9031     */
9032    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
9033        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
9034            postSendViewScrolledAccessibilityEventCallback();
9035        }
9036
9037        mBackgroundSizeChanged = true;
9038
9039        final AttachInfo ai = mAttachInfo;
9040        if (ai != null) {
9041            ai.mViewScrollChanged = true;
9042        }
9043    }
9044
9045    /**
9046     * Interface definition for a callback to be invoked when the layout bounds of a view
9047     * changes due to layout processing.
9048     */
9049    public interface OnLayoutChangeListener {
9050        /**
9051         * Called when the layout bounds of a view changes due to layout processing.
9052         *
9053         * @param v The view whose bounds have changed.
9054         * @param left The new value of the view's left property.
9055         * @param top The new value of the view's top property.
9056         * @param right The new value of the view's right property.
9057         * @param bottom The new value of the view's bottom property.
9058         * @param oldLeft The previous value of the view's left property.
9059         * @param oldTop The previous value of the view's top property.
9060         * @param oldRight The previous value of the view's right property.
9061         * @param oldBottom The previous value of the view's bottom property.
9062         */
9063        void onLayoutChange(View v, int left, int top, int right, int bottom,
9064            int oldLeft, int oldTop, int oldRight, int oldBottom);
9065    }
9066
9067    /**
9068     * This is called during layout when the size of this view has changed. If
9069     * you were just added to the view hierarchy, you're called with the old
9070     * values of 0.
9071     *
9072     * @param w Current width of this view.
9073     * @param h Current height of this view.
9074     * @param oldw Old width of this view.
9075     * @param oldh Old height of this view.
9076     */
9077    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
9078    }
9079
9080    /**
9081     * Called by draw to draw the child views. This may be overridden
9082     * by derived classes to gain control just before its children are drawn
9083     * (but after its own view has been drawn).
9084     * @param canvas the canvas on which to draw the view
9085     */
9086    protected void dispatchDraw(Canvas canvas) {
9087
9088    }
9089
9090    /**
9091     * Gets the parent of this view. Note that the parent is a
9092     * ViewParent and not necessarily a View.
9093     *
9094     * @return Parent of this view.
9095     */
9096    public final ViewParent getParent() {
9097        return mParent;
9098    }
9099
9100    /**
9101     * Set the horizontal scrolled position of your view. This will cause a call to
9102     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9103     * invalidated.
9104     * @param value the x position to scroll to
9105     */
9106    public void setScrollX(int value) {
9107        scrollTo(value, mScrollY);
9108    }
9109
9110    /**
9111     * Set the vertical scrolled position of your view. This will cause a call to
9112     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9113     * invalidated.
9114     * @param value the y position to scroll to
9115     */
9116    public void setScrollY(int value) {
9117        scrollTo(mScrollX, value);
9118    }
9119
9120    /**
9121     * Return the scrolled left position of this view. This is the left edge of
9122     * the displayed part of your view. You do not need to draw any pixels
9123     * farther left, since those are outside of the frame of your view on
9124     * screen.
9125     *
9126     * @return The left edge of the displayed part of your view, in pixels.
9127     */
9128    public final int getScrollX() {
9129        return mScrollX;
9130    }
9131
9132    /**
9133     * Return the scrolled top position of this view. This is the top edge of
9134     * the displayed part of your view. You do not need to draw any pixels above
9135     * it, since those are outside of the frame of your view on screen.
9136     *
9137     * @return The top edge of the displayed part of your view, in pixels.
9138     */
9139    public final int getScrollY() {
9140        return mScrollY;
9141    }
9142
9143    /**
9144     * Return the width of the your view.
9145     *
9146     * @return The width of your view, in pixels.
9147     */
9148    @ViewDebug.ExportedProperty(category = "layout")
9149    public final int getWidth() {
9150        return mRight - mLeft;
9151    }
9152
9153    /**
9154     * Return the height of your view.
9155     *
9156     * @return The height of your view, in pixels.
9157     */
9158    @ViewDebug.ExportedProperty(category = "layout")
9159    public final int getHeight() {
9160        return mBottom - mTop;
9161    }
9162
9163    /**
9164     * Return the visible drawing bounds of your view. Fills in the output
9165     * rectangle with the values from getScrollX(), getScrollY(),
9166     * getWidth(), and getHeight(). These bounds do not account for any
9167     * transformation properties currently set on the view, such as
9168     * {@link #setScaleX(float)} or {@link #setRotation(float)}.
9169     *
9170     * @param outRect The (scrolled) drawing bounds of the view.
9171     */
9172    public void getDrawingRect(Rect outRect) {
9173        outRect.left = mScrollX;
9174        outRect.top = mScrollY;
9175        outRect.right = mScrollX + (mRight - mLeft);
9176        outRect.bottom = mScrollY + (mBottom - mTop);
9177    }
9178
9179    /**
9180     * Like {@link #getMeasuredWidthAndState()}, but only returns the
9181     * raw width component (that is the result is masked by
9182     * {@link #MEASURED_SIZE_MASK}).
9183     *
9184     * @return The raw measured width of this view.
9185     */
9186    public final int getMeasuredWidth() {
9187        return mMeasuredWidth & MEASURED_SIZE_MASK;
9188    }
9189
9190    /**
9191     * Return the full width measurement information for this view as computed
9192     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
9193     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
9194     * This should be used during measurement and layout calculations only. Use
9195     * {@link #getWidth()} to see how wide a view is after layout.
9196     *
9197     * @return The measured width of this view as a bit mask.
9198     */
9199    public final int getMeasuredWidthAndState() {
9200        return mMeasuredWidth;
9201    }
9202
9203    /**
9204     * Like {@link #getMeasuredHeightAndState()}, but only returns the
9205     * raw width component (that is the result is masked by
9206     * {@link #MEASURED_SIZE_MASK}).
9207     *
9208     * @return The raw measured height of this view.
9209     */
9210    public final int getMeasuredHeight() {
9211        return mMeasuredHeight & MEASURED_SIZE_MASK;
9212    }
9213
9214    /**
9215     * Return the full height measurement information for this view as computed
9216     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
9217     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
9218     * This should be used during measurement and layout calculations only. Use
9219     * {@link #getHeight()} to see how wide a view is after layout.
9220     *
9221     * @return The measured width of this view as a bit mask.
9222     */
9223    public final int getMeasuredHeightAndState() {
9224        return mMeasuredHeight;
9225    }
9226
9227    /**
9228     * Return only the state bits of {@link #getMeasuredWidthAndState()}
9229     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
9230     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
9231     * and the height component is at the shifted bits
9232     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
9233     */
9234    public final int getMeasuredState() {
9235        return (mMeasuredWidth&MEASURED_STATE_MASK)
9236                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
9237                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
9238    }
9239
9240    /**
9241     * The transform matrix of this view, which is calculated based on the current
9242     * roation, scale, and pivot properties.
9243     *
9244     * @see #getRotation()
9245     * @see #getScaleX()
9246     * @see #getScaleY()
9247     * @see #getPivotX()
9248     * @see #getPivotY()
9249     * @return The current transform matrix for the view
9250     */
9251    public Matrix getMatrix() {
9252        if (mTransformationInfo != null) {
9253            updateMatrix();
9254            return mTransformationInfo.mMatrix;
9255        }
9256        return Matrix.IDENTITY_MATRIX;
9257    }
9258
9259    /**
9260     * Utility function to determine if the value is far enough away from zero to be
9261     * considered non-zero.
9262     * @param value A floating point value to check for zero-ness
9263     * @return whether the passed-in value is far enough away from zero to be considered non-zero
9264     */
9265    private static boolean nonzero(float value) {
9266        return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
9267    }
9268
9269    /**
9270     * Returns true if the transform matrix is the identity matrix.
9271     * Recomputes the matrix if necessary.
9272     *
9273     * @return True if the transform matrix is the identity matrix, false otherwise.
9274     */
9275    final boolean hasIdentityMatrix() {
9276        if (mTransformationInfo != null) {
9277            updateMatrix();
9278            return mTransformationInfo.mMatrixIsIdentity;
9279        }
9280        return true;
9281    }
9282
9283    void ensureTransformationInfo() {
9284        if (mTransformationInfo == null) {
9285            mTransformationInfo = new TransformationInfo();
9286        }
9287    }
9288
9289    /**
9290     * Recomputes the transform matrix if necessary.
9291     */
9292    private void updateMatrix() {
9293        final TransformationInfo info = mTransformationInfo;
9294        if (info == null) {
9295            return;
9296        }
9297        if (info.mMatrixDirty) {
9298            // transform-related properties have changed since the last time someone
9299            // asked for the matrix; recalculate it with the current values
9300
9301            // Figure out if we need to update the pivot point
9302            if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9303                if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) {
9304                    info.mPrevWidth = mRight - mLeft;
9305                    info.mPrevHeight = mBottom - mTop;
9306                    info.mPivotX = info.mPrevWidth / 2f;
9307                    info.mPivotY = info.mPrevHeight / 2f;
9308                }
9309            }
9310            info.mMatrix.reset();
9311            if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) {
9312                info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY);
9313                info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY);
9314                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
9315            } else {
9316                if (info.mCamera == null) {
9317                    info.mCamera = new Camera();
9318                    info.matrix3D = new Matrix();
9319                }
9320                info.mCamera.save();
9321                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
9322                info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation);
9323                info.mCamera.getMatrix(info.matrix3D);
9324                info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY);
9325                info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX,
9326                        info.mPivotY + info.mTranslationY);
9327                info.mMatrix.postConcat(info.matrix3D);
9328                info.mCamera.restore();
9329            }
9330            info.mMatrixDirty = false;
9331            info.mMatrixIsIdentity = info.mMatrix.isIdentity();
9332            info.mInverseMatrixDirty = true;
9333        }
9334    }
9335
9336   /**
9337     * Utility method to retrieve the inverse of the current mMatrix property.
9338     * We cache the matrix to avoid recalculating it when transform properties
9339     * have not changed.
9340     *
9341     * @return The inverse of the current matrix of this view.
9342     */
9343    final Matrix getInverseMatrix() {
9344        final TransformationInfo info = mTransformationInfo;
9345        if (info != null) {
9346            updateMatrix();
9347            if (info.mInverseMatrixDirty) {
9348                if (info.mInverseMatrix == null) {
9349                    info.mInverseMatrix = new Matrix();
9350                }
9351                info.mMatrix.invert(info.mInverseMatrix);
9352                info.mInverseMatrixDirty = false;
9353            }
9354            return info.mInverseMatrix;
9355        }
9356        return Matrix.IDENTITY_MATRIX;
9357    }
9358
9359    /**
9360     * Gets the distance along the Z axis from the camera to this view.
9361     *
9362     * @see #setCameraDistance(float)
9363     *
9364     * @return The distance along the Z axis.
9365     */
9366    public float getCameraDistance() {
9367        ensureTransformationInfo();
9368        final float dpi = mResources.getDisplayMetrics().densityDpi;
9369        final TransformationInfo info = mTransformationInfo;
9370        if (info.mCamera == null) {
9371            info.mCamera = new Camera();
9372            info.matrix3D = new Matrix();
9373        }
9374        return -(info.mCamera.getLocationZ() * dpi);
9375    }
9376
9377    /**
9378     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
9379     * views are drawn) from the camera to this view. The camera's distance
9380     * affects 3D transformations, for instance rotations around the X and Y
9381     * axis. If the rotationX or rotationY properties are changed and this view is
9382     * large (more than half the size of the screen), it is recommended to always
9383     * use a camera distance that's greater than the height (X axis rotation) or
9384     * the width (Y axis rotation) of this view.</p>
9385     *
9386     * <p>The distance of the camera from the view plane can have an affect on the
9387     * perspective distortion of the view when it is rotated around the x or y axis.
9388     * For example, a large distance will result in a large viewing angle, and there
9389     * will not be much perspective distortion of the view as it rotates. A short
9390     * distance may cause much more perspective distortion upon rotation, and can
9391     * also result in some drawing artifacts if the rotated view ends up partially
9392     * behind the camera (which is why the recommendation is to use a distance at
9393     * least as far as the size of the view, if the view is to be rotated.)</p>
9394     *
9395     * <p>The distance is expressed in "depth pixels." The default distance depends
9396     * on the screen density. For instance, on a medium density display, the
9397     * default distance is 1280. On a high density display, the default distance
9398     * is 1920.</p>
9399     *
9400     * <p>If you want to specify a distance that leads to visually consistent
9401     * results across various densities, use the following formula:</p>
9402     * <pre>
9403     * float scale = context.getResources().getDisplayMetrics().density;
9404     * view.setCameraDistance(distance * scale);
9405     * </pre>
9406     *
9407     * <p>The density scale factor of a high density display is 1.5,
9408     * and 1920 = 1280 * 1.5.</p>
9409     *
9410     * @param distance The distance in "depth pixels", if negative the opposite
9411     *        value is used
9412     *
9413     * @see #setRotationX(float)
9414     * @see #setRotationY(float)
9415     */
9416    public void setCameraDistance(float distance) {
9417        invalidateViewProperty(true, false);
9418
9419        ensureTransformationInfo();
9420        final float dpi = mResources.getDisplayMetrics().densityDpi;
9421        final TransformationInfo info = mTransformationInfo;
9422        if (info.mCamera == null) {
9423            info.mCamera = new Camera();
9424            info.matrix3D = new Matrix();
9425        }
9426
9427        info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi);
9428        info.mMatrixDirty = true;
9429
9430        invalidateViewProperty(false, false);
9431        if (mDisplayList != null) {
9432            mDisplayList.setCameraDistance(-Math.abs(distance) / dpi);
9433        }
9434        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9435            // View was rejected last time it was drawn by its parent; this may have changed
9436            invalidateParentIfNeeded();
9437        }
9438    }
9439
9440    /**
9441     * The degrees that the view is rotated around the pivot point.
9442     *
9443     * @see #setRotation(float)
9444     * @see #getPivotX()
9445     * @see #getPivotY()
9446     *
9447     * @return The degrees of rotation.
9448     */
9449    @ViewDebug.ExportedProperty(category = "drawing")
9450    public float getRotation() {
9451        return mTransformationInfo != null ? mTransformationInfo.mRotation : 0;
9452    }
9453
9454    /**
9455     * Sets the degrees that the view is rotated around the pivot point. Increasing values
9456     * result in clockwise rotation.
9457     *
9458     * @param rotation The degrees of rotation.
9459     *
9460     * @see #getRotation()
9461     * @see #getPivotX()
9462     * @see #getPivotY()
9463     * @see #setRotationX(float)
9464     * @see #setRotationY(float)
9465     *
9466     * @attr ref android.R.styleable#View_rotation
9467     */
9468    public void setRotation(float rotation) {
9469        ensureTransformationInfo();
9470        final TransformationInfo info = mTransformationInfo;
9471        if (info.mRotation != rotation) {
9472            // Double-invalidation is necessary to capture view's old and new areas
9473            invalidateViewProperty(true, false);
9474            info.mRotation = rotation;
9475            info.mMatrixDirty = true;
9476            invalidateViewProperty(false, true);
9477            if (mDisplayList != null) {
9478                mDisplayList.setRotation(rotation);
9479            }
9480            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9481                // View was rejected last time it was drawn by its parent; this may have changed
9482                invalidateParentIfNeeded();
9483            }
9484        }
9485    }
9486
9487    /**
9488     * The degrees that the view is rotated around the vertical axis through the pivot point.
9489     *
9490     * @see #getPivotX()
9491     * @see #getPivotY()
9492     * @see #setRotationY(float)
9493     *
9494     * @return The degrees of Y rotation.
9495     */
9496    @ViewDebug.ExportedProperty(category = "drawing")
9497    public float getRotationY() {
9498        return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0;
9499    }
9500
9501    /**
9502     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
9503     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
9504     * down the y axis.
9505     *
9506     * When rotating large views, it is recommended to adjust the camera distance
9507     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
9508     *
9509     * @param rotationY The degrees of Y rotation.
9510     *
9511     * @see #getRotationY()
9512     * @see #getPivotX()
9513     * @see #getPivotY()
9514     * @see #setRotation(float)
9515     * @see #setRotationX(float)
9516     * @see #setCameraDistance(float)
9517     *
9518     * @attr ref android.R.styleable#View_rotationY
9519     */
9520    public void setRotationY(float rotationY) {
9521        ensureTransformationInfo();
9522        final TransformationInfo info = mTransformationInfo;
9523        if (info.mRotationY != rotationY) {
9524            invalidateViewProperty(true, false);
9525            info.mRotationY = rotationY;
9526            info.mMatrixDirty = true;
9527            invalidateViewProperty(false, true);
9528            if (mDisplayList != null) {
9529                mDisplayList.setRotationY(rotationY);
9530            }
9531            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9532                // View was rejected last time it was drawn by its parent; this may have changed
9533                invalidateParentIfNeeded();
9534            }
9535        }
9536    }
9537
9538    /**
9539     * The degrees that the view is rotated around the horizontal axis through the pivot point.
9540     *
9541     * @see #getPivotX()
9542     * @see #getPivotY()
9543     * @see #setRotationX(float)
9544     *
9545     * @return The degrees of X rotation.
9546     */
9547    @ViewDebug.ExportedProperty(category = "drawing")
9548    public float getRotationX() {
9549        return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0;
9550    }
9551
9552    /**
9553     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
9554     * Increasing values result in clockwise rotation from the viewpoint of looking down the
9555     * x axis.
9556     *
9557     * When rotating large views, it is recommended to adjust the camera distance
9558     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
9559     *
9560     * @param rotationX The degrees of X rotation.
9561     *
9562     * @see #getRotationX()
9563     * @see #getPivotX()
9564     * @see #getPivotY()
9565     * @see #setRotation(float)
9566     * @see #setRotationY(float)
9567     * @see #setCameraDistance(float)
9568     *
9569     * @attr ref android.R.styleable#View_rotationX
9570     */
9571    public void setRotationX(float rotationX) {
9572        ensureTransformationInfo();
9573        final TransformationInfo info = mTransformationInfo;
9574        if (info.mRotationX != rotationX) {
9575            invalidateViewProperty(true, false);
9576            info.mRotationX = rotationX;
9577            info.mMatrixDirty = true;
9578            invalidateViewProperty(false, true);
9579            if (mDisplayList != null) {
9580                mDisplayList.setRotationX(rotationX);
9581            }
9582            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9583                // View was rejected last time it was drawn by its parent; this may have changed
9584                invalidateParentIfNeeded();
9585            }
9586        }
9587    }
9588
9589    /**
9590     * The amount that the view is scaled in x around the pivot point, as a proportion of
9591     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
9592     *
9593     * <p>By default, this is 1.0f.
9594     *
9595     * @see #getPivotX()
9596     * @see #getPivotY()
9597     * @return The scaling factor.
9598     */
9599    @ViewDebug.ExportedProperty(category = "drawing")
9600    public float getScaleX() {
9601        return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1;
9602    }
9603
9604    /**
9605     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
9606     * the view's unscaled width. A value of 1 means that no scaling is applied.
9607     *
9608     * @param scaleX The scaling factor.
9609     * @see #getPivotX()
9610     * @see #getPivotY()
9611     *
9612     * @attr ref android.R.styleable#View_scaleX
9613     */
9614    public void setScaleX(float scaleX) {
9615        ensureTransformationInfo();
9616        final TransformationInfo info = mTransformationInfo;
9617        if (info.mScaleX != scaleX) {
9618            invalidateViewProperty(true, false);
9619            info.mScaleX = scaleX;
9620            info.mMatrixDirty = true;
9621            invalidateViewProperty(false, true);
9622            if (mDisplayList != null) {
9623                mDisplayList.setScaleX(scaleX);
9624            }
9625            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9626                // View was rejected last time it was drawn by its parent; this may have changed
9627                invalidateParentIfNeeded();
9628            }
9629        }
9630    }
9631
9632    /**
9633     * The amount that the view is scaled in y around the pivot point, as a proportion of
9634     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
9635     *
9636     * <p>By default, this is 1.0f.
9637     *
9638     * @see #getPivotX()
9639     * @see #getPivotY()
9640     * @return The scaling factor.
9641     */
9642    @ViewDebug.ExportedProperty(category = "drawing")
9643    public float getScaleY() {
9644        return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1;
9645    }
9646
9647    /**
9648     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
9649     * the view's unscaled width. A value of 1 means that no scaling is applied.
9650     *
9651     * @param scaleY The scaling factor.
9652     * @see #getPivotX()
9653     * @see #getPivotY()
9654     *
9655     * @attr ref android.R.styleable#View_scaleY
9656     */
9657    public void setScaleY(float scaleY) {
9658        ensureTransformationInfo();
9659        final TransformationInfo info = mTransformationInfo;
9660        if (info.mScaleY != scaleY) {
9661            invalidateViewProperty(true, false);
9662            info.mScaleY = scaleY;
9663            info.mMatrixDirty = true;
9664            invalidateViewProperty(false, true);
9665            if (mDisplayList != null) {
9666                mDisplayList.setScaleY(scaleY);
9667            }
9668            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9669                // View was rejected last time it was drawn by its parent; this may have changed
9670                invalidateParentIfNeeded();
9671            }
9672        }
9673    }
9674
9675    /**
9676     * The x location of the point around which the view is {@link #setRotation(float) rotated}
9677     * and {@link #setScaleX(float) scaled}.
9678     *
9679     * @see #getRotation()
9680     * @see #getScaleX()
9681     * @see #getScaleY()
9682     * @see #getPivotY()
9683     * @return The x location of the pivot point.
9684     *
9685     * @attr ref android.R.styleable#View_transformPivotX
9686     */
9687    @ViewDebug.ExportedProperty(category = "drawing")
9688    public float getPivotX() {
9689        return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0;
9690    }
9691
9692    /**
9693     * Sets the x location of the point around which the view is
9694     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
9695     * By default, the pivot point is centered on the object.
9696     * Setting this property disables this behavior and causes the view to use only the
9697     * explicitly set pivotX and pivotY values.
9698     *
9699     * @param pivotX The x location of the pivot point.
9700     * @see #getRotation()
9701     * @see #getScaleX()
9702     * @see #getScaleY()
9703     * @see #getPivotY()
9704     *
9705     * @attr ref android.R.styleable#View_transformPivotX
9706     */
9707    public void setPivotX(float pivotX) {
9708        ensureTransformationInfo();
9709        final TransformationInfo info = mTransformationInfo;
9710        boolean pivotSet = (mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) ==
9711                PFLAG_PIVOT_EXPLICITLY_SET;
9712        if (info.mPivotX != pivotX || !pivotSet) {
9713            mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET;
9714            invalidateViewProperty(true, false);
9715            info.mPivotX = pivotX;
9716            info.mMatrixDirty = true;
9717            invalidateViewProperty(false, true);
9718            if (mDisplayList != null) {
9719                mDisplayList.setPivotX(pivotX);
9720            }
9721            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9722                // View was rejected last time it was drawn by its parent; this may have changed
9723                invalidateParentIfNeeded();
9724            }
9725        }
9726    }
9727
9728    /**
9729     * The y location of the point around which the view is {@link #setRotation(float) rotated}
9730     * and {@link #setScaleY(float) scaled}.
9731     *
9732     * @see #getRotation()
9733     * @see #getScaleX()
9734     * @see #getScaleY()
9735     * @see #getPivotY()
9736     * @return The y location of the pivot point.
9737     *
9738     * @attr ref android.R.styleable#View_transformPivotY
9739     */
9740    @ViewDebug.ExportedProperty(category = "drawing")
9741    public float getPivotY() {
9742        return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0;
9743    }
9744
9745    /**
9746     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
9747     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
9748     * Setting this property disables this behavior and causes the view to use only the
9749     * explicitly set pivotX and pivotY values.
9750     *
9751     * @param pivotY The y location of the pivot point.
9752     * @see #getRotation()
9753     * @see #getScaleX()
9754     * @see #getScaleY()
9755     * @see #getPivotY()
9756     *
9757     * @attr ref android.R.styleable#View_transformPivotY
9758     */
9759    public void setPivotY(float pivotY) {
9760        ensureTransformationInfo();
9761        final TransformationInfo info = mTransformationInfo;
9762        boolean pivotSet = (mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) ==
9763                PFLAG_PIVOT_EXPLICITLY_SET;
9764        if (info.mPivotY != pivotY || !pivotSet) {
9765            mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET;
9766            invalidateViewProperty(true, false);
9767            info.mPivotY = pivotY;
9768            info.mMatrixDirty = true;
9769            invalidateViewProperty(false, true);
9770            if (mDisplayList != null) {
9771                mDisplayList.setPivotY(pivotY);
9772            }
9773            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9774                // View was rejected last time it was drawn by its parent; this may have changed
9775                invalidateParentIfNeeded();
9776            }
9777        }
9778    }
9779
9780    /**
9781     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
9782     * completely transparent and 1 means the view is completely opaque.
9783     *
9784     * <p>By default this is 1.0f.
9785     * @return The opacity of the view.
9786     */
9787    @ViewDebug.ExportedProperty(category = "drawing")
9788    public float getAlpha() {
9789        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
9790    }
9791
9792    /**
9793     * Returns whether this View has content which overlaps.
9794     *
9795     * <p>This function, intended to be overridden by specific View types, is an optimization when
9796     * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to
9797     * an offscreen buffer and then composited into place, which can be expensive. If the view has
9798     * no overlapping rendering, the view can draw each primitive with the appropriate alpha value
9799     * directly. An example of overlapping rendering is a TextView with a background image, such as
9800     * a Button. An example of non-overlapping rendering is a TextView with no background, or an
9801     * ImageView with only the foreground image. The default implementation returns true; subclasses
9802     * should override if they have cases which can be optimized.</p>
9803     *
9804     * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas}
9805     * necessitates that a View return true if it uses the methods internally without passing the
9806     * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p>
9807     *
9808     * @return true if the content in this view might overlap, false otherwise.
9809     */
9810    public boolean hasOverlappingRendering() {
9811        return true;
9812    }
9813
9814    /**
9815     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
9816     * completely transparent and 1 means the view is completely opaque.</p>
9817     *
9818     * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant
9819     * performance implications, especially for large views. It is best to use the alpha property
9820     * sparingly and transiently, as in the case of fading animations.</p>
9821     *
9822     * <p>For a view with a frequently changing alpha, such as during a fading animation, it is
9823     * strongly recommended for performance reasons to either override
9824     * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a
9825     * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p>
9826     *
9827     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
9828     * responsible for applying the opacity itself.</p>
9829     *
9830     * <p>Note that if the view is backed by a
9831     * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a
9832     * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than
9833     * 1.0 will supercede the alpha of the layer paint.</p>
9834     *
9835     * @param alpha The opacity of the view.
9836     *
9837     * @see #hasOverlappingRendering()
9838     * @see #setLayerType(int, android.graphics.Paint)
9839     *
9840     * @attr ref android.R.styleable#View_alpha
9841     */
9842    public void setAlpha(float alpha) {
9843        ensureTransformationInfo();
9844        if (mTransformationInfo.mAlpha != alpha) {
9845            mTransformationInfo.mAlpha = alpha;
9846            if (onSetAlpha((int) (alpha * 255))) {
9847                mPrivateFlags |= PFLAG_ALPHA_SET;
9848                // subclass is handling alpha - don't optimize rendering cache invalidation
9849                invalidateParentCaches();
9850                invalidate(true);
9851            } else {
9852                mPrivateFlags &= ~PFLAG_ALPHA_SET;
9853                invalidateViewProperty(true, false);
9854                if (mDisplayList != null) {
9855                    mDisplayList.setAlpha(getFinalAlpha());
9856                }
9857            }
9858        }
9859    }
9860
9861    /**
9862     * Faster version of setAlpha() which performs the same steps except there are
9863     * no calls to invalidate(). The caller of this function should perform proper invalidation
9864     * on the parent and this object. The return value indicates whether the subclass handles
9865     * alpha (the return value for onSetAlpha()).
9866     *
9867     * @param alpha The new value for the alpha property
9868     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
9869     *         the new value for the alpha property is different from the old value
9870     */
9871    boolean setAlphaNoInvalidation(float alpha) {
9872        ensureTransformationInfo();
9873        if (mTransformationInfo.mAlpha != alpha) {
9874            mTransformationInfo.mAlpha = alpha;
9875            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
9876            if (subclassHandlesAlpha) {
9877                mPrivateFlags |= PFLAG_ALPHA_SET;
9878                return true;
9879            } else {
9880                mPrivateFlags &= ~PFLAG_ALPHA_SET;
9881                if (mDisplayList != null) {
9882                    mDisplayList.setAlpha(getFinalAlpha());
9883                }
9884            }
9885        }
9886        return false;
9887    }
9888
9889    /**
9890     * This property is hidden and intended only for use by the Fade transition, which
9891     * animates it to produce a visual translucency that does not side-effect (or get
9892     * affected by) the real alpha property. This value is composited with the other
9893     * alpha value (and the AlphaAnimation value, when that is present) to produce
9894     * a final visual translucency result, which is what is passed into the DisplayList.
9895     *
9896     * @hide
9897     */
9898    public void setTransitionAlpha(float alpha) {
9899        ensureTransformationInfo();
9900        if (mTransformationInfo.mTransitionAlpha != alpha) {
9901            mTransformationInfo.mTransitionAlpha = alpha;
9902            mPrivateFlags &= ~PFLAG_ALPHA_SET;
9903            invalidateViewProperty(true, false);
9904            if (mDisplayList != null) {
9905                mDisplayList.setAlpha(getFinalAlpha());
9906            }
9907        }
9908    }
9909
9910    /**
9911     * Calculates the visual alpha of this view, which is a combination of the actual
9912     * alpha value and the transitionAlpha value (if set).
9913     */
9914    private float getFinalAlpha() {
9915        if (mTransformationInfo != null) {
9916            return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha;
9917        }
9918        return 1;
9919    }
9920
9921    /**
9922     * This property is hidden and intended only for use by the Fade transition, which
9923     * animates it to produce a visual translucency that does not side-effect (or get
9924     * affected by) the real alpha property. This value is composited with the other
9925     * alpha value (and the AlphaAnimation value, when that is present) to produce
9926     * a final visual translucency result, which is what is passed into the DisplayList.
9927     *
9928     * @hide
9929     */
9930    public float getTransitionAlpha() {
9931        return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1;
9932    }
9933
9934    /**
9935     * Top position of this view relative to its parent.
9936     *
9937     * @return The top of this view, in pixels.
9938     */
9939    @ViewDebug.CapturedViewProperty
9940    public final int getTop() {
9941        return mTop;
9942    }
9943
9944    /**
9945     * Sets the top position of this view relative to its parent. This method is meant to be called
9946     * by the layout system and should not generally be called otherwise, because the property
9947     * may be changed at any time by the layout.
9948     *
9949     * @param top The top of this view, in pixels.
9950     */
9951    public final void setTop(int top) {
9952        if (top != mTop) {
9953            updateMatrix();
9954            final boolean matrixIsIdentity = mTransformationInfo == null
9955                    || mTransformationInfo.mMatrixIsIdentity;
9956            if (matrixIsIdentity) {
9957                if (mAttachInfo != null) {
9958                    int minTop;
9959                    int yLoc;
9960                    if (top < mTop) {
9961                        minTop = top;
9962                        yLoc = top - mTop;
9963                    } else {
9964                        minTop = mTop;
9965                        yLoc = 0;
9966                    }
9967                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
9968                }
9969            } else {
9970                // Double-invalidation is necessary to capture view's old and new areas
9971                invalidate(true);
9972            }
9973
9974            int width = mRight - mLeft;
9975            int oldHeight = mBottom - mTop;
9976
9977            mTop = top;
9978            if (mDisplayList != null) {
9979                mDisplayList.setTop(mTop);
9980            }
9981
9982            sizeChange(width, mBottom - mTop, width, oldHeight);
9983
9984            if (!matrixIsIdentity) {
9985                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9986                    // A change in dimension means an auto-centered pivot point changes, too
9987                    mTransformationInfo.mMatrixDirty = true;
9988                }
9989                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
9990                invalidate(true);
9991            }
9992            mBackgroundSizeChanged = true;
9993            invalidateParentIfNeeded();
9994            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9995                // View was rejected last time it was drawn by its parent; this may have changed
9996                invalidateParentIfNeeded();
9997            }
9998        }
9999    }
10000
10001    /**
10002     * Bottom position of this view relative to its parent.
10003     *
10004     * @return The bottom of this view, in pixels.
10005     */
10006    @ViewDebug.CapturedViewProperty
10007    public final int getBottom() {
10008        return mBottom;
10009    }
10010
10011    /**
10012     * True if this view has changed since the last time being drawn.
10013     *
10014     * @return The dirty state of this view.
10015     */
10016    public boolean isDirty() {
10017        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
10018    }
10019
10020    /**
10021     * Sets the bottom position of this view relative to its parent. This method is meant to be
10022     * called by the layout system and should not generally be called otherwise, because the
10023     * property may be changed at any time by the layout.
10024     *
10025     * @param bottom The bottom of this view, in pixels.
10026     */
10027    public final void setBottom(int bottom) {
10028        if (bottom != mBottom) {
10029            updateMatrix();
10030            final boolean matrixIsIdentity = mTransformationInfo == null
10031                    || mTransformationInfo.mMatrixIsIdentity;
10032            if (matrixIsIdentity) {
10033                if (mAttachInfo != null) {
10034                    int maxBottom;
10035                    if (bottom < mBottom) {
10036                        maxBottom = mBottom;
10037                    } else {
10038                        maxBottom = bottom;
10039                    }
10040                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
10041                }
10042            } else {
10043                // Double-invalidation is necessary to capture view's old and new areas
10044                invalidate(true);
10045            }
10046
10047            int width = mRight - mLeft;
10048            int oldHeight = mBottom - mTop;
10049
10050            mBottom = bottom;
10051            if (mDisplayList != null) {
10052                mDisplayList.setBottom(mBottom);
10053            }
10054
10055            sizeChange(width, mBottom - mTop, width, oldHeight);
10056
10057            if (!matrixIsIdentity) {
10058                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
10059                    // A change in dimension means an auto-centered pivot point changes, too
10060                    mTransformationInfo.mMatrixDirty = true;
10061                }
10062                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10063                invalidate(true);
10064            }
10065            mBackgroundSizeChanged = true;
10066            invalidateParentIfNeeded();
10067            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10068                // View was rejected last time it was drawn by its parent; this may have changed
10069                invalidateParentIfNeeded();
10070            }
10071        }
10072    }
10073
10074    /**
10075     * Left position of this view relative to its parent.
10076     *
10077     * @return The left edge of this view, in pixels.
10078     */
10079    @ViewDebug.CapturedViewProperty
10080    public final int getLeft() {
10081        return mLeft;
10082    }
10083
10084    /**
10085     * Sets the left position of this view relative to its parent. This method is meant to be called
10086     * by the layout system and should not generally be called otherwise, because the property
10087     * may be changed at any time by the layout.
10088     *
10089     * @param left The bottom of this view, in pixels.
10090     */
10091    public final void setLeft(int left) {
10092        if (left != mLeft) {
10093            updateMatrix();
10094            final boolean matrixIsIdentity = mTransformationInfo == null
10095                    || mTransformationInfo.mMatrixIsIdentity;
10096            if (matrixIsIdentity) {
10097                if (mAttachInfo != null) {
10098                    int minLeft;
10099                    int xLoc;
10100                    if (left < mLeft) {
10101                        minLeft = left;
10102                        xLoc = left - mLeft;
10103                    } else {
10104                        minLeft = mLeft;
10105                        xLoc = 0;
10106                    }
10107                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
10108                }
10109            } else {
10110                // Double-invalidation is necessary to capture view's old and new areas
10111                invalidate(true);
10112            }
10113
10114            int oldWidth = mRight - mLeft;
10115            int height = mBottom - mTop;
10116
10117            mLeft = left;
10118            if (mDisplayList != null) {
10119                mDisplayList.setLeft(left);
10120            }
10121
10122            sizeChange(mRight - mLeft, height, oldWidth, height);
10123
10124            if (!matrixIsIdentity) {
10125                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
10126                    // A change in dimension means an auto-centered pivot point changes, too
10127                    mTransformationInfo.mMatrixDirty = true;
10128                }
10129                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10130                invalidate(true);
10131            }
10132            mBackgroundSizeChanged = true;
10133            invalidateParentIfNeeded();
10134            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10135                // View was rejected last time it was drawn by its parent; this may have changed
10136                invalidateParentIfNeeded();
10137            }
10138        }
10139    }
10140
10141    /**
10142     * Right position of this view relative to its parent.
10143     *
10144     * @return The right edge of this view, in pixels.
10145     */
10146    @ViewDebug.CapturedViewProperty
10147    public final int getRight() {
10148        return mRight;
10149    }
10150
10151    /**
10152     * Sets the right position of this view relative to its parent. This method is meant to be called
10153     * by the layout system and should not generally be called otherwise, because the property
10154     * may be changed at any time by the layout.
10155     *
10156     * @param right The bottom of this view, in pixels.
10157     */
10158    public final void setRight(int right) {
10159        if (right != mRight) {
10160            updateMatrix();
10161            final boolean matrixIsIdentity = mTransformationInfo == null
10162                    || mTransformationInfo.mMatrixIsIdentity;
10163            if (matrixIsIdentity) {
10164                if (mAttachInfo != null) {
10165                    int maxRight;
10166                    if (right < mRight) {
10167                        maxRight = mRight;
10168                    } else {
10169                        maxRight = right;
10170                    }
10171                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
10172                }
10173            } else {
10174                // Double-invalidation is necessary to capture view's old and new areas
10175                invalidate(true);
10176            }
10177
10178            int oldWidth = mRight - mLeft;
10179            int height = mBottom - mTop;
10180
10181            mRight = right;
10182            if (mDisplayList != null) {
10183                mDisplayList.setRight(mRight);
10184            }
10185
10186            sizeChange(mRight - mLeft, height, oldWidth, height);
10187
10188            if (!matrixIsIdentity) {
10189                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
10190                    // A change in dimension means an auto-centered pivot point changes, too
10191                    mTransformationInfo.mMatrixDirty = true;
10192                }
10193                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10194                invalidate(true);
10195            }
10196            mBackgroundSizeChanged = true;
10197            invalidateParentIfNeeded();
10198            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10199                // View was rejected last time it was drawn by its parent; this may have changed
10200                invalidateParentIfNeeded();
10201            }
10202        }
10203    }
10204
10205    /**
10206     * The visual x position of this view, in pixels. This is equivalent to the
10207     * {@link #setTranslationX(float) translationX} property plus the current
10208     * {@link #getLeft() left} property.
10209     *
10210     * @return The visual x position of this view, in pixels.
10211     */
10212    @ViewDebug.ExportedProperty(category = "drawing")
10213    public float getX() {
10214        return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0);
10215    }
10216
10217    /**
10218     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
10219     * {@link #setTranslationX(float) translationX} property to be the difference between
10220     * the x value passed in and the current {@link #getLeft() left} property.
10221     *
10222     * @param x The visual x position of this view, in pixels.
10223     */
10224    public void setX(float x) {
10225        setTranslationX(x - mLeft);
10226    }
10227
10228    /**
10229     * The visual y position of this view, in pixels. This is equivalent to the
10230     * {@link #setTranslationY(float) translationY} property plus the current
10231     * {@link #getTop() top} property.
10232     *
10233     * @return The visual y position of this view, in pixels.
10234     */
10235    @ViewDebug.ExportedProperty(category = "drawing")
10236    public float getY() {
10237        return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0);
10238    }
10239
10240    /**
10241     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
10242     * {@link #setTranslationY(float) translationY} property to be the difference between
10243     * the y value passed in and the current {@link #getTop() top} property.
10244     *
10245     * @param y The visual y position of this view, in pixels.
10246     */
10247    public void setY(float y) {
10248        setTranslationY(y - mTop);
10249    }
10250
10251
10252    /**
10253     * The horizontal location of this view relative to its {@link #getLeft() left} position.
10254     * This position is post-layout, in addition to wherever the object's
10255     * layout placed it.
10256     *
10257     * @return The horizontal position of this view relative to its left position, in pixels.
10258     */
10259    @ViewDebug.ExportedProperty(category = "drawing")
10260    public float getTranslationX() {
10261        return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0;
10262    }
10263
10264    /**
10265     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
10266     * This effectively positions the object post-layout, in addition to wherever the object's
10267     * layout placed it.
10268     *
10269     * @param translationX The horizontal position of this view relative to its left position,
10270     * in pixels.
10271     *
10272     * @attr ref android.R.styleable#View_translationX
10273     */
10274    public void setTranslationX(float translationX) {
10275        ensureTransformationInfo();
10276        final TransformationInfo info = mTransformationInfo;
10277        if (info.mTranslationX != translationX) {
10278            // Double-invalidation is necessary to capture view's old and new areas
10279            invalidateViewProperty(true, false);
10280            info.mTranslationX = translationX;
10281            info.mMatrixDirty = true;
10282            invalidateViewProperty(false, true);
10283            if (mDisplayList != null) {
10284                mDisplayList.setTranslationX(translationX);
10285            }
10286            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10287                // View was rejected last time it was drawn by its parent; this may have changed
10288                invalidateParentIfNeeded();
10289            }
10290        }
10291    }
10292
10293    /**
10294     * The vertical location of this view relative to its {@link #getTop() top} position.
10295     * This position is post-layout, in addition to wherever the object's
10296     * layout placed it.
10297     *
10298     * @return The vertical position of this view relative to its top position,
10299     * in pixels.
10300     */
10301    @ViewDebug.ExportedProperty(category = "drawing")
10302    public float getTranslationY() {
10303        return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0;
10304    }
10305
10306    /**
10307     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
10308     * This effectively positions the object post-layout, in addition to wherever the object's
10309     * layout placed it.
10310     *
10311     * @param translationY The vertical position of this view relative to its top position,
10312     * in pixels.
10313     *
10314     * @attr ref android.R.styleable#View_translationY
10315     */
10316    public void setTranslationY(float translationY) {
10317        ensureTransformationInfo();
10318        final TransformationInfo info = mTransformationInfo;
10319        if (info.mTranslationY != translationY) {
10320            invalidateViewProperty(true, false);
10321            info.mTranslationY = translationY;
10322            info.mMatrixDirty = true;
10323            invalidateViewProperty(false, true);
10324            if (mDisplayList != null) {
10325                mDisplayList.setTranslationY(translationY);
10326            }
10327            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10328                // View was rejected last time it was drawn by its parent; this may have changed
10329                invalidateParentIfNeeded();
10330            }
10331        }
10332    }
10333
10334    /**
10335     * Hit rectangle in parent's coordinates
10336     *
10337     * @param outRect The hit rectangle of the view.
10338     */
10339    public void getHitRect(Rect outRect) {
10340        updateMatrix();
10341        final TransformationInfo info = mTransformationInfo;
10342        if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) {
10343            outRect.set(mLeft, mTop, mRight, mBottom);
10344        } else {
10345            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
10346            tmpRect.set(0, 0, getWidth(), getHeight());
10347            info.mMatrix.mapRect(tmpRect);
10348            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
10349                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
10350        }
10351    }
10352
10353    /**
10354     * Determines whether the given point, in local coordinates is inside the view.
10355     */
10356    /*package*/ final boolean pointInView(float localX, float localY) {
10357        return localX >= 0 && localX < (mRight - mLeft)
10358                && localY >= 0 && localY < (mBottom - mTop);
10359    }
10360
10361    /**
10362     * Utility method to determine whether the given point, in local coordinates,
10363     * is inside the view, where the area of the view is expanded by the slop factor.
10364     * This method is called while processing touch-move events to determine if the event
10365     * is still within the view.
10366     *
10367     * @hide
10368     */
10369    public boolean pointInView(float localX, float localY, float slop) {
10370        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
10371                localY < ((mBottom - mTop) + slop);
10372    }
10373
10374    /**
10375     * When a view has focus and the user navigates away from it, the next view is searched for
10376     * starting from the rectangle filled in by this method.
10377     *
10378     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
10379     * of the view.  However, if your view maintains some idea of internal selection,
10380     * such as a cursor, or a selected row or column, you should override this method and
10381     * fill in a more specific rectangle.
10382     *
10383     * @param r The rectangle to fill in, in this view's coordinates.
10384     */
10385    public void getFocusedRect(Rect r) {
10386        getDrawingRect(r);
10387    }
10388
10389    /**
10390     * If some part of this view is not clipped by any of its parents, then
10391     * return that area in r in global (root) coordinates. To convert r to local
10392     * coordinates (without taking possible View rotations into account), offset
10393     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
10394     * If the view is completely clipped or translated out, return false.
10395     *
10396     * @param r If true is returned, r holds the global coordinates of the
10397     *        visible portion of this view.
10398     * @param globalOffset If true is returned, globalOffset holds the dx,dy
10399     *        between this view and its root. globalOffet may be null.
10400     * @return true if r is non-empty (i.e. part of the view is visible at the
10401     *         root level.
10402     */
10403    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
10404        int width = mRight - mLeft;
10405        int height = mBottom - mTop;
10406        if (width > 0 && height > 0) {
10407            r.set(0, 0, width, height);
10408            if (globalOffset != null) {
10409                globalOffset.set(-mScrollX, -mScrollY);
10410            }
10411            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
10412        }
10413        return false;
10414    }
10415
10416    public final boolean getGlobalVisibleRect(Rect r) {
10417        return getGlobalVisibleRect(r, null);
10418    }
10419
10420    public final boolean getLocalVisibleRect(Rect r) {
10421        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
10422        if (getGlobalVisibleRect(r, offset)) {
10423            r.offset(-offset.x, -offset.y); // make r local
10424            return true;
10425        }
10426        return false;
10427    }
10428
10429    /**
10430     * Offset this view's vertical location by the specified number of pixels.
10431     *
10432     * @param offset the number of pixels to offset the view by
10433     */
10434    public void offsetTopAndBottom(int offset) {
10435        if (offset != 0) {
10436            updateMatrix();
10437            final boolean matrixIsIdentity = mTransformationInfo == null
10438                    || mTransformationInfo.mMatrixIsIdentity;
10439            if (matrixIsIdentity) {
10440                if (mDisplayList != null) {
10441                    invalidateViewProperty(false, false);
10442                } else {
10443                    final ViewParent p = mParent;
10444                    if (p != null && mAttachInfo != null) {
10445                        final Rect r = mAttachInfo.mTmpInvalRect;
10446                        int minTop;
10447                        int maxBottom;
10448                        int yLoc;
10449                        if (offset < 0) {
10450                            minTop = mTop + offset;
10451                            maxBottom = mBottom;
10452                            yLoc = offset;
10453                        } else {
10454                            minTop = mTop;
10455                            maxBottom = mBottom + offset;
10456                            yLoc = 0;
10457                        }
10458                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
10459                        p.invalidateChild(this, r);
10460                    }
10461                }
10462            } else {
10463                invalidateViewProperty(false, false);
10464            }
10465
10466            mTop += offset;
10467            mBottom += offset;
10468            if (mDisplayList != null) {
10469                mDisplayList.offsetTopAndBottom(offset);
10470                invalidateViewProperty(false, false);
10471            } else {
10472                if (!matrixIsIdentity) {
10473                    invalidateViewProperty(false, true);
10474                }
10475                invalidateParentIfNeeded();
10476            }
10477        }
10478    }
10479
10480    /**
10481     * Offset this view's horizontal location by the specified amount of pixels.
10482     *
10483     * @param offset the number of pixels to offset the view by
10484     */
10485    public void offsetLeftAndRight(int offset) {
10486        if (offset != 0) {
10487            updateMatrix();
10488            final boolean matrixIsIdentity = mTransformationInfo == null
10489                    || mTransformationInfo.mMatrixIsIdentity;
10490            if (matrixIsIdentity) {
10491                if (mDisplayList != null) {
10492                    invalidateViewProperty(false, false);
10493                } else {
10494                    final ViewParent p = mParent;
10495                    if (p != null && mAttachInfo != null) {
10496                        final Rect r = mAttachInfo.mTmpInvalRect;
10497                        int minLeft;
10498                        int maxRight;
10499                        if (offset < 0) {
10500                            minLeft = mLeft + offset;
10501                            maxRight = mRight;
10502                        } else {
10503                            minLeft = mLeft;
10504                            maxRight = mRight + offset;
10505                        }
10506                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
10507                        p.invalidateChild(this, r);
10508                    }
10509                }
10510            } else {
10511                invalidateViewProperty(false, false);
10512            }
10513
10514            mLeft += offset;
10515            mRight += offset;
10516            if (mDisplayList != null) {
10517                mDisplayList.offsetLeftAndRight(offset);
10518                invalidateViewProperty(false, false);
10519            } else {
10520                if (!matrixIsIdentity) {
10521                    invalidateViewProperty(false, true);
10522                }
10523                invalidateParentIfNeeded();
10524            }
10525        }
10526    }
10527
10528    /**
10529     * Get the LayoutParams associated with this view. All views should have
10530     * layout parameters. These supply parameters to the <i>parent</i> of this
10531     * view specifying how it should be arranged. There are many subclasses of
10532     * ViewGroup.LayoutParams, and these correspond to the different subclasses
10533     * of ViewGroup that are responsible for arranging their children.
10534     *
10535     * This method may return null if this View is not attached to a parent
10536     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
10537     * was not invoked successfully. When a View is attached to a parent
10538     * ViewGroup, this method must not return null.
10539     *
10540     * @return The LayoutParams associated with this view, or null if no
10541     *         parameters have been set yet
10542     */
10543    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
10544    public ViewGroup.LayoutParams getLayoutParams() {
10545        return mLayoutParams;
10546    }
10547
10548    /**
10549     * Set the layout parameters associated with this view. These supply
10550     * parameters to the <i>parent</i> of this view specifying how it should be
10551     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
10552     * correspond to the different subclasses of ViewGroup that are responsible
10553     * for arranging their children.
10554     *
10555     * @param params The layout parameters for this view, cannot be null
10556     */
10557    public void setLayoutParams(ViewGroup.LayoutParams params) {
10558        if (params == null) {
10559            throw new NullPointerException("Layout parameters cannot be null");
10560        }
10561        mLayoutParams = params;
10562        resolveLayoutParams();
10563        if (mParent instanceof ViewGroup) {
10564            ((ViewGroup) mParent).onSetLayoutParams(this, params);
10565        }
10566        requestLayout();
10567    }
10568
10569    /**
10570     * Resolve the layout parameters depending on the resolved layout direction
10571     *
10572     * @hide
10573     */
10574    public void resolveLayoutParams() {
10575        if (mLayoutParams != null) {
10576            mLayoutParams.resolveLayoutDirection(getLayoutDirection());
10577        }
10578    }
10579
10580    /**
10581     * Set the scrolled position of your view. This will cause a call to
10582     * {@link #onScrollChanged(int, int, int, int)} and the view will be
10583     * invalidated.
10584     * @param x the x position to scroll to
10585     * @param y the y position to scroll to
10586     */
10587    public void scrollTo(int x, int y) {
10588        if (mScrollX != x || mScrollY != y) {
10589            int oldX = mScrollX;
10590            int oldY = mScrollY;
10591            mScrollX = x;
10592            mScrollY = y;
10593            invalidateParentCaches();
10594            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
10595            if (!awakenScrollBars()) {
10596                postInvalidateOnAnimation();
10597            }
10598        }
10599    }
10600
10601    /**
10602     * Move the scrolled position of your view. This will cause a call to
10603     * {@link #onScrollChanged(int, int, int, int)} and the view will be
10604     * invalidated.
10605     * @param x the amount of pixels to scroll by horizontally
10606     * @param y the amount of pixels to scroll by vertically
10607     */
10608    public void scrollBy(int x, int y) {
10609        scrollTo(mScrollX + x, mScrollY + y);
10610    }
10611
10612    /**
10613     * <p>Trigger the scrollbars to draw. When invoked this method starts an
10614     * animation to fade the scrollbars out after a default delay. If a subclass
10615     * provides animated scrolling, the start delay should equal the duration
10616     * of the scrolling animation.</p>
10617     *
10618     * <p>The animation starts only if at least one of the scrollbars is
10619     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
10620     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
10621     * this method returns true, and false otherwise. If the animation is
10622     * started, this method calls {@link #invalidate()}; in that case the
10623     * caller should not call {@link #invalidate()}.</p>
10624     *
10625     * <p>This method should be invoked every time a subclass directly updates
10626     * the scroll parameters.</p>
10627     *
10628     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
10629     * and {@link #scrollTo(int, int)}.</p>
10630     *
10631     * @return true if the animation is played, false otherwise
10632     *
10633     * @see #awakenScrollBars(int)
10634     * @see #scrollBy(int, int)
10635     * @see #scrollTo(int, int)
10636     * @see #isHorizontalScrollBarEnabled()
10637     * @see #isVerticalScrollBarEnabled()
10638     * @see #setHorizontalScrollBarEnabled(boolean)
10639     * @see #setVerticalScrollBarEnabled(boolean)
10640     */
10641    protected boolean awakenScrollBars() {
10642        return mScrollCache != null &&
10643                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
10644    }
10645
10646    /**
10647     * Trigger the scrollbars to draw.
10648     * This method differs from awakenScrollBars() only in its default duration.
10649     * initialAwakenScrollBars() will show the scroll bars for longer than
10650     * usual to give the user more of a chance to notice them.
10651     *
10652     * @return true if the animation is played, false otherwise.
10653     */
10654    private boolean initialAwakenScrollBars() {
10655        return mScrollCache != null &&
10656                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
10657    }
10658
10659    /**
10660     * <p>
10661     * Trigger the scrollbars to draw. When invoked this method starts an
10662     * animation to fade the scrollbars out after a fixed delay. If a subclass
10663     * provides animated scrolling, the start delay should equal the duration of
10664     * the scrolling animation.
10665     * </p>
10666     *
10667     * <p>
10668     * The animation starts only if at least one of the scrollbars is enabled,
10669     * as specified by {@link #isHorizontalScrollBarEnabled()} and
10670     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
10671     * this method returns true, and false otherwise. If the animation is
10672     * started, this method calls {@link #invalidate()}; in that case the caller
10673     * should not call {@link #invalidate()}.
10674     * </p>
10675     *
10676     * <p>
10677     * This method should be invoked everytime a subclass directly updates the
10678     * scroll parameters.
10679     * </p>
10680     *
10681     * @param startDelay the delay, in milliseconds, after which the animation
10682     *        should start; when the delay is 0, the animation starts
10683     *        immediately
10684     * @return true if the animation is played, false otherwise
10685     *
10686     * @see #scrollBy(int, int)
10687     * @see #scrollTo(int, int)
10688     * @see #isHorizontalScrollBarEnabled()
10689     * @see #isVerticalScrollBarEnabled()
10690     * @see #setHorizontalScrollBarEnabled(boolean)
10691     * @see #setVerticalScrollBarEnabled(boolean)
10692     */
10693    protected boolean awakenScrollBars(int startDelay) {
10694        return awakenScrollBars(startDelay, true);
10695    }
10696
10697    /**
10698     * <p>
10699     * Trigger the scrollbars to draw. When invoked this method starts an
10700     * animation to fade the scrollbars out after a fixed delay. If a subclass
10701     * provides animated scrolling, the start delay should equal the duration of
10702     * the scrolling animation.
10703     * </p>
10704     *
10705     * <p>
10706     * The animation starts only if at least one of the scrollbars is enabled,
10707     * as specified by {@link #isHorizontalScrollBarEnabled()} and
10708     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
10709     * this method returns true, and false otherwise. If the animation is
10710     * started, this method calls {@link #invalidate()} if the invalidate parameter
10711     * is set to true; in that case the caller
10712     * should not call {@link #invalidate()}.
10713     * </p>
10714     *
10715     * <p>
10716     * This method should be invoked everytime a subclass directly updates the
10717     * scroll parameters.
10718     * </p>
10719     *
10720     * @param startDelay the delay, in milliseconds, after which the animation
10721     *        should start; when the delay is 0, the animation starts
10722     *        immediately
10723     *
10724     * @param invalidate Wheter this method should call invalidate
10725     *
10726     * @return true if the animation is played, false otherwise
10727     *
10728     * @see #scrollBy(int, int)
10729     * @see #scrollTo(int, int)
10730     * @see #isHorizontalScrollBarEnabled()
10731     * @see #isVerticalScrollBarEnabled()
10732     * @see #setHorizontalScrollBarEnabled(boolean)
10733     * @see #setVerticalScrollBarEnabled(boolean)
10734     */
10735    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
10736        final ScrollabilityCache scrollCache = mScrollCache;
10737
10738        if (scrollCache == null || !scrollCache.fadeScrollBars) {
10739            return false;
10740        }
10741
10742        if (scrollCache.scrollBar == null) {
10743            scrollCache.scrollBar = new ScrollBarDrawable();
10744        }
10745
10746        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
10747
10748            if (invalidate) {
10749                // Invalidate to show the scrollbars
10750                postInvalidateOnAnimation();
10751            }
10752
10753            if (scrollCache.state == ScrollabilityCache.OFF) {
10754                // FIXME: this is copied from WindowManagerService.
10755                // We should get this value from the system when it
10756                // is possible to do so.
10757                final int KEY_REPEAT_FIRST_DELAY = 750;
10758                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
10759            }
10760
10761            // Tell mScrollCache when we should start fading. This may
10762            // extend the fade start time if one was already scheduled
10763            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
10764            scrollCache.fadeStartTime = fadeStartTime;
10765            scrollCache.state = ScrollabilityCache.ON;
10766
10767            // Schedule our fader to run, unscheduling any old ones first
10768            if (mAttachInfo != null) {
10769                mAttachInfo.mHandler.removeCallbacks(scrollCache);
10770                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
10771            }
10772
10773            return true;
10774        }
10775
10776        return false;
10777    }
10778
10779    /**
10780     * Do not invalidate views which are not visible and which are not running an animation. They
10781     * will not get drawn and they should not set dirty flags as if they will be drawn
10782     */
10783    private boolean skipInvalidate() {
10784        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
10785                (!(mParent instanceof ViewGroup) ||
10786                        !((ViewGroup) mParent).isViewTransitioning(this));
10787    }
10788    /**
10789     * Mark the area defined by dirty as needing to be drawn. If the view is
10790     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point
10791     * in the future. This must be called from a UI thread. To call from a non-UI
10792     * thread, call {@link #postInvalidate()}.
10793     *
10794     * WARNING: This method is destructive to dirty.
10795     * @param dirty the rectangle representing the bounds of the dirty region
10796     */
10797    public void invalidate(Rect dirty) {
10798        if (skipInvalidate()) {
10799            return;
10800        }
10801        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) ||
10802                (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID ||
10803                (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED) {
10804            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10805            mPrivateFlags |= PFLAG_INVALIDATED;
10806            mPrivateFlags |= PFLAG_DIRTY;
10807            final ViewParent p = mParent;
10808            final AttachInfo ai = mAttachInfo;
10809            //noinspection PointlessBooleanExpression,ConstantConditions
10810            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10811                if (p != null && ai != null && ai.mHardwareAccelerated) {
10812                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10813                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10814                    p.invalidateChild(this, null);
10815                    return;
10816                }
10817            }
10818            if (p != null && ai != null) {
10819                final int scrollX = mScrollX;
10820                final int scrollY = mScrollY;
10821                final Rect r = ai.mTmpInvalRect;
10822                r.set(dirty.left - scrollX, dirty.top - scrollY,
10823                        dirty.right - scrollX, dirty.bottom - scrollY);
10824                mParent.invalidateChild(this, r);
10825            }
10826        }
10827    }
10828
10829    /**
10830     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn.
10831     * The coordinates of the dirty rect are relative to the view.
10832     * If the view is visible, {@link #onDraw(android.graphics.Canvas)}
10833     * will be called at some point in the future. This must be called from
10834     * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
10835     * @param l the left position of the dirty region
10836     * @param t the top position of the dirty region
10837     * @param r the right position of the dirty region
10838     * @param b the bottom position of the dirty region
10839     */
10840    public void invalidate(int l, int t, int r, int b) {
10841        if (skipInvalidate()) {
10842            return;
10843        }
10844        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) ||
10845                (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID ||
10846                (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED) {
10847            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10848            mPrivateFlags |= PFLAG_INVALIDATED;
10849            mPrivateFlags |= PFLAG_DIRTY;
10850            final ViewParent p = mParent;
10851            final AttachInfo ai = mAttachInfo;
10852            //noinspection PointlessBooleanExpression,ConstantConditions
10853            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10854                if (p != null && ai != null && ai.mHardwareAccelerated) {
10855                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10856                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10857                    p.invalidateChild(this, null);
10858                    return;
10859                }
10860            }
10861            if (p != null && ai != null && l < r && t < b) {
10862                final int scrollX = mScrollX;
10863                final int scrollY = mScrollY;
10864                final Rect tmpr = ai.mTmpInvalRect;
10865                tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
10866                p.invalidateChild(this, tmpr);
10867            }
10868        }
10869    }
10870
10871    /**
10872     * Invalidate the whole view. If the view is visible,
10873     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
10874     * the future. This must be called from a UI thread. To call from a non-UI thread,
10875     * call {@link #postInvalidate()}.
10876     */
10877    public void invalidate() {
10878        invalidate(true);
10879    }
10880
10881    /**
10882     * This is where the invalidate() work actually happens. A full invalidate()
10883     * causes the drawing cache to be invalidated, but this function can be called with
10884     * invalidateCache set to false to skip that invalidation step for cases that do not
10885     * need it (for example, a component that remains at the same dimensions with the same
10886     * content).
10887     *
10888     * @param invalidateCache Whether the drawing cache for this view should be invalidated as
10889     * well. This is usually true for a full invalidate, but may be set to false if the
10890     * View's contents or dimensions have not changed.
10891     */
10892    void invalidate(boolean invalidateCache) {
10893        if (skipInvalidate()) {
10894            return;
10895        }
10896        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) ||
10897                (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) ||
10898                (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED || isOpaque() != mLastIsOpaque) {
10899            mLastIsOpaque = isOpaque();
10900            mPrivateFlags &= ~PFLAG_DRAWN;
10901            mPrivateFlags |= PFLAG_DIRTY;
10902            if (invalidateCache) {
10903                mPrivateFlags |= PFLAG_INVALIDATED;
10904                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10905            }
10906            final AttachInfo ai = mAttachInfo;
10907            final ViewParent p = mParent;
10908            //noinspection PointlessBooleanExpression,ConstantConditions
10909            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10910                if (p != null && ai != null && ai.mHardwareAccelerated) {
10911                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10912                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10913                    p.invalidateChild(this, null);
10914                    return;
10915                }
10916            }
10917
10918            if (p != null && ai != null) {
10919                final Rect r = ai.mTmpInvalRect;
10920                r.set(0, 0, mRight - mLeft, mBottom - mTop);
10921                // Don't call invalidate -- we don't want to internally scroll
10922                // our own bounds
10923                p.invalidateChild(this, r);
10924            }
10925        }
10926    }
10927
10928    /**
10929     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
10930     * set any flags or handle all of the cases handled by the default invalidation methods.
10931     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
10932     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
10933     * walk up the hierarchy, transforming the dirty rect as necessary.
10934     *
10935     * The method also handles normal invalidation logic if display list properties are not
10936     * being used in this view. The invalidateParent and forceRedraw flags are used by that
10937     * backup approach, to handle these cases used in the various property-setting methods.
10938     *
10939     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
10940     * are not being used in this view
10941     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
10942     * list properties are not being used in this view
10943     */
10944    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
10945        if (mDisplayList == null || (mPrivateFlags & PFLAG_DRAW_ANIMATION) == PFLAG_DRAW_ANIMATION) {
10946            if (invalidateParent) {
10947                invalidateParentCaches();
10948            }
10949            if (forceRedraw) {
10950                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10951            }
10952            invalidate(false);
10953        } else {
10954            final AttachInfo ai = mAttachInfo;
10955            final ViewParent p = mParent;
10956            if (p != null && ai != null) {
10957                final Rect r = ai.mTmpInvalRect;
10958                r.set(0, 0, mRight - mLeft, mBottom - mTop);
10959                if (mParent instanceof ViewGroup) {
10960                    ((ViewGroup) mParent).invalidateChildFast(this, r);
10961                } else {
10962                    mParent.invalidateChild(this, r);
10963                }
10964            }
10965        }
10966    }
10967
10968    /**
10969     * Utility method to transform a given Rect by the current matrix of this view.
10970     */
10971    void transformRect(final Rect rect) {
10972        if (!getMatrix().isIdentity()) {
10973            RectF boundingRect = mAttachInfo.mTmpTransformRect;
10974            boundingRect.set(rect);
10975            getMatrix().mapRect(boundingRect);
10976            rect.set((int) Math.floor(boundingRect.left),
10977                    (int) Math.floor(boundingRect.top),
10978                    (int) Math.ceil(boundingRect.right),
10979                    (int) Math.ceil(boundingRect.bottom));
10980        }
10981    }
10982
10983    /**
10984     * Used to indicate that the parent of this view should clear its caches. This functionality
10985     * is used to force the parent to rebuild its display list (when hardware-accelerated),
10986     * which is necessary when various parent-managed properties of the view change, such as
10987     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
10988     * clears the parent caches and does not causes an invalidate event.
10989     *
10990     * @hide
10991     */
10992    protected void invalidateParentCaches() {
10993        if (mParent instanceof View) {
10994            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
10995        }
10996    }
10997
10998    /**
10999     * Used to indicate that the parent of this view should be invalidated. This functionality
11000     * is used to force the parent to rebuild its display list (when hardware-accelerated),
11001     * which is necessary when various parent-managed properties of the view change, such as
11002     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
11003     * an invalidation event to the parent.
11004     *
11005     * @hide
11006     */
11007    protected void invalidateParentIfNeeded() {
11008        if (isHardwareAccelerated() && mParent instanceof View) {
11009            ((View) mParent).invalidate(true);
11010        }
11011    }
11012
11013    /**
11014     * Indicates whether this View is opaque. An opaque View guarantees that it will
11015     * draw all the pixels overlapping its bounds using a fully opaque color.
11016     *
11017     * Subclasses of View should override this method whenever possible to indicate
11018     * whether an instance is opaque. Opaque Views are treated in a special way by
11019     * the View hierarchy, possibly allowing it to perform optimizations during
11020     * invalidate/draw passes.
11021     *
11022     * @return True if this View is guaranteed to be fully opaque, false otherwise.
11023     */
11024    @ViewDebug.ExportedProperty(category = "drawing")
11025    public boolean isOpaque() {
11026        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
11027                getFinalAlpha() >= 1.0f;
11028    }
11029
11030    /**
11031     * @hide
11032     */
11033    protected void computeOpaqueFlags() {
11034        // Opaque if:
11035        //   - Has a background
11036        //   - Background is opaque
11037        //   - Doesn't have scrollbars or scrollbars overlay
11038
11039        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
11040            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
11041        } else {
11042            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
11043        }
11044
11045        final int flags = mViewFlags;
11046        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
11047                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY ||
11048                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) {
11049            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
11050        } else {
11051            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
11052        }
11053    }
11054
11055    /**
11056     * @hide
11057     */
11058    protected boolean hasOpaqueScrollbars() {
11059        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
11060    }
11061
11062    /**
11063     * @return A handler associated with the thread running the View. This
11064     * handler can be used to pump events in the UI events queue.
11065     */
11066    public Handler getHandler() {
11067        final AttachInfo attachInfo = mAttachInfo;
11068        if (attachInfo != null) {
11069            return attachInfo.mHandler;
11070        }
11071        return null;
11072    }
11073
11074    /**
11075     * Gets the view root associated with the View.
11076     * @return The view root, or null if none.
11077     * @hide
11078     */
11079    public ViewRootImpl getViewRootImpl() {
11080        if (mAttachInfo != null) {
11081            return mAttachInfo.mViewRootImpl;
11082        }
11083        return null;
11084    }
11085
11086    /**
11087     * <p>Causes the Runnable to be added to the message queue.
11088     * The runnable will be run on the user interface thread.</p>
11089     *
11090     * @param action The Runnable that will be executed.
11091     *
11092     * @return Returns true if the Runnable was successfully placed in to the
11093     *         message queue.  Returns false on failure, usually because the
11094     *         looper processing the message queue is exiting.
11095     *
11096     * @see #postDelayed
11097     * @see #removeCallbacks
11098     */
11099    public boolean post(Runnable action) {
11100        final AttachInfo attachInfo = mAttachInfo;
11101        if (attachInfo != null) {
11102            return attachInfo.mHandler.post(action);
11103        }
11104        // Assume that post will succeed later
11105        ViewRootImpl.getRunQueue().post(action);
11106        return true;
11107    }
11108
11109    /**
11110     * <p>Causes the Runnable to be added to the message queue, to be run
11111     * after the specified amount of time elapses.
11112     * The runnable will be run on the user interface thread.</p>
11113     *
11114     * @param action The Runnable that will be executed.
11115     * @param delayMillis The delay (in milliseconds) until the Runnable
11116     *        will be executed.
11117     *
11118     * @return true if the Runnable was successfully placed in to the
11119     *         message queue.  Returns false on failure, usually because the
11120     *         looper processing the message queue is exiting.  Note that a
11121     *         result of true does not mean the Runnable will be processed --
11122     *         if the looper is quit before the delivery time of the message
11123     *         occurs then the message will be dropped.
11124     *
11125     * @see #post
11126     * @see #removeCallbacks
11127     */
11128    public boolean postDelayed(Runnable action, long delayMillis) {
11129        final AttachInfo attachInfo = mAttachInfo;
11130        if (attachInfo != null) {
11131            return attachInfo.mHandler.postDelayed(action, delayMillis);
11132        }
11133        // Assume that post will succeed later
11134        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
11135        return true;
11136    }
11137
11138    /**
11139     * <p>Causes the Runnable to execute on the next animation time step.
11140     * The runnable will be run on the user interface thread.</p>
11141     *
11142     * @param action The Runnable that will be executed.
11143     *
11144     * @see #postOnAnimationDelayed
11145     * @see #removeCallbacks
11146     */
11147    public void postOnAnimation(Runnable action) {
11148        final AttachInfo attachInfo = mAttachInfo;
11149        if (attachInfo != null) {
11150            attachInfo.mViewRootImpl.mChoreographer.postCallback(
11151                    Choreographer.CALLBACK_ANIMATION, action, null);
11152        } else {
11153            // Assume that post will succeed later
11154            ViewRootImpl.getRunQueue().post(action);
11155        }
11156    }
11157
11158    /**
11159     * <p>Causes the Runnable to execute on the next animation time step,
11160     * after the specified amount of time elapses.
11161     * The runnable will be run on the user interface thread.</p>
11162     *
11163     * @param action The Runnable that will be executed.
11164     * @param delayMillis The delay (in milliseconds) until the Runnable
11165     *        will be executed.
11166     *
11167     * @see #postOnAnimation
11168     * @see #removeCallbacks
11169     */
11170    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
11171        final AttachInfo attachInfo = mAttachInfo;
11172        if (attachInfo != null) {
11173            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
11174                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
11175        } else {
11176            // Assume that post will succeed later
11177            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
11178        }
11179    }
11180
11181    /**
11182     * <p>Removes the specified Runnable from the message queue.</p>
11183     *
11184     * @param action The Runnable to remove from the message handling queue
11185     *
11186     * @return true if this view could ask the Handler to remove the Runnable,
11187     *         false otherwise. When the returned value is true, the Runnable
11188     *         may or may not have been actually removed from the message queue
11189     *         (for instance, if the Runnable was not in the queue already.)
11190     *
11191     * @see #post
11192     * @see #postDelayed
11193     * @see #postOnAnimation
11194     * @see #postOnAnimationDelayed
11195     */
11196    public boolean removeCallbacks(Runnable action) {
11197        if (action != null) {
11198            final AttachInfo attachInfo = mAttachInfo;
11199            if (attachInfo != null) {
11200                attachInfo.mHandler.removeCallbacks(action);
11201                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
11202                        Choreographer.CALLBACK_ANIMATION, action, null);
11203            } else {
11204                // Assume that post will succeed later
11205                ViewRootImpl.getRunQueue().removeCallbacks(action);
11206            }
11207        }
11208        return true;
11209    }
11210
11211    /**
11212     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
11213     * Use this to invalidate the View from a non-UI thread.</p>
11214     *
11215     * <p>This method can be invoked from outside of the UI thread
11216     * only when this View is attached to a window.</p>
11217     *
11218     * @see #invalidate()
11219     * @see #postInvalidateDelayed(long)
11220     */
11221    public void postInvalidate() {
11222        postInvalidateDelayed(0);
11223    }
11224
11225    /**
11226     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
11227     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
11228     *
11229     * <p>This method can be invoked from outside of the UI thread
11230     * only when this View is attached to a window.</p>
11231     *
11232     * @param left The left coordinate of the rectangle to invalidate.
11233     * @param top The top coordinate of the rectangle to invalidate.
11234     * @param right The right coordinate of the rectangle to invalidate.
11235     * @param bottom The bottom coordinate of the rectangle to invalidate.
11236     *
11237     * @see #invalidate(int, int, int, int)
11238     * @see #invalidate(Rect)
11239     * @see #postInvalidateDelayed(long, int, int, int, int)
11240     */
11241    public void postInvalidate(int left, int top, int right, int bottom) {
11242        postInvalidateDelayed(0, left, top, right, bottom);
11243    }
11244
11245    /**
11246     * <p>Cause an invalidate to happen on a subsequent cycle through the event
11247     * loop. Waits for the specified amount of time.</p>
11248     *
11249     * <p>This method can be invoked from outside of the UI thread
11250     * only when this View is attached to a window.</p>
11251     *
11252     * @param delayMilliseconds the duration in milliseconds to delay the
11253     *         invalidation by
11254     *
11255     * @see #invalidate()
11256     * @see #postInvalidate()
11257     */
11258    public void postInvalidateDelayed(long delayMilliseconds) {
11259        // We try only with the AttachInfo because there's no point in invalidating
11260        // if we are not attached to our window
11261        final AttachInfo attachInfo = mAttachInfo;
11262        if (attachInfo != null) {
11263            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
11264        }
11265    }
11266
11267    /**
11268     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
11269     * through the event loop. Waits for the specified amount of time.</p>
11270     *
11271     * <p>This method can be invoked from outside of the UI thread
11272     * only when this View is attached to a window.</p>
11273     *
11274     * @param delayMilliseconds the duration in milliseconds to delay the
11275     *         invalidation by
11276     * @param left The left coordinate of the rectangle to invalidate.
11277     * @param top The top coordinate of the rectangle to invalidate.
11278     * @param right The right coordinate of the rectangle to invalidate.
11279     * @param bottom The bottom coordinate of the rectangle to invalidate.
11280     *
11281     * @see #invalidate(int, int, int, int)
11282     * @see #invalidate(Rect)
11283     * @see #postInvalidate(int, int, int, int)
11284     */
11285    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
11286            int right, int bottom) {
11287
11288        // We try only with the AttachInfo because there's no point in invalidating
11289        // if we are not attached to our window
11290        final AttachInfo attachInfo = mAttachInfo;
11291        if (attachInfo != null) {
11292            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
11293            info.target = this;
11294            info.left = left;
11295            info.top = top;
11296            info.right = right;
11297            info.bottom = bottom;
11298
11299            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
11300        }
11301    }
11302
11303    /**
11304     * <p>Cause an invalidate to happen on the next animation time step, typically the
11305     * next display frame.</p>
11306     *
11307     * <p>This method can be invoked from outside of the UI thread
11308     * only when this View is attached to a window.</p>
11309     *
11310     * @see #invalidate()
11311     */
11312    public void postInvalidateOnAnimation() {
11313        // We try only with the AttachInfo because there's no point in invalidating
11314        // if we are not attached to our window
11315        final AttachInfo attachInfo = mAttachInfo;
11316        if (attachInfo != null) {
11317            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
11318        }
11319    }
11320
11321    /**
11322     * <p>Cause an invalidate of the specified area to happen on the next animation
11323     * time step, typically the next display frame.</p>
11324     *
11325     * <p>This method can be invoked from outside of the UI thread
11326     * only when this View is attached to a window.</p>
11327     *
11328     * @param left The left coordinate of the rectangle to invalidate.
11329     * @param top The top coordinate of the rectangle to invalidate.
11330     * @param right The right coordinate of the rectangle to invalidate.
11331     * @param bottom The bottom coordinate of the rectangle to invalidate.
11332     *
11333     * @see #invalidate(int, int, int, int)
11334     * @see #invalidate(Rect)
11335     */
11336    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
11337        // We try only with the AttachInfo because there's no point in invalidating
11338        // if we are not attached to our window
11339        final AttachInfo attachInfo = mAttachInfo;
11340        if (attachInfo != null) {
11341            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
11342            info.target = this;
11343            info.left = left;
11344            info.top = top;
11345            info.right = right;
11346            info.bottom = bottom;
11347
11348            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
11349        }
11350    }
11351
11352    /**
11353     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
11354     * This event is sent at most once every
11355     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
11356     */
11357    private void postSendViewScrolledAccessibilityEventCallback() {
11358        if (mSendViewScrolledAccessibilityEvent == null) {
11359            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
11360        }
11361        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
11362            mSendViewScrolledAccessibilityEvent.mIsPending = true;
11363            postDelayed(mSendViewScrolledAccessibilityEvent,
11364                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
11365        }
11366    }
11367
11368    /**
11369     * Called by a parent to request that a child update its values for mScrollX
11370     * and mScrollY if necessary. This will typically be done if the child is
11371     * animating a scroll using a {@link android.widget.Scroller Scroller}
11372     * object.
11373     */
11374    public void computeScroll() {
11375    }
11376
11377    /**
11378     * <p>Indicate whether the horizontal edges are faded when the view is
11379     * scrolled horizontally.</p>
11380     *
11381     * @return true if the horizontal edges should are faded on scroll, false
11382     *         otherwise
11383     *
11384     * @see #setHorizontalFadingEdgeEnabled(boolean)
11385     *
11386     * @attr ref android.R.styleable#View_requiresFadingEdge
11387     */
11388    public boolean isHorizontalFadingEdgeEnabled() {
11389        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
11390    }
11391
11392    /**
11393     * <p>Define whether the horizontal edges should be faded when this view
11394     * is scrolled horizontally.</p>
11395     *
11396     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
11397     *                                    be faded when the view is scrolled
11398     *                                    horizontally
11399     *
11400     * @see #isHorizontalFadingEdgeEnabled()
11401     *
11402     * @attr ref android.R.styleable#View_requiresFadingEdge
11403     */
11404    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
11405        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
11406            if (horizontalFadingEdgeEnabled) {
11407                initScrollCache();
11408            }
11409
11410            mViewFlags ^= FADING_EDGE_HORIZONTAL;
11411        }
11412    }
11413
11414    /**
11415     * <p>Indicate whether the vertical edges are faded when the view is
11416     * scrolled horizontally.</p>
11417     *
11418     * @return true if the vertical edges should are faded on scroll, false
11419     *         otherwise
11420     *
11421     * @see #setVerticalFadingEdgeEnabled(boolean)
11422     *
11423     * @attr ref android.R.styleable#View_requiresFadingEdge
11424     */
11425    public boolean isVerticalFadingEdgeEnabled() {
11426        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
11427    }
11428
11429    /**
11430     * <p>Define whether the vertical edges should be faded when this view
11431     * is scrolled vertically.</p>
11432     *
11433     * @param verticalFadingEdgeEnabled true if the vertical edges should
11434     *                                  be faded when the view is scrolled
11435     *                                  vertically
11436     *
11437     * @see #isVerticalFadingEdgeEnabled()
11438     *
11439     * @attr ref android.R.styleable#View_requiresFadingEdge
11440     */
11441    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
11442        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
11443            if (verticalFadingEdgeEnabled) {
11444                initScrollCache();
11445            }
11446
11447            mViewFlags ^= FADING_EDGE_VERTICAL;
11448        }
11449    }
11450
11451    /**
11452     * Returns the strength, or intensity, of the top faded edge. The strength is
11453     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11454     * returns 0.0 or 1.0 but no value in between.
11455     *
11456     * Subclasses should override this method to provide a smoother fade transition
11457     * when scrolling occurs.
11458     *
11459     * @return the intensity of the top fade as a float between 0.0f and 1.0f
11460     */
11461    protected float getTopFadingEdgeStrength() {
11462        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
11463    }
11464
11465    /**
11466     * Returns the strength, or intensity, of the bottom faded edge. The strength is
11467     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11468     * returns 0.0 or 1.0 but no value in between.
11469     *
11470     * Subclasses should override this method to provide a smoother fade transition
11471     * when scrolling occurs.
11472     *
11473     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
11474     */
11475    protected float getBottomFadingEdgeStrength() {
11476        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
11477                computeVerticalScrollRange() ? 1.0f : 0.0f;
11478    }
11479
11480    /**
11481     * Returns the strength, or intensity, of the left faded edge. The strength is
11482     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11483     * returns 0.0 or 1.0 but no value in between.
11484     *
11485     * Subclasses should override this method to provide a smoother fade transition
11486     * when scrolling occurs.
11487     *
11488     * @return the intensity of the left fade as a float between 0.0f and 1.0f
11489     */
11490    protected float getLeftFadingEdgeStrength() {
11491        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
11492    }
11493
11494    /**
11495     * Returns the strength, or intensity, of the right faded edge. The strength is
11496     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11497     * returns 0.0 or 1.0 but no value in between.
11498     *
11499     * Subclasses should override this method to provide a smoother fade transition
11500     * when scrolling occurs.
11501     *
11502     * @return the intensity of the right fade as a float between 0.0f and 1.0f
11503     */
11504    protected float getRightFadingEdgeStrength() {
11505        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
11506                computeHorizontalScrollRange() ? 1.0f : 0.0f;
11507    }
11508
11509    /**
11510     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
11511     * scrollbar is not drawn by default.</p>
11512     *
11513     * @return true if the horizontal scrollbar should be painted, false
11514     *         otherwise
11515     *
11516     * @see #setHorizontalScrollBarEnabled(boolean)
11517     */
11518    public boolean isHorizontalScrollBarEnabled() {
11519        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
11520    }
11521
11522    /**
11523     * <p>Define whether the horizontal scrollbar should be drawn or not. The
11524     * scrollbar is not drawn by default.</p>
11525     *
11526     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
11527     *                                   be painted
11528     *
11529     * @see #isHorizontalScrollBarEnabled()
11530     */
11531    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
11532        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
11533            mViewFlags ^= SCROLLBARS_HORIZONTAL;
11534            computeOpaqueFlags();
11535            resolvePadding();
11536        }
11537    }
11538
11539    /**
11540     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
11541     * scrollbar is not drawn by default.</p>
11542     *
11543     * @return true if the vertical scrollbar should be painted, false
11544     *         otherwise
11545     *
11546     * @see #setVerticalScrollBarEnabled(boolean)
11547     */
11548    public boolean isVerticalScrollBarEnabled() {
11549        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
11550    }
11551
11552    /**
11553     * <p>Define whether the vertical scrollbar should be drawn or not. The
11554     * scrollbar is not drawn by default.</p>
11555     *
11556     * @param verticalScrollBarEnabled true if the vertical scrollbar should
11557     *                                 be painted
11558     *
11559     * @see #isVerticalScrollBarEnabled()
11560     */
11561    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
11562        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
11563            mViewFlags ^= SCROLLBARS_VERTICAL;
11564            computeOpaqueFlags();
11565            resolvePadding();
11566        }
11567    }
11568
11569    /**
11570     * @hide
11571     */
11572    protected void recomputePadding() {
11573        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
11574    }
11575
11576    /**
11577     * Define whether scrollbars will fade when the view is not scrolling.
11578     *
11579     * @param fadeScrollbars wheter to enable fading
11580     *
11581     * @attr ref android.R.styleable#View_fadeScrollbars
11582     */
11583    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
11584        initScrollCache();
11585        final ScrollabilityCache scrollabilityCache = mScrollCache;
11586        scrollabilityCache.fadeScrollBars = fadeScrollbars;
11587        if (fadeScrollbars) {
11588            scrollabilityCache.state = ScrollabilityCache.OFF;
11589        } else {
11590            scrollabilityCache.state = ScrollabilityCache.ON;
11591        }
11592    }
11593
11594    /**
11595     *
11596     * Returns true if scrollbars will fade when this view is not scrolling
11597     *
11598     * @return true if scrollbar fading is enabled
11599     *
11600     * @attr ref android.R.styleable#View_fadeScrollbars
11601     */
11602    public boolean isScrollbarFadingEnabled() {
11603        return mScrollCache != null && mScrollCache.fadeScrollBars;
11604    }
11605
11606    /**
11607     *
11608     * Returns the delay before scrollbars fade.
11609     *
11610     * @return the delay before scrollbars fade
11611     *
11612     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
11613     */
11614    public int getScrollBarDefaultDelayBeforeFade() {
11615        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
11616                mScrollCache.scrollBarDefaultDelayBeforeFade;
11617    }
11618
11619    /**
11620     * Define the delay before scrollbars fade.
11621     *
11622     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
11623     *
11624     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
11625     */
11626    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
11627        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
11628    }
11629
11630    /**
11631     *
11632     * Returns the scrollbar fade duration.
11633     *
11634     * @return the scrollbar fade duration
11635     *
11636     * @attr ref android.R.styleable#View_scrollbarFadeDuration
11637     */
11638    public int getScrollBarFadeDuration() {
11639        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
11640                mScrollCache.scrollBarFadeDuration;
11641    }
11642
11643    /**
11644     * Define the scrollbar fade duration.
11645     *
11646     * @param scrollBarFadeDuration - the scrollbar fade duration
11647     *
11648     * @attr ref android.R.styleable#View_scrollbarFadeDuration
11649     */
11650    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
11651        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
11652    }
11653
11654    /**
11655     *
11656     * Returns the scrollbar size.
11657     *
11658     * @return the scrollbar size
11659     *
11660     * @attr ref android.R.styleable#View_scrollbarSize
11661     */
11662    public int getScrollBarSize() {
11663        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
11664                mScrollCache.scrollBarSize;
11665    }
11666
11667    /**
11668     * Define the scrollbar size.
11669     *
11670     * @param scrollBarSize - the scrollbar size
11671     *
11672     * @attr ref android.R.styleable#View_scrollbarSize
11673     */
11674    public void setScrollBarSize(int scrollBarSize) {
11675        getScrollCache().scrollBarSize = scrollBarSize;
11676    }
11677
11678    /**
11679     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
11680     * inset. When inset, they add to the padding of the view. And the scrollbars
11681     * can be drawn inside the padding area or on the edge of the view. For example,
11682     * if a view has a background drawable and you want to draw the scrollbars
11683     * inside the padding specified by the drawable, you can use
11684     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
11685     * appear at the edge of the view, ignoring the padding, then you can use
11686     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
11687     * @param style the style of the scrollbars. Should be one of
11688     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
11689     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
11690     * @see #SCROLLBARS_INSIDE_OVERLAY
11691     * @see #SCROLLBARS_INSIDE_INSET
11692     * @see #SCROLLBARS_OUTSIDE_OVERLAY
11693     * @see #SCROLLBARS_OUTSIDE_INSET
11694     *
11695     * @attr ref android.R.styleable#View_scrollbarStyle
11696     */
11697    public void setScrollBarStyle(int style) {
11698        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
11699            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
11700            computeOpaqueFlags();
11701            resolvePadding();
11702        }
11703    }
11704
11705    /**
11706     * <p>Returns the current scrollbar style.</p>
11707     * @return the current scrollbar style
11708     * @see #SCROLLBARS_INSIDE_OVERLAY
11709     * @see #SCROLLBARS_INSIDE_INSET
11710     * @see #SCROLLBARS_OUTSIDE_OVERLAY
11711     * @see #SCROLLBARS_OUTSIDE_INSET
11712     *
11713     * @attr ref android.R.styleable#View_scrollbarStyle
11714     */
11715    @ViewDebug.ExportedProperty(mapping = {
11716            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
11717            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
11718            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
11719            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
11720    })
11721    public int getScrollBarStyle() {
11722        return mViewFlags & SCROLLBARS_STYLE_MASK;
11723    }
11724
11725    /**
11726     * <p>Compute the horizontal range that the horizontal scrollbar
11727     * represents.</p>
11728     *
11729     * <p>The range is expressed in arbitrary units that must be the same as the
11730     * units used by {@link #computeHorizontalScrollExtent()} and
11731     * {@link #computeHorizontalScrollOffset()}.</p>
11732     *
11733     * <p>The default range is the drawing width of this view.</p>
11734     *
11735     * @return the total horizontal range represented by the horizontal
11736     *         scrollbar
11737     *
11738     * @see #computeHorizontalScrollExtent()
11739     * @see #computeHorizontalScrollOffset()
11740     * @see android.widget.ScrollBarDrawable
11741     */
11742    protected int computeHorizontalScrollRange() {
11743        return getWidth();
11744    }
11745
11746    /**
11747     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
11748     * within the horizontal range. This value is used to compute the position
11749     * of the thumb within the scrollbar's track.</p>
11750     *
11751     * <p>The range is expressed in arbitrary units that must be the same as the
11752     * units used by {@link #computeHorizontalScrollRange()} and
11753     * {@link #computeHorizontalScrollExtent()}.</p>
11754     *
11755     * <p>The default offset is the scroll offset of this view.</p>
11756     *
11757     * @return the horizontal offset of the scrollbar's thumb
11758     *
11759     * @see #computeHorizontalScrollRange()
11760     * @see #computeHorizontalScrollExtent()
11761     * @see android.widget.ScrollBarDrawable
11762     */
11763    protected int computeHorizontalScrollOffset() {
11764        return mScrollX;
11765    }
11766
11767    /**
11768     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
11769     * within the horizontal range. This value is used to compute the length
11770     * of the thumb within the scrollbar's track.</p>
11771     *
11772     * <p>The range is expressed in arbitrary units that must be the same as the
11773     * units used by {@link #computeHorizontalScrollRange()} and
11774     * {@link #computeHorizontalScrollOffset()}.</p>
11775     *
11776     * <p>The default extent is the drawing width of this view.</p>
11777     *
11778     * @return the horizontal extent of the scrollbar's thumb
11779     *
11780     * @see #computeHorizontalScrollRange()
11781     * @see #computeHorizontalScrollOffset()
11782     * @see android.widget.ScrollBarDrawable
11783     */
11784    protected int computeHorizontalScrollExtent() {
11785        return getWidth();
11786    }
11787
11788    /**
11789     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
11790     *
11791     * <p>The range is expressed in arbitrary units that must be the same as the
11792     * units used by {@link #computeVerticalScrollExtent()} and
11793     * {@link #computeVerticalScrollOffset()}.</p>
11794     *
11795     * @return the total vertical range represented by the vertical scrollbar
11796     *
11797     * <p>The default range is the drawing height of this view.</p>
11798     *
11799     * @see #computeVerticalScrollExtent()
11800     * @see #computeVerticalScrollOffset()
11801     * @see android.widget.ScrollBarDrawable
11802     */
11803    protected int computeVerticalScrollRange() {
11804        return getHeight();
11805    }
11806
11807    /**
11808     * <p>Compute the vertical offset of the vertical scrollbar's thumb
11809     * within the horizontal range. This value is used to compute the position
11810     * of the thumb within the scrollbar's track.</p>
11811     *
11812     * <p>The range is expressed in arbitrary units that must be the same as the
11813     * units used by {@link #computeVerticalScrollRange()} and
11814     * {@link #computeVerticalScrollExtent()}.</p>
11815     *
11816     * <p>The default offset is the scroll offset of this view.</p>
11817     *
11818     * @return the vertical offset of the scrollbar's thumb
11819     *
11820     * @see #computeVerticalScrollRange()
11821     * @see #computeVerticalScrollExtent()
11822     * @see android.widget.ScrollBarDrawable
11823     */
11824    protected int computeVerticalScrollOffset() {
11825        return mScrollY;
11826    }
11827
11828    /**
11829     * <p>Compute the vertical extent of the horizontal scrollbar's thumb
11830     * within the vertical range. This value is used to compute the length
11831     * of the thumb within the scrollbar's track.</p>
11832     *
11833     * <p>The range is expressed in arbitrary units that must be the same as the
11834     * units used by {@link #computeVerticalScrollRange()} and
11835     * {@link #computeVerticalScrollOffset()}.</p>
11836     *
11837     * <p>The default extent is the drawing height of this view.</p>
11838     *
11839     * @return the vertical extent of the scrollbar's thumb
11840     *
11841     * @see #computeVerticalScrollRange()
11842     * @see #computeVerticalScrollOffset()
11843     * @see android.widget.ScrollBarDrawable
11844     */
11845    protected int computeVerticalScrollExtent() {
11846        return getHeight();
11847    }
11848
11849    /**
11850     * Check if this view can be scrolled horizontally in a certain direction.
11851     *
11852     * @param direction Negative to check scrolling left, positive to check scrolling right.
11853     * @return true if this view can be scrolled in the specified direction, false otherwise.
11854     */
11855    public boolean canScrollHorizontally(int direction) {
11856        final int offset = computeHorizontalScrollOffset();
11857        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
11858        if (range == 0) return false;
11859        if (direction < 0) {
11860            return offset > 0;
11861        } else {
11862            return offset < range - 1;
11863        }
11864    }
11865
11866    /**
11867     * Check if this view can be scrolled vertically in a certain direction.
11868     *
11869     * @param direction Negative to check scrolling up, positive to check scrolling down.
11870     * @return true if this view can be scrolled in the specified direction, false otherwise.
11871     */
11872    public boolean canScrollVertically(int direction) {
11873        final int offset = computeVerticalScrollOffset();
11874        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
11875        if (range == 0) return false;
11876        if (direction < 0) {
11877            return offset > 0;
11878        } else {
11879            return offset < range - 1;
11880        }
11881    }
11882
11883    /**
11884     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
11885     * scrollbars are painted only if they have been awakened first.</p>
11886     *
11887     * @param canvas the canvas on which to draw the scrollbars
11888     *
11889     * @see #awakenScrollBars(int)
11890     */
11891    protected final void onDrawScrollBars(Canvas canvas) {
11892        // scrollbars are drawn only when the animation is running
11893        final ScrollabilityCache cache = mScrollCache;
11894        if (cache != null) {
11895
11896            int state = cache.state;
11897
11898            if (state == ScrollabilityCache.OFF) {
11899                return;
11900            }
11901
11902            boolean invalidate = false;
11903
11904            if (state == ScrollabilityCache.FADING) {
11905                // We're fading -- get our fade interpolation
11906                if (cache.interpolatorValues == null) {
11907                    cache.interpolatorValues = new float[1];
11908                }
11909
11910                float[] values = cache.interpolatorValues;
11911
11912                // Stops the animation if we're done
11913                if (cache.scrollBarInterpolator.timeToValues(values) ==
11914                        Interpolator.Result.FREEZE_END) {
11915                    cache.state = ScrollabilityCache.OFF;
11916                } else {
11917                    cache.scrollBar.setAlpha(Math.round(values[0]));
11918                }
11919
11920                // This will make the scroll bars inval themselves after
11921                // drawing. We only want this when we're fading so that
11922                // we prevent excessive redraws
11923                invalidate = true;
11924            } else {
11925                // We're just on -- but we may have been fading before so
11926                // reset alpha
11927                cache.scrollBar.setAlpha(255);
11928            }
11929
11930
11931            final int viewFlags = mViewFlags;
11932
11933            final boolean drawHorizontalScrollBar =
11934                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
11935            final boolean drawVerticalScrollBar =
11936                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
11937                && !isVerticalScrollBarHidden();
11938
11939            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
11940                final int width = mRight - mLeft;
11941                final int height = mBottom - mTop;
11942
11943                final ScrollBarDrawable scrollBar = cache.scrollBar;
11944
11945                final int scrollX = mScrollX;
11946                final int scrollY = mScrollY;
11947                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
11948
11949                int left;
11950                int top;
11951                int right;
11952                int bottom;
11953
11954                if (drawHorizontalScrollBar) {
11955                    int size = scrollBar.getSize(false);
11956                    if (size <= 0) {
11957                        size = cache.scrollBarSize;
11958                    }
11959
11960                    scrollBar.setParameters(computeHorizontalScrollRange(),
11961                                            computeHorizontalScrollOffset(),
11962                                            computeHorizontalScrollExtent(), false);
11963                    final int verticalScrollBarGap = drawVerticalScrollBar ?
11964                            getVerticalScrollbarWidth() : 0;
11965                    top = scrollY + height - size - (mUserPaddingBottom & inside);
11966                    left = scrollX + (mPaddingLeft & inside);
11967                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
11968                    bottom = top + size;
11969                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
11970                    if (invalidate) {
11971                        invalidate(left, top, right, bottom);
11972                    }
11973                }
11974
11975                if (drawVerticalScrollBar) {
11976                    int size = scrollBar.getSize(true);
11977                    if (size <= 0) {
11978                        size = cache.scrollBarSize;
11979                    }
11980
11981                    scrollBar.setParameters(computeVerticalScrollRange(),
11982                                            computeVerticalScrollOffset(),
11983                                            computeVerticalScrollExtent(), true);
11984                    int verticalScrollbarPosition = mVerticalScrollbarPosition;
11985                    if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
11986                        verticalScrollbarPosition = isLayoutRtl() ?
11987                                SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
11988                    }
11989                    switch (verticalScrollbarPosition) {
11990                        default:
11991                        case SCROLLBAR_POSITION_RIGHT:
11992                            left = scrollX + width - size - (mUserPaddingRight & inside);
11993                            break;
11994                        case SCROLLBAR_POSITION_LEFT:
11995                            left = scrollX + (mUserPaddingLeft & inside);
11996                            break;
11997                    }
11998                    top = scrollY + (mPaddingTop & inside);
11999                    right = left + size;
12000                    bottom = scrollY + height - (mUserPaddingBottom & inside);
12001                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
12002                    if (invalidate) {
12003                        invalidate(left, top, right, bottom);
12004                    }
12005                }
12006            }
12007        }
12008    }
12009
12010    /**
12011     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
12012     * FastScroller is visible.
12013     * @return whether to temporarily hide the vertical scrollbar
12014     * @hide
12015     */
12016    protected boolean isVerticalScrollBarHidden() {
12017        return false;
12018    }
12019
12020    /**
12021     * <p>Draw the horizontal scrollbar if
12022     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
12023     *
12024     * @param canvas the canvas on which to draw the scrollbar
12025     * @param scrollBar the scrollbar's drawable
12026     *
12027     * @see #isHorizontalScrollBarEnabled()
12028     * @see #computeHorizontalScrollRange()
12029     * @see #computeHorizontalScrollExtent()
12030     * @see #computeHorizontalScrollOffset()
12031     * @see android.widget.ScrollBarDrawable
12032     * @hide
12033     */
12034    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
12035            int l, int t, int r, int b) {
12036        scrollBar.setBounds(l, t, r, b);
12037        scrollBar.draw(canvas);
12038    }
12039
12040    /**
12041     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
12042     * returns true.</p>
12043     *
12044     * @param canvas the canvas on which to draw the scrollbar
12045     * @param scrollBar the scrollbar's drawable
12046     *
12047     * @see #isVerticalScrollBarEnabled()
12048     * @see #computeVerticalScrollRange()
12049     * @see #computeVerticalScrollExtent()
12050     * @see #computeVerticalScrollOffset()
12051     * @see android.widget.ScrollBarDrawable
12052     * @hide
12053     */
12054    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
12055            int l, int t, int r, int b) {
12056        scrollBar.setBounds(l, t, r, b);
12057        scrollBar.draw(canvas);
12058    }
12059
12060    /**
12061     * Implement this to do your drawing.
12062     *
12063     * @param canvas the canvas on which the background will be drawn
12064     */
12065    protected void onDraw(Canvas canvas) {
12066    }
12067
12068    /*
12069     * Caller is responsible for calling requestLayout if necessary.
12070     * (This allows addViewInLayout to not request a new layout.)
12071     */
12072    void assignParent(ViewParent parent) {
12073        if (mParent == null) {
12074            mParent = parent;
12075        } else if (parent == null) {
12076            mParent = null;
12077        } else {
12078            throw new RuntimeException("view " + this + " being added, but"
12079                    + " it already has a parent");
12080        }
12081    }
12082
12083    /**
12084     * This is called when the view is attached to a window.  At this point it
12085     * has a Surface and will start drawing.  Note that this function is
12086     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
12087     * however it may be called any time before the first onDraw -- including
12088     * before or after {@link #onMeasure(int, int)}.
12089     *
12090     * @see #onDetachedFromWindow()
12091     */
12092    protected void onAttachedToWindow() {
12093        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
12094            mParent.requestTransparentRegion(this);
12095        }
12096
12097        if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
12098            initialAwakenScrollBars();
12099            mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
12100        }
12101
12102        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
12103
12104        jumpDrawablesToCurrentState();
12105
12106        resetSubtreeAccessibilityStateChanged();
12107
12108        if (isFocused()) {
12109            InputMethodManager imm = InputMethodManager.peekInstance();
12110            imm.focusIn(this);
12111        }
12112
12113        if (mDisplayList != null) {
12114            mDisplayList.clearDirty();
12115        }
12116    }
12117
12118    /**
12119     * Resolve all RTL related properties.
12120     *
12121     * @return true if resolution of RTL properties has been done
12122     *
12123     * @hide
12124     */
12125    public boolean resolveRtlPropertiesIfNeeded() {
12126        if (!needRtlPropertiesResolution()) return false;
12127
12128        // Order is important here: LayoutDirection MUST be resolved first
12129        if (!isLayoutDirectionResolved()) {
12130            resolveLayoutDirection();
12131            resolveLayoutParams();
12132        }
12133        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
12134        if (!isTextDirectionResolved()) {
12135            resolveTextDirection();
12136        }
12137        if (!isTextAlignmentResolved()) {
12138            resolveTextAlignment();
12139        }
12140        // Should resolve Drawables before Padding because we need the layout direction of the
12141        // Drawable to correctly resolve Padding.
12142        if (!isDrawablesResolved()) {
12143            resolveDrawables();
12144        }
12145        if (!isPaddingResolved()) {
12146            resolvePadding();
12147        }
12148        onRtlPropertiesChanged(getLayoutDirection());
12149        return true;
12150    }
12151
12152    /**
12153     * Reset resolution of all RTL related properties.
12154     *
12155     * @hide
12156     */
12157    public void resetRtlProperties() {
12158        resetResolvedLayoutDirection();
12159        resetResolvedTextDirection();
12160        resetResolvedTextAlignment();
12161        resetResolvedPadding();
12162        resetResolvedDrawables();
12163    }
12164
12165    /**
12166     * @see #onScreenStateChanged(int)
12167     */
12168    void dispatchScreenStateChanged(int screenState) {
12169        onScreenStateChanged(screenState);
12170    }
12171
12172    /**
12173     * This method is called whenever the state of the screen this view is
12174     * attached to changes. A state change will usually occurs when the screen
12175     * turns on or off (whether it happens automatically or the user does it
12176     * manually.)
12177     *
12178     * @param screenState The new state of the screen. Can be either
12179     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
12180     */
12181    public void onScreenStateChanged(int screenState) {
12182    }
12183
12184    /**
12185     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
12186     */
12187    private boolean hasRtlSupport() {
12188        return mContext.getApplicationInfo().hasRtlSupport();
12189    }
12190
12191    /**
12192     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
12193     * RTL not supported)
12194     */
12195    private boolean isRtlCompatibilityMode() {
12196        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
12197        return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport();
12198    }
12199
12200    /**
12201     * @return true if RTL properties need resolution.
12202     *
12203     */
12204    private boolean needRtlPropertiesResolution() {
12205        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
12206    }
12207
12208    /**
12209     * Called when any RTL property (layout direction or text direction or text alignment) has
12210     * been changed.
12211     *
12212     * Subclasses need to override this method to take care of cached information that depends on the
12213     * resolved layout direction, or to inform child views that inherit their layout direction.
12214     *
12215     * The default implementation does nothing.
12216     *
12217     * @param layoutDirection the direction of the layout
12218     *
12219     * @see #LAYOUT_DIRECTION_LTR
12220     * @see #LAYOUT_DIRECTION_RTL
12221     */
12222    public void onRtlPropertiesChanged(int layoutDirection) {
12223    }
12224
12225    /**
12226     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
12227     * that the parent directionality can and will be resolved before its children.
12228     *
12229     * @return true if resolution has been done, false otherwise.
12230     *
12231     * @hide
12232     */
12233    public boolean resolveLayoutDirection() {
12234        // Clear any previous layout direction resolution
12235        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
12236
12237        if (hasRtlSupport()) {
12238            // Set resolved depending on layout direction
12239            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
12240                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
12241                case LAYOUT_DIRECTION_INHERIT:
12242                    // We cannot resolve yet. LTR is by default and let the resolution happen again
12243                    // later to get the correct resolved value
12244                    if (!canResolveLayoutDirection()) return false;
12245
12246                    // Parent has not yet resolved, LTR is still the default
12247                    try {
12248                        if (!mParent.isLayoutDirectionResolved()) return false;
12249
12250                        if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
12251                            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12252                        }
12253                    } catch (AbstractMethodError e) {
12254                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
12255                                " does not fully implement ViewParent", e);
12256                    }
12257                    break;
12258                case LAYOUT_DIRECTION_RTL:
12259                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12260                    break;
12261                case LAYOUT_DIRECTION_LOCALE:
12262                    if((LAYOUT_DIRECTION_RTL ==
12263                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
12264                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12265                    }
12266                    break;
12267                default:
12268                    // Nothing to do, LTR by default
12269            }
12270        }
12271
12272        // Set to resolved
12273        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
12274        return true;
12275    }
12276
12277    /**
12278     * Check if layout direction resolution can be done.
12279     *
12280     * @return true if layout direction resolution can be done otherwise return false.
12281     */
12282    public boolean canResolveLayoutDirection() {
12283        switch (getRawLayoutDirection()) {
12284            case LAYOUT_DIRECTION_INHERIT:
12285                if (mParent != null) {
12286                    try {
12287                        return mParent.canResolveLayoutDirection();
12288                    } catch (AbstractMethodError e) {
12289                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
12290                                " does not fully implement ViewParent", e);
12291                    }
12292                }
12293                return false;
12294
12295            default:
12296                return true;
12297        }
12298    }
12299
12300    /**
12301     * Reset the resolved layout direction. Layout direction will be resolved during a call to
12302     * {@link #onMeasure(int, int)}.
12303     *
12304     * @hide
12305     */
12306    public void resetResolvedLayoutDirection() {
12307        // Reset the current resolved bits
12308        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
12309    }
12310
12311    /**
12312     * @return true if the layout direction is inherited.
12313     *
12314     * @hide
12315     */
12316    public boolean isLayoutDirectionInherited() {
12317        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
12318    }
12319
12320    /**
12321     * @return true if layout direction has been resolved.
12322     */
12323    public boolean isLayoutDirectionResolved() {
12324        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
12325    }
12326
12327    /**
12328     * Return if padding has been resolved
12329     *
12330     * @hide
12331     */
12332    boolean isPaddingResolved() {
12333        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
12334    }
12335
12336    /**
12337     * Resolves padding depending on layout direction, if applicable, and
12338     * recomputes internal padding values to adjust for scroll bars.
12339     *
12340     * @hide
12341     */
12342    public void resolvePadding() {
12343        final int resolvedLayoutDirection = getLayoutDirection();
12344
12345        if (!isRtlCompatibilityMode()) {
12346            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
12347            // If start / end padding are defined, they will be resolved (hence overriding) to
12348            // left / right or right / left depending on the resolved layout direction.
12349            // If start / end padding are not defined, use the left / right ones.
12350            if (mBackground != null && mUseBackgroundPadding) {
12351                Rect padding = sThreadLocal.get();
12352                if (padding == null) {
12353                    padding = new Rect();
12354                    sThreadLocal.set(padding);
12355                }
12356                mBackground.getPadding(padding);
12357                mUserPaddingLeftInitial = padding.left;
12358                mUserPaddingRightInitial = padding.right;
12359            }
12360            switch (resolvedLayoutDirection) {
12361                case LAYOUT_DIRECTION_RTL:
12362                    if (mUserPaddingStart != UNDEFINED_PADDING) {
12363                        mUserPaddingRight = mUserPaddingStart;
12364                    } else {
12365                        mUserPaddingRight = mUserPaddingRightInitial;
12366                    }
12367                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
12368                        mUserPaddingLeft = mUserPaddingEnd;
12369                    } else {
12370                        mUserPaddingLeft = mUserPaddingLeftInitial;
12371                    }
12372                    break;
12373                case LAYOUT_DIRECTION_LTR:
12374                default:
12375                    if (mUserPaddingStart != UNDEFINED_PADDING) {
12376                        mUserPaddingLeft = mUserPaddingStart;
12377                    } else {
12378                        mUserPaddingLeft = mUserPaddingLeftInitial;
12379                    }
12380                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
12381                        mUserPaddingRight = mUserPaddingEnd;
12382                    } else {
12383                        mUserPaddingRight = mUserPaddingRightInitial;
12384                    }
12385            }
12386
12387            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
12388        }
12389
12390        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
12391        onRtlPropertiesChanged(resolvedLayoutDirection);
12392
12393        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
12394    }
12395
12396    /**
12397     * Reset the resolved layout direction.
12398     *
12399     * @hide
12400     */
12401    public void resetResolvedPadding() {
12402        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
12403    }
12404
12405    /**
12406     * This is called when the view is detached from a window.  At this point it
12407     * no longer has a surface for drawing.
12408     *
12409     * @see #onAttachedToWindow()
12410     */
12411    protected void onDetachedFromWindow() {
12412        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
12413        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
12414
12415        removeUnsetPressCallback();
12416        removeLongPressCallback();
12417        removePerformClickCallback();
12418        removeSendViewScrolledAccessibilityEventCallback();
12419
12420        destroyDrawingCache();
12421        destroyLayer(false);
12422
12423        cleanupDraw();
12424
12425        mCurrentAnimation = null;
12426    }
12427
12428    private void cleanupDraw() {
12429        if (mAttachInfo != null) {
12430            if (mDisplayList != null) {
12431                mDisplayList.markDirty();
12432                mAttachInfo.mViewRootImpl.enqueueDisplayList(mDisplayList);
12433            }
12434            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
12435        } else {
12436            // Should never happen
12437            resetDisplayList();
12438        }
12439    }
12440
12441    /**
12442     * This method ensures the hardware renderer is in a valid state
12443     * before executing the specified action.
12444     *
12445     * This method will attempt to set a valid state even if the window
12446     * the renderer is attached to was destroyed.
12447     *
12448     * This method is not guaranteed to work. If the hardware renderer
12449     * does not exist or cannot be put in a valid state, this method
12450     * will not executed the specified action.
12451     *
12452     * The specified action is executed synchronously.
12453     *
12454     * @param action The action to execute after the renderer is in a valid state
12455     *
12456     * @return True if the specified Runnable was executed, false otherwise
12457     *
12458     * @hide
12459     */
12460    public boolean executeHardwareAction(Runnable action) {
12461        //noinspection SimplifiableIfStatement
12462        if (mAttachInfo != null && mAttachInfo.mHardwareRenderer != null) {
12463            return mAttachInfo.mHardwareRenderer.safelyRun(action);
12464        }
12465        return false;
12466    }
12467
12468    void invalidateInheritedLayoutMode(int layoutModeOfRoot) {
12469    }
12470
12471    /**
12472     * @return The number of times this view has been attached to a window
12473     */
12474    protected int getWindowAttachCount() {
12475        return mWindowAttachCount;
12476    }
12477
12478    /**
12479     * Retrieve a unique token identifying the window this view is attached to.
12480     * @return Return the window's token for use in
12481     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
12482     */
12483    public IBinder getWindowToken() {
12484        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
12485    }
12486
12487    /**
12488     * Retrieve the {@link WindowId} for the window this view is
12489     * currently attached to.
12490     */
12491    public WindowId getWindowId() {
12492        if (mAttachInfo == null) {
12493            return null;
12494        }
12495        if (mAttachInfo.mWindowId == null) {
12496            try {
12497                mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId(
12498                        mAttachInfo.mWindowToken);
12499                mAttachInfo.mWindowId = new WindowId(
12500                        mAttachInfo.mIWindowId);
12501            } catch (RemoteException e) {
12502            }
12503        }
12504        return mAttachInfo.mWindowId;
12505    }
12506
12507    /**
12508     * Retrieve a unique token identifying the top-level "real" window of
12509     * the window that this view is attached to.  That is, this is like
12510     * {@link #getWindowToken}, except if the window this view in is a panel
12511     * window (attached to another containing window), then the token of
12512     * the containing window is returned instead.
12513     *
12514     * @return Returns the associated window token, either
12515     * {@link #getWindowToken()} or the containing window's token.
12516     */
12517    public IBinder getApplicationWindowToken() {
12518        AttachInfo ai = mAttachInfo;
12519        if (ai != null) {
12520            IBinder appWindowToken = ai.mPanelParentWindowToken;
12521            if (appWindowToken == null) {
12522                appWindowToken = ai.mWindowToken;
12523            }
12524            return appWindowToken;
12525        }
12526        return null;
12527    }
12528
12529    /**
12530     * Gets the logical display to which the view's window has been attached.
12531     *
12532     * @return The logical display, or null if the view is not currently attached to a window.
12533     */
12534    public Display getDisplay() {
12535        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
12536    }
12537
12538    /**
12539     * Retrieve private session object this view hierarchy is using to
12540     * communicate with the window manager.
12541     * @return the session object to communicate with the window manager
12542     */
12543    /*package*/ IWindowSession getWindowSession() {
12544        return mAttachInfo != null ? mAttachInfo.mSession : null;
12545    }
12546
12547    /**
12548     * @param info the {@link android.view.View.AttachInfo} to associated with
12549     *        this view
12550     */
12551    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
12552        //System.out.println("Attached! " + this);
12553        mAttachInfo = info;
12554        if (mOverlay != null) {
12555            mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
12556        }
12557        mWindowAttachCount++;
12558        // We will need to evaluate the drawable state at least once.
12559        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
12560        if (mFloatingTreeObserver != null) {
12561            info.mTreeObserver.merge(mFloatingTreeObserver);
12562            mFloatingTreeObserver = null;
12563        }
12564        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
12565            mAttachInfo.mScrollContainers.add(this);
12566            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
12567        }
12568        performCollectViewAttributes(mAttachInfo, visibility);
12569        onAttachedToWindow();
12570
12571        ListenerInfo li = mListenerInfo;
12572        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
12573                li != null ? li.mOnAttachStateChangeListeners : null;
12574        if (listeners != null && listeners.size() > 0) {
12575            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
12576            // perform the dispatching. The iterator is a safe guard against listeners that
12577            // could mutate the list by calling the various add/remove methods. This prevents
12578            // the array from being modified while we iterate it.
12579            for (OnAttachStateChangeListener listener : listeners) {
12580                listener.onViewAttachedToWindow(this);
12581            }
12582        }
12583
12584        int vis = info.mWindowVisibility;
12585        if (vis != GONE) {
12586            onWindowVisibilityChanged(vis);
12587        }
12588        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
12589            // If nobody has evaluated the drawable state yet, then do it now.
12590            refreshDrawableState();
12591        }
12592        needGlobalAttributesUpdate(false);
12593    }
12594
12595    void dispatchDetachedFromWindow() {
12596        AttachInfo info = mAttachInfo;
12597        if (info != null) {
12598            int vis = info.mWindowVisibility;
12599            if (vis != GONE) {
12600                onWindowVisibilityChanged(GONE);
12601            }
12602        }
12603
12604        onDetachedFromWindow();
12605
12606        ListenerInfo li = mListenerInfo;
12607        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
12608                li != null ? li.mOnAttachStateChangeListeners : null;
12609        if (listeners != null && listeners.size() > 0) {
12610            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
12611            // perform the dispatching. The iterator is a safe guard against listeners that
12612            // could mutate the list by calling the various add/remove methods. This prevents
12613            // the array from being modified while we iterate it.
12614            for (OnAttachStateChangeListener listener : listeners) {
12615                listener.onViewDetachedFromWindow(this);
12616            }
12617        }
12618
12619        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
12620            mAttachInfo.mScrollContainers.remove(this);
12621            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
12622        }
12623
12624        mAttachInfo = null;
12625        if (mOverlay != null) {
12626            mOverlay.getOverlayView().dispatchDetachedFromWindow();
12627        }
12628    }
12629
12630    /**
12631     * Cancel any deferred high-level input events that were previously posted to the event queue.
12632     *
12633     * <p>Many views post high-level events such as click handlers to the event queue
12634     * to run deferred in order to preserve a desired user experience - clearing visible
12635     * pressed states before executing, etc. This method will abort any events of this nature
12636     * that are currently in flight.</p>
12637     *
12638     * <p>Custom views that generate their own high-level deferred input events should override
12639     * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p>
12640     *
12641     * <p>This will also cancel pending input events for any child views.</p>
12642     *
12643     * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases.
12644     * This will not impact newer events posted after this call that may occur as a result of
12645     * lower-level input events still waiting in the queue. If you are trying to prevent
12646     * double-submitted  events for the duration of some sort of asynchronous transaction
12647     * you should also take other steps to protect against unexpected double inputs e.g. calling
12648     * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when
12649     * the transaction completes, tracking already submitted transaction IDs, etc.</p>
12650     */
12651    public final void cancelPendingInputEvents() {
12652        dispatchCancelPendingInputEvents();
12653    }
12654
12655    /**
12656     * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight.
12657     * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling.
12658     */
12659    void dispatchCancelPendingInputEvents() {
12660        mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER;
12661        onCancelPendingInputEvents();
12662        if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) {
12663            throw new SuperNotCalledException("View " + getClass().getSimpleName() +
12664                    " did not call through to super.onCancelPendingInputEvents()");
12665        }
12666    }
12667
12668    /**
12669     * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or
12670     * a parent view.
12671     *
12672     * <p>This method is responsible for removing any pending high-level input events that were
12673     * posted to the event queue to run later. Custom view classes that post their own deferred
12674     * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or
12675     * {@link android.os.Handler} should override this method, call
12676     * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate.
12677     * </p>
12678     */
12679    public void onCancelPendingInputEvents() {
12680        removePerformClickCallback();
12681        cancelLongPress();
12682        mPrivateFlags3 |= PFLAG3_CALLED_SUPER;
12683    }
12684
12685    /**
12686     * Store this view hierarchy's frozen state into the given container.
12687     *
12688     * @param container The SparseArray in which to save the view's state.
12689     *
12690     * @see #restoreHierarchyState(android.util.SparseArray)
12691     * @see #dispatchSaveInstanceState(android.util.SparseArray)
12692     * @see #onSaveInstanceState()
12693     */
12694    public void saveHierarchyState(SparseArray<Parcelable> container) {
12695        dispatchSaveInstanceState(container);
12696    }
12697
12698    /**
12699     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
12700     * this view and its children. May be overridden to modify how freezing happens to a
12701     * view's children; for example, some views may want to not store state for their children.
12702     *
12703     * @param container The SparseArray in which to save the view's state.
12704     *
12705     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
12706     * @see #saveHierarchyState(android.util.SparseArray)
12707     * @see #onSaveInstanceState()
12708     */
12709    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
12710        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
12711            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
12712            Parcelable state = onSaveInstanceState();
12713            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
12714                throw new IllegalStateException(
12715                        "Derived class did not call super.onSaveInstanceState()");
12716            }
12717            if (state != null) {
12718                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
12719                // + ": " + state);
12720                container.put(mID, state);
12721            }
12722        }
12723    }
12724
12725    /**
12726     * Hook allowing a view to generate a representation of its internal state
12727     * that can later be used to create a new instance with that same state.
12728     * This state should only contain information that is not persistent or can
12729     * not be reconstructed later. For example, you will never store your
12730     * current position on screen because that will be computed again when a
12731     * new instance of the view is placed in its view hierarchy.
12732     * <p>
12733     * Some examples of things you may store here: the current cursor position
12734     * in a text view (but usually not the text itself since that is stored in a
12735     * content provider or other persistent storage), the currently selected
12736     * item in a list view.
12737     *
12738     * @return Returns a Parcelable object containing the view's current dynamic
12739     *         state, or null if there is nothing interesting to save. The
12740     *         default implementation returns null.
12741     * @see #onRestoreInstanceState(android.os.Parcelable)
12742     * @see #saveHierarchyState(android.util.SparseArray)
12743     * @see #dispatchSaveInstanceState(android.util.SparseArray)
12744     * @see #setSaveEnabled(boolean)
12745     */
12746    protected Parcelable onSaveInstanceState() {
12747        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
12748        return BaseSavedState.EMPTY_STATE;
12749    }
12750
12751    /**
12752     * Restore this view hierarchy's frozen state from the given container.
12753     *
12754     * @param container The SparseArray which holds previously frozen states.
12755     *
12756     * @see #saveHierarchyState(android.util.SparseArray)
12757     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
12758     * @see #onRestoreInstanceState(android.os.Parcelable)
12759     */
12760    public void restoreHierarchyState(SparseArray<Parcelable> container) {
12761        dispatchRestoreInstanceState(container);
12762    }
12763
12764    /**
12765     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
12766     * state for this view and its children. May be overridden to modify how restoring
12767     * happens to a view's children; for example, some views may want to not store state
12768     * for their children.
12769     *
12770     * @param container The SparseArray which holds previously saved state.
12771     *
12772     * @see #dispatchSaveInstanceState(android.util.SparseArray)
12773     * @see #restoreHierarchyState(android.util.SparseArray)
12774     * @see #onRestoreInstanceState(android.os.Parcelable)
12775     */
12776    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
12777        if (mID != NO_ID) {
12778            Parcelable state = container.get(mID);
12779            if (state != null) {
12780                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
12781                // + ": " + state);
12782                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
12783                onRestoreInstanceState(state);
12784                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
12785                    throw new IllegalStateException(
12786                            "Derived class did not call super.onRestoreInstanceState()");
12787                }
12788            }
12789        }
12790    }
12791
12792    /**
12793     * Hook allowing a view to re-apply a representation of its internal state that had previously
12794     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
12795     * null state.
12796     *
12797     * @param state The frozen state that had previously been returned by
12798     *        {@link #onSaveInstanceState}.
12799     *
12800     * @see #onSaveInstanceState()
12801     * @see #restoreHierarchyState(android.util.SparseArray)
12802     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
12803     */
12804    protected void onRestoreInstanceState(Parcelable state) {
12805        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
12806        if (state != BaseSavedState.EMPTY_STATE && state != null) {
12807            throw new IllegalArgumentException("Wrong state class, expecting View State but "
12808                    + "received " + state.getClass().toString() + " instead. This usually happens "
12809                    + "when two views of different type have the same id in the same hierarchy. "
12810                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
12811                    + "other views do not use the same id.");
12812        }
12813    }
12814
12815    /**
12816     * <p>Return the time at which the drawing of the view hierarchy started.</p>
12817     *
12818     * @return the drawing start time in milliseconds
12819     */
12820    public long getDrawingTime() {
12821        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
12822    }
12823
12824    /**
12825     * <p>Enables or disables the duplication of the parent's state into this view. When
12826     * duplication is enabled, this view gets its drawable state from its parent rather
12827     * than from its own internal properties.</p>
12828     *
12829     * <p>Note: in the current implementation, setting this property to true after the
12830     * view was added to a ViewGroup might have no effect at all. This property should
12831     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
12832     *
12833     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
12834     * property is enabled, an exception will be thrown.</p>
12835     *
12836     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
12837     * parent, these states should not be affected by this method.</p>
12838     *
12839     * @param enabled True to enable duplication of the parent's drawable state, false
12840     *                to disable it.
12841     *
12842     * @see #getDrawableState()
12843     * @see #isDuplicateParentStateEnabled()
12844     */
12845    public void setDuplicateParentStateEnabled(boolean enabled) {
12846        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
12847    }
12848
12849    /**
12850     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
12851     *
12852     * @return True if this view's drawable state is duplicated from the parent,
12853     *         false otherwise
12854     *
12855     * @see #getDrawableState()
12856     * @see #setDuplicateParentStateEnabled(boolean)
12857     */
12858    public boolean isDuplicateParentStateEnabled() {
12859        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
12860    }
12861
12862    /**
12863     * <p>Specifies the type of layer backing this view. The layer can be
12864     * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
12865     * {@link #LAYER_TYPE_HARDWARE}.</p>
12866     *
12867     * <p>A layer is associated with an optional {@link android.graphics.Paint}
12868     * instance that controls how the layer is composed on screen. The following
12869     * properties of the paint are taken into account when composing the layer:</p>
12870     * <ul>
12871     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
12872     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
12873     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
12874     * </ul>
12875     *
12876     * <p>If this view has an alpha value set to < 1.0 by calling
12877     * {@link #setAlpha(float)}, the alpha value of the layer's paint is superceded
12878     * by this view's alpha value.</p>
12879     *
12880     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE},
12881     * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE}
12882     * for more information on when and how to use layers.</p>
12883     *
12884     * @param layerType The type of layer to use with this view, must be one of
12885     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
12886     *        {@link #LAYER_TYPE_HARDWARE}
12887     * @param paint The paint used to compose the layer. This argument is optional
12888     *        and can be null. It is ignored when the layer type is
12889     *        {@link #LAYER_TYPE_NONE}
12890     *
12891     * @see #getLayerType()
12892     * @see #LAYER_TYPE_NONE
12893     * @see #LAYER_TYPE_SOFTWARE
12894     * @see #LAYER_TYPE_HARDWARE
12895     * @see #setAlpha(float)
12896     *
12897     * @attr ref android.R.styleable#View_layerType
12898     */
12899    public void setLayerType(int layerType, Paint paint) {
12900        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
12901            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
12902                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
12903        }
12904
12905        if (layerType == mLayerType) {
12906            if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) {
12907                mLayerPaint = paint == null ? new Paint() : paint;
12908                invalidateParentCaches();
12909                invalidate(true);
12910            }
12911            return;
12912        }
12913
12914        // Destroy any previous software drawing cache if needed
12915        switch (mLayerType) {
12916            case LAYER_TYPE_HARDWARE:
12917                destroyLayer(false);
12918                // fall through - non-accelerated views may use software layer mechanism instead
12919            case LAYER_TYPE_SOFTWARE:
12920                destroyDrawingCache();
12921                break;
12922            default:
12923                break;
12924        }
12925
12926        mLayerType = layerType;
12927        final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE;
12928        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
12929        mLocalDirtyRect = layerDisabled ? null : new Rect();
12930
12931        invalidateParentCaches();
12932        invalidate(true);
12933    }
12934
12935    /**
12936     * Updates the {@link Paint} object used with the current layer (used only if the current
12937     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
12938     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
12939     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
12940     * ensure that the view gets redrawn immediately.
12941     *
12942     * <p>A layer is associated with an optional {@link android.graphics.Paint}
12943     * instance that controls how the layer is composed on screen. The following
12944     * properties of the paint are taken into account when composing the layer:</p>
12945     * <ul>
12946     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
12947     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
12948     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
12949     * </ul>
12950     *
12951     * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the
12952     * alpha value of the layer's paint is superceded by this view's alpha value.</p>
12953     *
12954     * @param paint The paint used to compose the layer. This argument is optional
12955     *        and can be null. It is ignored when the layer type is
12956     *        {@link #LAYER_TYPE_NONE}
12957     *
12958     * @see #setLayerType(int, android.graphics.Paint)
12959     */
12960    public void setLayerPaint(Paint paint) {
12961        int layerType = getLayerType();
12962        if (layerType != LAYER_TYPE_NONE) {
12963            mLayerPaint = paint == null ? new Paint() : paint;
12964            if (layerType == LAYER_TYPE_HARDWARE) {
12965                HardwareLayer layer = getHardwareLayer();
12966                if (layer != null) {
12967                    layer.setLayerPaint(paint);
12968                }
12969                invalidateViewProperty(false, false);
12970            } else {
12971                invalidate();
12972            }
12973        }
12974    }
12975
12976    /**
12977     * Indicates whether this view has a static layer. A view with layer type
12978     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
12979     * dynamic.
12980     */
12981    boolean hasStaticLayer() {
12982        return true;
12983    }
12984
12985    /**
12986     * Indicates what type of layer is currently associated with this view. By default
12987     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
12988     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
12989     * for more information on the different types of layers.
12990     *
12991     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
12992     *         {@link #LAYER_TYPE_HARDWARE}
12993     *
12994     * @see #setLayerType(int, android.graphics.Paint)
12995     * @see #buildLayer()
12996     * @see #LAYER_TYPE_NONE
12997     * @see #LAYER_TYPE_SOFTWARE
12998     * @see #LAYER_TYPE_HARDWARE
12999     */
13000    public int getLayerType() {
13001        return mLayerType;
13002    }
13003
13004    /**
13005     * Forces this view's layer to be created and this view to be rendered
13006     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
13007     * invoking this method will have no effect.
13008     *
13009     * This method can for instance be used to render a view into its layer before
13010     * starting an animation. If this view is complex, rendering into the layer
13011     * before starting the animation will avoid skipping frames.
13012     *
13013     * @throws IllegalStateException If this view is not attached to a window
13014     *
13015     * @see #setLayerType(int, android.graphics.Paint)
13016     */
13017    public void buildLayer() {
13018        if (mLayerType == LAYER_TYPE_NONE) return;
13019
13020        final AttachInfo attachInfo = mAttachInfo;
13021        if (attachInfo == null) {
13022            throw new IllegalStateException("This view must be attached to a window first");
13023        }
13024
13025        switch (mLayerType) {
13026            case LAYER_TYPE_HARDWARE:
13027                if (attachInfo.mHardwareRenderer != null &&
13028                        attachInfo.mHardwareRenderer.isEnabled() &&
13029                        attachInfo.mHardwareRenderer.validate()) {
13030                    getHardwareLayer();
13031                    // TODO: We need a better way to handle this case
13032                    // If views have registered pre-draw listeners they need
13033                    // to be notified before we build the layer. Those listeners
13034                    // may however rely on other events to happen first so we
13035                    // cannot just invoke them here until they don't cancel the
13036                    // current frame
13037                    if (!attachInfo.mTreeObserver.hasOnPreDrawListeners()) {
13038                        attachInfo.mViewRootImpl.dispatchFlushHardwareLayerUpdates();
13039                    }
13040                }
13041                break;
13042            case LAYER_TYPE_SOFTWARE:
13043                buildDrawingCache(true);
13044                break;
13045        }
13046    }
13047
13048    /**
13049     * <p>Returns a hardware layer that can be used to draw this view again
13050     * without executing its draw method.</p>
13051     *
13052     * @return A HardwareLayer ready to render, or null if an error occurred.
13053     */
13054    HardwareLayer getHardwareLayer() {
13055        if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null ||
13056                !mAttachInfo.mHardwareRenderer.isEnabled()) {
13057            return null;
13058        }
13059
13060        if (!mAttachInfo.mHardwareRenderer.validate()) return null;
13061
13062        final int width = mRight - mLeft;
13063        final int height = mBottom - mTop;
13064
13065        if (width == 0 || height == 0) {
13066            return null;
13067        }
13068
13069        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
13070            if (mHardwareLayer == null) {
13071                mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
13072                        width, height, isOpaque());
13073                mLocalDirtyRect.set(0, 0, width, height);
13074            } else {
13075                if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) {
13076                    if (mHardwareLayer.resize(width, height)) {
13077                        mLocalDirtyRect.set(0, 0, width, height);
13078                    }
13079                }
13080
13081                // This should not be necessary but applications that change
13082                // the parameters of their background drawable without calling
13083                // this.setBackground(Drawable) can leave the view in a bad state
13084                // (for instance isOpaque() returns true, but the background is
13085                // not opaque.)
13086                computeOpaqueFlags();
13087
13088                final boolean opaque = isOpaque();
13089                if (mHardwareLayer.isValid() && mHardwareLayer.isOpaque() != opaque) {
13090                    mHardwareLayer.setOpaque(opaque);
13091                    mLocalDirtyRect.set(0, 0, width, height);
13092                }
13093            }
13094
13095            // The layer is not valid if the underlying GPU resources cannot be allocated
13096            if (!mHardwareLayer.isValid()) {
13097                return null;
13098            }
13099
13100            mHardwareLayer.setLayerPaint(mLayerPaint);
13101            mHardwareLayer.redrawLater(getHardwareLayerDisplayList(mHardwareLayer), mLocalDirtyRect);
13102            ViewRootImpl viewRoot = getViewRootImpl();
13103            if (viewRoot != null) viewRoot.pushHardwareLayerUpdate(mHardwareLayer);
13104
13105            mLocalDirtyRect.setEmpty();
13106        }
13107
13108        return mHardwareLayer;
13109    }
13110
13111    /**
13112     * Destroys this View's hardware layer if possible.
13113     *
13114     * @return True if the layer was destroyed, false otherwise.
13115     *
13116     * @see #setLayerType(int, android.graphics.Paint)
13117     * @see #LAYER_TYPE_HARDWARE
13118     */
13119    boolean destroyLayer(boolean valid) {
13120        if (mHardwareLayer != null) {
13121            AttachInfo info = mAttachInfo;
13122            if (info != null && info.mHardwareRenderer != null &&
13123                    info.mHardwareRenderer.isEnabled() &&
13124                    (valid || info.mHardwareRenderer.validate())) {
13125
13126                info.mHardwareRenderer.cancelLayerUpdate(mHardwareLayer);
13127                mHardwareLayer.destroy();
13128                mHardwareLayer = null;
13129
13130                invalidate(true);
13131                invalidateParentCaches();
13132            }
13133            return true;
13134        }
13135        return false;
13136    }
13137
13138    /**
13139     * Destroys all hardware rendering resources. This method is invoked
13140     * when the system needs to reclaim resources. Upon execution of this
13141     * method, you should free any OpenGL resources created by the view.
13142     *
13143     * Note: you <strong>must</strong> call
13144     * <code>super.destroyHardwareResources()</code> when overriding
13145     * this method.
13146     *
13147     * @hide
13148     */
13149    protected void destroyHardwareResources() {
13150        resetDisplayList();
13151        destroyLayer(true);
13152    }
13153
13154    /**
13155     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
13156     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
13157     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
13158     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
13159     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
13160     * null.</p>
13161     *
13162     * <p>Enabling the drawing cache is similar to
13163     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
13164     * acceleration is turned off. When hardware acceleration is turned on, enabling the
13165     * drawing cache has no effect on rendering because the system uses a different mechanism
13166     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
13167     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
13168     * for information on how to enable software and hardware layers.</p>
13169     *
13170     * <p>This API can be used to manually generate
13171     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
13172     * {@link #getDrawingCache()}.</p>
13173     *
13174     * @param enabled true to enable the drawing cache, false otherwise
13175     *
13176     * @see #isDrawingCacheEnabled()
13177     * @see #getDrawingCache()
13178     * @see #buildDrawingCache()
13179     * @see #setLayerType(int, android.graphics.Paint)
13180     */
13181    public void setDrawingCacheEnabled(boolean enabled) {
13182        mCachingFailed = false;
13183        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
13184    }
13185
13186    /**
13187     * <p>Indicates whether the drawing cache is enabled for this view.</p>
13188     *
13189     * @return true if the drawing cache is enabled
13190     *
13191     * @see #setDrawingCacheEnabled(boolean)
13192     * @see #getDrawingCache()
13193     */
13194    @ViewDebug.ExportedProperty(category = "drawing")
13195    public boolean isDrawingCacheEnabled() {
13196        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
13197    }
13198
13199    /**
13200     * Debugging utility which recursively outputs the dirty state of a view and its
13201     * descendants.
13202     *
13203     * @hide
13204     */
13205    @SuppressWarnings({"UnusedDeclaration"})
13206    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
13207        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
13208                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
13209                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
13210                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
13211        if (clear) {
13212            mPrivateFlags &= clearMask;
13213        }
13214        if (this instanceof ViewGroup) {
13215            ViewGroup parent = (ViewGroup) this;
13216            final int count = parent.getChildCount();
13217            for (int i = 0; i < count; i++) {
13218                final View child = parent.getChildAt(i);
13219                child.outputDirtyFlags(indent + "  ", clear, clearMask);
13220            }
13221        }
13222    }
13223
13224    /**
13225     * This method is used by ViewGroup to cause its children to restore or recreate their
13226     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
13227     * to recreate its own display list, which would happen if it went through the normal
13228     * draw/dispatchDraw mechanisms.
13229     *
13230     * @hide
13231     */
13232    protected void dispatchGetDisplayList() {}
13233
13234    /**
13235     * A view that is not attached or hardware accelerated cannot create a display list.
13236     * This method checks these conditions and returns the appropriate result.
13237     *
13238     * @return true if view has the ability to create a display list, false otherwise.
13239     *
13240     * @hide
13241     */
13242    public boolean canHaveDisplayList() {
13243        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
13244    }
13245
13246    /**
13247     * @return The {@link HardwareRenderer} associated with that view or null if
13248     *         hardware rendering is not supported or this view is not attached
13249     *         to a window.
13250     *
13251     * @hide
13252     */
13253    public HardwareRenderer getHardwareRenderer() {
13254        if (mAttachInfo != null) {
13255            return mAttachInfo.mHardwareRenderer;
13256        }
13257        return null;
13258    }
13259
13260    /**
13261     * Returns a DisplayList. If the incoming displayList is null, one will be created.
13262     * Otherwise, the same display list will be returned (after having been rendered into
13263     * along the way, depending on the invalidation state of the view).
13264     *
13265     * @param displayList The previous version of this displayList, could be null.
13266     * @param isLayer Whether the requester of the display list is a layer. If so,
13267     * the view will avoid creating a layer inside the resulting display list.
13268     * @return A new or reused DisplayList object.
13269     */
13270    private DisplayList getDisplayList(DisplayList displayList, boolean isLayer) {
13271        if (!canHaveDisplayList()) {
13272            return null;
13273        }
13274
13275        if (((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 ||
13276                displayList == null || !displayList.isValid() ||
13277                (!isLayer && mRecreateDisplayList))) {
13278            // Don't need to recreate the display list, just need to tell our
13279            // children to restore/recreate theirs
13280            if (displayList != null && displayList.isValid() &&
13281                    !isLayer && !mRecreateDisplayList) {
13282                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13283                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13284                dispatchGetDisplayList();
13285
13286                return displayList;
13287            }
13288
13289            if (!isLayer) {
13290                // If we got here, we're recreating it. Mark it as such to ensure that
13291                // we copy in child display lists into ours in drawChild()
13292                mRecreateDisplayList = true;
13293            }
13294            if (displayList == null) {
13295                displayList = mAttachInfo.mHardwareRenderer.createDisplayList(getClass().getName());
13296                // If we're creating a new display list, make sure our parent gets invalidated
13297                // since they will need to recreate their display list to account for this
13298                // new child display list.
13299                invalidateParentCaches();
13300            }
13301
13302            boolean caching = false;
13303            int width = mRight - mLeft;
13304            int height = mBottom - mTop;
13305            int layerType = getLayerType();
13306
13307            final HardwareCanvas canvas = displayList.start(width, height);
13308
13309            try {
13310                if (!isLayer && layerType != LAYER_TYPE_NONE) {
13311                    if (layerType == LAYER_TYPE_HARDWARE) {
13312                        final HardwareLayer layer = getHardwareLayer();
13313                        if (layer != null && layer.isValid()) {
13314                            canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
13315                        } else {
13316                            canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint,
13317                                    Canvas.HAS_ALPHA_LAYER_SAVE_FLAG |
13318                                            Canvas.CLIP_TO_LAYER_SAVE_FLAG);
13319                        }
13320                        caching = true;
13321                    } else {
13322                        buildDrawingCache(true);
13323                        Bitmap cache = getDrawingCache(true);
13324                        if (cache != null) {
13325                            canvas.drawBitmap(cache, 0, 0, mLayerPaint);
13326                            caching = true;
13327                        }
13328                    }
13329                } else {
13330
13331                    computeScroll();
13332
13333                    canvas.translate(-mScrollX, -mScrollY);
13334                    if (!isLayer) {
13335                        mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13336                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13337                    }
13338
13339                    // Fast path for layouts with no backgrounds
13340                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13341                        dispatchDraw(canvas);
13342                        if (mOverlay != null && !mOverlay.isEmpty()) {
13343                            mOverlay.getOverlayView().draw(canvas);
13344                        }
13345                    } else {
13346                        draw(canvas);
13347                    }
13348                }
13349            } finally {
13350                displayList.end();
13351                displayList.setCaching(caching);
13352                if (isLayer) {
13353                    displayList.setLeftTopRightBottom(0, 0, width, height);
13354                } else {
13355                    setDisplayListProperties(displayList);
13356                }
13357            }
13358        } else if (!isLayer) {
13359            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13360            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13361        }
13362
13363        return displayList;
13364    }
13365
13366    /**
13367     * Get the DisplayList for the HardwareLayer
13368     *
13369     * @param layer The HardwareLayer whose DisplayList we want
13370     * @return A DisplayList fopr the specified HardwareLayer
13371     */
13372    private DisplayList getHardwareLayerDisplayList(HardwareLayer layer) {
13373        DisplayList displayList = getDisplayList(layer.getDisplayList(), true);
13374        layer.setDisplayList(displayList);
13375        return displayList;
13376    }
13377
13378
13379    /**
13380     * <p>Returns a display list that can be used to draw this view again
13381     * without executing its draw method.</p>
13382     *
13383     * @return A DisplayList ready to replay, or null if caching is not enabled.
13384     *
13385     * @hide
13386     */
13387    public DisplayList getDisplayList() {
13388        mDisplayList = getDisplayList(mDisplayList, false);
13389        return mDisplayList;
13390    }
13391
13392    private void clearDisplayList() {
13393        if (mDisplayList != null) {
13394            mDisplayList.clear();
13395        }
13396    }
13397
13398    private void resetDisplayList() {
13399        if (mDisplayList != null) {
13400            mDisplayList.reset();
13401        }
13402    }
13403
13404    /**
13405     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
13406     *
13407     * @return A non-scaled bitmap representing this view or null if cache is disabled.
13408     *
13409     * @see #getDrawingCache(boolean)
13410     */
13411    public Bitmap getDrawingCache() {
13412        return getDrawingCache(false);
13413    }
13414
13415    /**
13416     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
13417     * is null when caching is disabled. If caching is enabled and the cache is not ready,
13418     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
13419     * draw from the cache when the cache is enabled. To benefit from the cache, you must
13420     * request the drawing cache by calling this method and draw it on screen if the
13421     * returned bitmap is not null.</p>
13422     *
13423     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
13424     * this method will create a bitmap of the same size as this view. Because this bitmap
13425     * will be drawn scaled by the parent ViewGroup, the result on screen might show
13426     * scaling artifacts. To avoid such artifacts, you should call this method by setting
13427     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
13428     * size than the view. This implies that your application must be able to handle this
13429     * size.</p>
13430     *
13431     * @param autoScale Indicates whether the generated bitmap should be scaled based on
13432     *        the current density of the screen when the application is in compatibility
13433     *        mode.
13434     *
13435     * @return A bitmap representing this view or null if cache is disabled.
13436     *
13437     * @see #setDrawingCacheEnabled(boolean)
13438     * @see #isDrawingCacheEnabled()
13439     * @see #buildDrawingCache(boolean)
13440     * @see #destroyDrawingCache()
13441     */
13442    public Bitmap getDrawingCache(boolean autoScale) {
13443        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
13444            return null;
13445        }
13446        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
13447            buildDrawingCache(autoScale);
13448        }
13449        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
13450    }
13451
13452    /**
13453     * <p>Frees the resources used by the drawing cache. If you call
13454     * {@link #buildDrawingCache()} manually without calling
13455     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
13456     * should cleanup the cache with this method afterwards.</p>
13457     *
13458     * @see #setDrawingCacheEnabled(boolean)
13459     * @see #buildDrawingCache()
13460     * @see #getDrawingCache()
13461     */
13462    public void destroyDrawingCache() {
13463        if (mDrawingCache != null) {
13464            mDrawingCache.recycle();
13465            mDrawingCache = null;
13466        }
13467        if (mUnscaledDrawingCache != null) {
13468            mUnscaledDrawingCache.recycle();
13469            mUnscaledDrawingCache = null;
13470        }
13471    }
13472
13473    /**
13474     * Setting a solid background color for the drawing cache's bitmaps will improve
13475     * performance and memory usage. Note, though that this should only be used if this
13476     * view will always be drawn on top of a solid color.
13477     *
13478     * @param color The background color to use for the drawing cache's bitmap
13479     *
13480     * @see #setDrawingCacheEnabled(boolean)
13481     * @see #buildDrawingCache()
13482     * @see #getDrawingCache()
13483     */
13484    public void setDrawingCacheBackgroundColor(int color) {
13485        if (color != mDrawingCacheBackgroundColor) {
13486            mDrawingCacheBackgroundColor = color;
13487            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
13488        }
13489    }
13490
13491    /**
13492     * @see #setDrawingCacheBackgroundColor(int)
13493     *
13494     * @return The background color to used for the drawing cache's bitmap
13495     */
13496    public int getDrawingCacheBackgroundColor() {
13497        return mDrawingCacheBackgroundColor;
13498    }
13499
13500    /**
13501     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
13502     *
13503     * @see #buildDrawingCache(boolean)
13504     */
13505    public void buildDrawingCache() {
13506        buildDrawingCache(false);
13507    }
13508
13509    /**
13510     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
13511     *
13512     * <p>If you call {@link #buildDrawingCache()} manually without calling
13513     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
13514     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
13515     *
13516     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
13517     * this method will create a bitmap of the same size as this view. Because this bitmap
13518     * will be drawn scaled by the parent ViewGroup, the result on screen might show
13519     * scaling artifacts. To avoid such artifacts, you should call this method by setting
13520     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
13521     * size than the view. This implies that your application must be able to handle this
13522     * size.</p>
13523     *
13524     * <p>You should avoid calling this method when hardware acceleration is enabled. If
13525     * you do not need the drawing cache bitmap, calling this method will increase memory
13526     * usage and cause the view to be rendered in software once, thus negatively impacting
13527     * performance.</p>
13528     *
13529     * @see #getDrawingCache()
13530     * @see #destroyDrawingCache()
13531     */
13532    public void buildDrawingCache(boolean autoScale) {
13533        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
13534                mDrawingCache == null : mUnscaledDrawingCache == null)) {
13535            mCachingFailed = false;
13536
13537            int width = mRight - mLeft;
13538            int height = mBottom - mTop;
13539
13540            final AttachInfo attachInfo = mAttachInfo;
13541            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
13542
13543            if (autoScale && scalingRequired) {
13544                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
13545                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
13546            }
13547
13548            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
13549            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
13550            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
13551
13552            final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
13553            final long drawingCacheSize =
13554                    ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
13555            if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
13556                if (width > 0 && height > 0) {
13557                    Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs "
13558                            + projectedBitmapSize + " bytes, only "
13559                            + drawingCacheSize + " available");
13560                }
13561                destroyDrawingCache();
13562                mCachingFailed = true;
13563                return;
13564            }
13565
13566            boolean clear = true;
13567            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
13568
13569            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
13570                Bitmap.Config quality;
13571                if (!opaque) {
13572                    // Never pick ARGB_4444 because it looks awful
13573                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
13574                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
13575                        case DRAWING_CACHE_QUALITY_AUTO:
13576                        case DRAWING_CACHE_QUALITY_LOW:
13577                        case DRAWING_CACHE_QUALITY_HIGH:
13578                        default:
13579                            quality = Bitmap.Config.ARGB_8888;
13580                            break;
13581                    }
13582                } else {
13583                    // Optimization for translucent windows
13584                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
13585                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
13586                }
13587
13588                // Try to cleanup memory
13589                if (bitmap != null) bitmap.recycle();
13590
13591                try {
13592                    bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
13593                            width, height, quality);
13594                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
13595                    if (autoScale) {
13596                        mDrawingCache = bitmap;
13597                    } else {
13598                        mUnscaledDrawingCache = bitmap;
13599                    }
13600                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
13601                } catch (OutOfMemoryError e) {
13602                    // If there is not enough memory to create the bitmap cache, just
13603                    // ignore the issue as bitmap caches are not required to draw the
13604                    // view hierarchy
13605                    if (autoScale) {
13606                        mDrawingCache = null;
13607                    } else {
13608                        mUnscaledDrawingCache = null;
13609                    }
13610                    mCachingFailed = true;
13611                    return;
13612                }
13613
13614                clear = drawingCacheBackgroundColor != 0;
13615            }
13616
13617            Canvas canvas;
13618            if (attachInfo != null) {
13619                canvas = attachInfo.mCanvas;
13620                if (canvas == null) {
13621                    canvas = new Canvas();
13622                }
13623                canvas.setBitmap(bitmap);
13624                // Temporarily clobber the cached Canvas in case one of our children
13625                // is also using a drawing cache. Without this, the children would
13626                // steal the canvas by attaching their own bitmap to it and bad, bad
13627                // thing would happen (invisible views, corrupted drawings, etc.)
13628                attachInfo.mCanvas = null;
13629            } else {
13630                // This case should hopefully never or seldom happen
13631                canvas = new Canvas(bitmap);
13632            }
13633
13634            if (clear) {
13635                bitmap.eraseColor(drawingCacheBackgroundColor);
13636            }
13637
13638            computeScroll();
13639            final int restoreCount = canvas.save();
13640
13641            if (autoScale && scalingRequired) {
13642                final float scale = attachInfo.mApplicationScale;
13643                canvas.scale(scale, scale);
13644            }
13645
13646            canvas.translate(-mScrollX, -mScrollY);
13647
13648            mPrivateFlags |= PFLAG_DRAWN;
13649            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
13650                    mLayerType != LAYER_TYPE_NONE) {
13651                mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
13652            }
13653
13654            // Fast path for layouts with no backgrounds
13655            if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13656                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13657                dispatchDraw(canvas);
13658                if (mOverlay != null && !mOverlay.isEmpty()) {
13659                    mOverlay.getOverlayView().draw(canvas);
13660                }
13661            } else {
13662                draw(canvas);
13663            }
13664
13665            canvas.restoreToCount(restoreCount);
13666            canvas.setBitmap(null);
13667
13668            if (attachInfo != null) {
13669                // Restore the cached Canvas for our siblings
13670                attachInfo.mCanvas = canvas;
13671            }
13672        }
13673    }
13674
13675    /**
13676     * Create a snapshot of the view into a bitmap.  We should probably make
13677     * some form of this public, but should think about the API.
13678     */
13679    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
13680        int width = mRight - mLeft;
13681        int height = mBottom - mTop;
13682
13683        final AttachInfo attachInfo = mAttachInfo;
13684        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
13685        width = (int) ((width * scale) + 0.5f);
13686        height = (int) ((height * scale) + 0.5f);
13687
13688        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
13689                width > 0 ? width : 1, height > 0 ? height : 1, quality);
13690        if (bitmap == null) {
13691            throw new OutOfMemoryError();
13692        }
13693
13694        Resources resources = getResources();
13695        if (resources != null) {
13696            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
13697        }
13698
13699        Canvas canvas;
13700        if (attachInfo != null) {
13701            canvas = attachInfo.mCanvas;
13702            if (canvas == null) {
13703                canvas = new Canvas();
13704            }
13705            canvas.setBitmap(bitmap);
13706            // Temporarily clobber the cached Canvas in case one of our children
13707            // is also using a drawing cache. Without this, the children would
13708            // steal the canvas by attaching their own bitmap to it and bad, bad
13709            // things would happen (invisible views, corrupted drawings, etc.)
13710            attachInfo.mCanvas = null;
13711        } else {
13712            // This case should hopefully never or seldom happen
13713            canvas = new Canvas(bitmap);
13714        }
13715
13716        if ((backgroundColor & 0xff000000) != 0) {
13717            bitmap.eraseColor(backgroundColor);
13718        }
13719
13720        computeScroll();
13721        final int restoreCount = canvas.save();
13722        canvas.scale(scale, scale);
13723        canvas.translate(-mScrollX, -mScrollY);
13724
13725        // Temporarily remove the dirty mask
13726        int flags = mPrivateFlags;
13727        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13728
13729        // Fast path for layouts with no backgrounds
13730        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13731            dispatchDraw(canvas);
13732            if (mOverlay != null && !mOverlay.isEmpty()) {
13733                mOverlay.getOverlayView().draw(canvas);
13734            }
13735        } else {
13736            draw(canvas);
13737        }
13738
13739        mPrivateFlags = flags;
13740
13741        canvas.restoreToCount(restoreCount);
13742        canvas.setBitmap(null);
13743
13744        if (attachInfo != null) {
13745            // Restore the cached Canvas for our siblings
13746            attachInfo.mCanvas = canvas;
13747        }
13748
13749        return bitmap;
13750    }
13751
13752    /**
13753     * Indicates whether this View is currently in edit mode. A View is usually
13754     * in edit mode when displayed within a developer tool. For instance, if
13755     * this View is being drawn by a visual user interface builder, this method
13756     * should return true.
13757     *
13758     * Subclasses should check the return value of this method to provide
13759     * different behaviors if their normal behavior might interfere with the
13760     * host environment. For instance: the class spawns a thread in its
13761     * constructor, the drawing code relies on device-specific features, etc.
13762     *
13763     * This method is usually checked in the drawing code of custom widgets.
13764     *
13765     * @return True if this View is in edit mode, false otherwise.
13766     */
13767    public boolean isInEditMode() {
13768        return false;
13769    }
13770
13771    /**
13772     * If the View draws content inside its padding and enables fading edges,
13773     * it needs to support padding offsets. Padding offsets are added to the
13774     * fading edges to extend the length of the fade so that it covers pixels
13775     * drawn inside the padding.
13776     *
13777     * Subclasses of this class should override this method if they need
13778     * to draw content inside the padding.
13779     *
13780     * @return True if padding offset must be applied, false otherwise.
13781     *
13782     * @see #getLeftPaddingOffset()
13783     * @see #getRightPaddingOffset()
13784     * @see #getTopPaddingOffset()
13785     * @see #getBottomPaddingOffset()
13786     *
13787     * @since CURRENT
13788     */
13789    protected boolean isPaddingOffsetRequired() {
13790        return false;
13791    }
13792
13793    /**
13794     * Amount by which to extend the left fading region. Called only when
13795     * {@link #isPaddingOffsetRequired()} returns true.
13796     *
13797     * @return The left padding offset in pixels.
13798     *
13799     * @see #isPaddingOffsetRequired()
13800     *
13801     * @since CURRENT
13802     */
13803    protected int getLeftPaddingOffset() {
13804        return 0;
13805    }
13806
13807    /**
13808     * Amount by which to extend the right fading region. Called only when
13809     * {@link #isPaddingOffsetRequired()} returns true.
13810     *
13811     * @return The right padding offset in pixels.
13812     *
13813     * @see #isPaddingOffsetRequired()
13814     *
13815     * @since CURRENT
13816     */
13817    protected int getRightPaddingOffset() {
13818        return 0;
13819    }
13820
13821    /**
13822     * Amount by which to extend the top fading region. Called only when
13823     * {@link #isPaddingOffsetRequired()} returns true.
13824     *
13825     * @return The top padding offset in pixels.
13826     *
13827     * @see #isPaddingOffsetRequired()
13828     *
13829     * @since CURRENT
13830     */
13831    protected int getTopPaddingOffset() {
13832        return 0;
13833    }
13834
13835    /**
13836     * Amount by which to extend the bottom fading region. Called only when
13837     * {@link #isPaddingOffsetRequired()} returns true.
13838     *
13839     * @return The bottom padding offset in pixels.
13840     *
13841     * @see #isPaddingOffsetRequired()
13842     *
13843     * @since CURRENT
13844     */
13845    protected int getBottomPaddingOffset() {
13846        return 0;
13847    }
13848
13849    /**
13850     * @hide
13851     * @param offsetRequired
13852     */
13853    protected int getFadeTop(boolean offsetRequired) {
13854        int top = mPaddingTop;
13855        if (offsetRequired) top += getTopPaddingOffset();
13856        return top;
13857    }
13858
13859    /**
13860     * @hide
13861     * @param offsetRequired
13862     */
13863    protected int getFadeHeight(boolean offsetRequired) {
13864        int padding = mPaddingTop;
13865        if (offsetRequired) padding += getTopPaddingOffset();
13866        return mBottom - mTop - mPaddingBottom - padding;
13867    }
13868
13869    /**
13870     * <p>Indicates whether this view is attached to a hardware accelerated
13871     * window or not.</p>
13872     *
13873     * <p>Even if this method returns true, it does not mean that every call
13874     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
13875     * accelerated {@link android.graphics.Canvas}. For instance, if this view
13876     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
13877     * window is hardware accelerated,
13878     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
13879     * return false, and this method will return true.</p>
13880     *
13881     * @return True if the view is attached to a window and the window is
13882     *         hardware accelerated; false in any other case.
13883     */
13884    public boolean isHardwareAccelerated() {
13885        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
13886    }
13887
13888    /**
13889     * Sets a rectangular area on this view to which the view will be clipped
13890     * when it is drawn. Setting the value to null will remove the clip bounds
13891     * and the view will draw normally, using its full bounds.
13892     *
13893     * @param clipBounds The rectangular area, in the local coordinates of
13894     * this view, to which future drawing operations will be clipped.
13895     */
13896    public void setClipBounds(Rect clipBounds) {
13897        if (clipBounds != null) {
13898            if (clipBounds.equals(mClipBounds)) {
13899                return;
13900            }
13901            if (mClipBounds == null) {
13902                invalidate();
13903                mClipBounds = new Rect(clipBounds);
13904            } else {
13905                invalidate(Math.min(mClipBounds.left, clipBounds.left),
13906                        Math.min(mClipBounds.top, clipBounds.top),
13907                        Math.max(mClipBounds.right, clipBounds.right),
13908                        Math.max(mClipBounds.bottom, clipBounds.bottom));
13909                mClipBounds.set(clipBounds);
13910            }
13911        } else {
13912            if (mClipBounds != null) {
13913                invalidate();
13914                mClipBounds = null;
13915            }
13916        }
13917    }
13918
13919    /**
13920     * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}.
13921     *
13922     * @return A copy of the current clip bounds if clip bounds are set,
13923     * otherwise null.
13924     */
13925    public Rect getClipBounds() {
13926        return (mClipBounds != null) ? new Rect(mClipBounds) : null;
13927    }
13928
13929    /**
13930     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
13931     * case of an active Animation being run on the view.
13932     */
13933    private boolean drawAnimation(ViewGroup parent, long drawingTime,
13934            Animation a, boolean scalingRequired) {
13935        Transformation invalidationTransform;
13936        final int flags = parent.mGroupFlags;
13937        final boolean initialized = a.isInitialized();
13938        if (!initialized) {
13939            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
13940            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
13941            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
13942            onAnimationStart();
13943        }
13944
13945        final Transformation t = parent.getChildTransformation();
13946        boolean more = a.getTransformation(drawingTime, t, 1f);
13947        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
13948            if (parent.mInvalidationTransformation == null) {
13949                parent.mInvalidationTransformation = new Transformation();
13950            }
13951            invalidationTransform = parent.mInvalidationTransformation;
13952            a.getTransformation(drawingTime, invalidationTransform, 1f);
13953        } else {
13954            invalidationTransform = t;
13955        }
13956
13957        if (more) {
13958            if (!a.willChangeBounds()) {
13959                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
13960                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
13961                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
13962                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
13963                    // The child need to draw an animation, potentially offscreen, so
13964                    // make sure we do not cancel invalidate requests
13965                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
13966                    parent.invalidate(mLeft, mTop, mRight, mBottom);
13967                }
13968            } else {
13969                if (parent.mInvalidateRegion == null) {
13970                    parent.mInvalidateRegion = new RectF();
13971                }
13972                final RectF region = parent.mInvalidateRegion;
13973                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
13974                        invalidationTransform);
13975
13976                // The child need to draw an animation, potentially offscreen, so
13977                // make sure we do not cancel invalidate requests
13978                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
13979
13980                final int left = mLeft + (int) region.left;
13981                final int top = mTop + (int) region.top;
13982                parent.invalidate(left, top, left + (int) (region.width() + .5f),
13983                        top + (int) (region.height() + .5f));
13984            }
13985        }
13986        return more;
13987    }
13988
13989    /**
13990     * This method is called by getDisplayList() when a display list is created or re-rendered.
13991     * It sets or resets the current value of all properties on that display list (resetting is
13992     * necessary when a display list is being re-created, because we need to make sure that
13993     * previously-set transform values
13994     */
13995    void setDisplayListProperties(DisplayList displayList) {
13996        if (displayList != null) {
13997            displayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
13998            displayList.setHasOverlappingRendering(hasOverlappingRendering());
13999            if (mParent instanceof ViewGroup) {
14000                displayList.setClipToBounds(
14001                        (((ViewGroup) mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0);
14002            }
14003            float alpha = 1;
14004            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
14005                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
14006                ViewGroup parentVG = (ViewGroup) mParent;
14007                final Transformation t = parentVG.getChildTransformation();
14008                if (parentVG.getChildStaticTransformation(this, t)) {
14009                    final int transformType = t.getTransformationType();
14010                    if (transformType != Transformation.TYPE_IDENTITY) {
14011                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
14012                            alpha = t.getAlpha();
14013                        }
14014                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
14015                            displayList.setMatrix(t.getMatrix());
14016                        }
14017                    }
14018                }
14019            }
14020            if (mTransformationInfo != null) {
14021                alpha *= getFinalAlpha();
14022                if (alpha < 1) {
14023                    final int multipliedAlpha = (int) (255 * alpha);
14024                    if (onSetAlpha(multipliedAlpha)) {
14025                        alpha = 1;
14026                    }
14027                }
14028                displayList.setTransformationInfo(alpha,
14029                        mTransformationInfo.mTranslationX, mTransformationInfo.mTranslationY,
14030                        mTransformationInfo.mRotation, mTransformationInfo.mRotationX,
14031                        mTransformationInfo.mRotationY, mTransformationInfo.mScaleX,
14032                        mTransformationInfo.mScaleY);
14033                if (mTransformationInfo.mCamera == null) {
14034                    mTransformationInfo.mCamera = new Camera();
14035                    mTransformationInfo.matrix3D = new Matrix();
14036                }
14037                displayList.setCameraDistance(mTransformationInfo.mCamera.getLocationZ());
14038                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == PFLAG_PIVOT_EXPLICITLY_SET) {
14039                    displayList.setPivotX(getPivotX());
14040                    displayList.setPivotY(getPivotY());
14041                }
14042            } else if (alpha < 1) {
14043                displayList.setAlpha(alpha);
14044            }
14045        }
14046    }
14047
14048    /**
14049     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
14050     * This draw() method is an implementation detail and is not intended to be overridden or
14051     * to be called from anywhere else other than ViewGroup.drawChild().
14052     */
14053    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
14054        boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
14055        boolean more = false;
14056        final boolean childHasIdentityMatrix = hasIdentityMatrix();
14057        final int flags = parent.mGroupFlags;
14058
14059        if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) {
14060            parent.getChildTransformation().clear();
14061            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14062        }
14063
14064        Transformation transformToApply = null;
14065        boolean concatMatrix = false;
14066
14067        boolean scalingRequired = false;
14068        boolean caching;
14069        int layerType = getLayerType();
14070
14071        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
14072        if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 ||
14073                (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) {
14074            caching = true;
14075            // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList
14076            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
14077        } else {
14078            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
14079        }
14080
14081        final Animation a = getAnimation();
14082        if (a != null) {
14083            more = drawAnimation(parent, drawingTime, a, scalingRequired);
14084            concatMatrix = a.willChangeTransformationMatrix();
14085            if (concatMatrix) {
14086                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
14087            }
14088            transformToApply = parent.getChildTransformation();
14089        } else {
14090            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) ==
14091                    PFLAG3_VIEW_IS_ANIMATING_TRANSFORM && mDisplayList != null) {
14092                // No longer animating: clear out old animation matrix
14093                mDisplayList.setAnimationMatrix(null);
14094                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
14095            }
14096            if (!useDisplayListProperties &&
14097                    (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
14098                final Transformation t = parent.getChildTransformation();
14099                final boolean hasTransform = parent.getChildStaticTransformation(this, t);
14100                if (hasTransform) {
14101                    final int transformType = t.getTransformationType();
14102                    transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null;
14103                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
14104                }
14105            }
14106        }
14107
14108        concatMatrix |= !childHasIdentityMatrix;
14109
14110        // Sets the flag as early as possible to allow draw() implementations
14111        // to call invalidate() successfully when doing animations
14112        mPrivateFlags |= PFLAG_DRAWN;
14113
14114        if (!concatMatrix &&
14115                (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
14116                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
14117                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
14118                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
14119            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
14120            return more;
14121        }
14122        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
14123
14124        if (hardwareAccelerated) {
14125            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
14126            // retain the flag's value temporarily in the mRecreateDisplayList flag
14127            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED;
14128            mPrivateFlags &= ~PFLAG_INVALIDATED;
14129        }
14130
14131        DisplayList displayList = null;
14132        Bitmap cache = null;
14133        boolean hasDisplayList = false;
14134        if (caching) {
14135            if (!hardwareAccelerated) {
14136                if (layerType != LAYER_TYPE_NONE) {
14137                    layerType = LAYER_TYPE_SOFTWARE;
14138                    buildDrawingCache(true);
14139                }
14140                cache = getDrawingCache(true);
14141            } else {
14142                switch (layerType) {
14143                    case LAYER_TYPE_SOFTWARE:
14144                        if (useDisplayListProperties) {
14145                            hasDisplayList = canHaveDisplayList();
14146                        } else {
14147                            buildDrawingCache(true);
14148                            cache = getDrawingCache(true);
14149                        }
14150                        break;
14151                    case LAYER_TYPE_HARDWARE:
14152                        if (useDisplayListProperties) {
14153                            hasDisplayList = canHaveDisplayList();
14154                        }
14155                        break;
14156                    case LAYER_TYPE_NONE:
14157                        // Delay getting the display list until animation-driven alpha values are
14158                        // set up and possibly passed on to the view
14159                        hasDisplayList = canHaveDisplayList();
14160                        break;
14161                }
14162            }
14163        }
14164        useDisplayListProperties &= hasDisplayList;
14165        if (useDisplayListProperties) {
14166            displayList = getDisplayList();
14167            if (!displayList.isValid()) {
14168                // Uncommon, but possible. If a view is removed from the hierarchy during the call
14169                // to getDisplayList(), the display list will be marked invalid and we should not
14170                // try to use it again.
14171                displayList = null;
14172                hasDisplayList = false;
14173                useDisplayListProperties = false;
14174            }
14175        }
14176
14177        int sx = 0;
14178        int sy = 0;
14179        if (!hasDisplayList) {
14180            computeScroll();
14181            sx = mScrollX;
14182            sy = mScrollY;
14183        }
14184
14185        final boolean hasNoCache = cache == null || hasDisplayList;
14186        final boolean offsetForScroll = cache == null && !hasDisplayList &&
14187                layerType != LAYER_TYPE_HARDWARE;
14188
14189        int restoreTo = -1;
14190        if (!useDisplayListProperties || transformToApply != null) {
14191            restoreTo = canvas.save();
14192        }
14193        if (offsetForScroll) {
14194            canvas.translate(mLeft - sx, mTop - sy);
14195        } else {
14196            if (!useDisplayListProperties) {
14197                canvas.translate(mLeft, mTop);
14198            }
14199            if (scalingRequired) {
14200                if (useDisplayListProperties) {
14201                    // TODO: Might not need this if we put everything inside the DL
14202                    restoreTo = canvas.save();
14203                }
14204                // mAttachInfo cannot be null, otherwise scalingRequired == false
14205                final float scale = 1.0f / mAttachInfo.mApplicationScale;
14206                canvas.scale(scale, scale);
14207            }
14208        }
14209
14210        float alpha = useDisplayListProperties ? 1 : (getAlpha() * getTransitionAlpha());
14211        if (transformToApply != null || alpha < 1 ||  !hasIdentityMatrix() ||
14212                (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
14213            if (transformToApply != null || !childHasIdentityMatrix) {
14214                int transX = 0;
14215                int transY = 0;
14216
14217                if (offsetForScroll) {
14218                    transX = -sx;
14219                    transY = -sy;
14220                }
14221
14222                if (transformToApply != null) {
14223                    if (concatMatrix) {
14224                        if (useDisplayListProperties) {
14225                            displayList.setAnimationMatrix(transformToApply.getMatrix());
14226                        } else {
14227                            // Undo the scroll translation, apply the transformation matrix,
14228                            // then redo the scroll translate to get the correct result.
14229                            canvas.translate(-transX, -transY);
14230                            canvas.concat(transformToApply.getMatrix());
14231                            canvas.translate(transX, transY);
14232                        }
14233                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14234                    }
14235
14236                    float transformAlpha = transformToApply.getAlpha();
14237                    if (transformAlpha < 1) {
14238                        alpha *= transformAlpha;
14239                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14240                    }
14241                }
14242
14243                if (!childHasIdentityMatrix && !useDisplayListProperties) {
14244                    canvas.translate(-transX, -transY);
14245                    canvas.concat(getMatrix());
14246                    canvas.translate(transX, transY);
14247                }
14248            }
14249
14250            // Deal with alpha if it is or used to be <1
14251            if (alpha < 1 ||
14252                    (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
14253                if (alpha < 1) {
14254                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
14255                } else {
14256                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
14257                }
14258                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14259                if (hasNoCache) {
14260                    final int multipliedAlpha = (int) (255 * alpha);
14261                    if (!onSetAlpha(multipliedAlpha)) {
14262                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
14263                        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 ||
14264                                layerType != LAYER_TYPE_NONE) {
14265                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
14266                        }
14267                        if (useDisplayListProperties) {
14268                            displayList.setAlpha(alpha * getAlpha() * getTransitionAlpha());
14269                        } else  if (layerType == LAYER_TYPE_NONE) {
14270                            final int scrollX = hasDisplayList ? 0 : sx;
14271                            final int scrollY = hasDisplayList ? 0 : sy;
14272                            canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft,
14273                                    scrollY + mBottom - mTop, multipliedAlpha, layerFlags);
14274                        }
14275                    } else {
14276                        // Alpha is handled by the child directly, clobber the layer's alpha
14277                        mPrivateFlags |= PFLAG_ALPHA_SET;
14278                    }
14279                }
14280            }
14281        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
14282            onSetAlpha(255);
14283            mPrivateFlags &= ~PFLAG_ALPHA_SET;
14284        }
14285
14286        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN &&
14287                !useDisplayListProperties && cache == null) {
14288            if (offsetForScroll) {
14289                canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
14290            } else {
14291                if (!scalingRequired || cache == null) {
14292                    canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
14293                } else {
14294                    canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
14295                }
14296            }
14297        }
14298
14299        if (!useDisplayListProperties && hasDisplayList) {
14300            displayList = getDisplayList();
14301            if (!displayList.isValid()) {
14302                // Uncommon, but possible. If a view is removed from the hierarchy during the call
14303                // to getDisplayList(), the display list will be marked invalid and we should not
14304                // try to use it again.
14305                displayList = null;
14306                hasDisplayList = false;
14307            }
14308        }
14309
14310        if (hasNoCache) {
14311            boolean layerRendered = false;
14312            if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) {
14313                final HardwareLayer layer = getHardwareLayer();
14314                if (layer != null && layer.isValid()) {
14315                    mLayerPaint.setAlpha((int) (alpha * 255));
14316                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
14317                    layerRendered = true;
14318                } else {
14319                    final int scrollX = hasDisplayList ? 0 : sx;
14320                    final int scrollY = hasDisplayList ? 0 : sy;
14321                    canvas.saveLayer(scrollX, scrollY,
14322                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
14323                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
14324                }
14325            }
14326
14327            if (!layerRendered) {
14328                if (!hasDisplayList) {
14329                    // Fast path for layouts with no backgrounds
14330                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14331                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14332                        dispatchDraw(canvas);
14333                    } else {
14334                        draw(canvas);
14335                    }
14336                } else {
14337                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14338                    ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags);
14339                }
14340            }
14341        } else if (cache != null) {
14342            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14343            Paint cachePaint;
14344
14345            if (layerType == LAYER_TYPE_NONE) {
14346                cachePaint = parent.mCachePaint;
14347                if (cachePaint == null) {
14348                    cachePaint = new Paint();
14349                    cachePaint.setDither(false);
14350                    parent.mCachePaint = cachePaint;
14351                }
14352                if (alpha < 1) {
14353                    cachePaint.setAlpha((int) (alpha * 255));
14354                    parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
14355                } else if  ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) {
14356                    cachePaint.setAlpha(255);
14357                    parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
14358                }
14359            } else {
14360                cachePaint = mLayerPaint;
14361                cachePaint.setAlpha((int) (alpha * 255));
14362            }
14363            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
14364        }
14365
14366        if (restoreTo >= 0) {
14367            canvas.restoreToCount(restoreTo);
14368        }
14369
14370        if (a != null && !more) {
14371            if (!hardwareAccelerated && !a.getFillAfter()) {
14372                onSetAlpha(255);
14373            }
14374            parent.finishAnimatingView(this, a);
14375        }
14376
14377        if (more && hardwareAccelerated) {
14378            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
14379                // alpha animations should cause the child to recreate its display list
14380                invalidate(true);
14381            }
14382        }
14383
14384        mRecreateDisplayList = false;
14385
14386        return more;
14387    }
14388
14389    /**
14390     * Manually render this view (and all of its children) to the given Canvas.
14391     * The view must have already done a full layout before this function is
14392     * called.  When implementing a view, implement
14393     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
14394     * If you do need to override this method, call the superclass version.
14395     *
14396     * @param canvas The Canvas to which the View is rendered.
14397     */
14398    public void draw(Canvas canvas) {
14399        if (mClipBounds != null) {
14400            canvas.clipRect(mClipBounds);
14401        }
14402        final int privateFlags = mPrivateFlags;
14403        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
14404                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
14405        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
14406
14407        /*
14408         * Draw traversal performs several drawing steps which must be executed
14409         * in the appropriate order:
14410         *
14411         *      1. Draw the background
14412         *      2. If necessary, save the canvas' layers to prepare for fading
14413         *      3. Draw view's content
14414         *      4. Draw children
14415         *      5. If necessary, draw the fading edges and restore layers
14416         *      6. Draw decorations (scrollbars for instance)
14417         */
14418
14419        // Step 1, draw the background, if needed
14420        int saveCount;
14421
14422        if (!dirtyOpaque) {
14423            final Drawable background = mBackground;
14424            if (background != null) {
14425                final int scrollX = mScrollX;
14426                final int scrollY = mScrollY;
14427
14428                if (mBackgroundSizeChanged) {
14429                    background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
14430                    mBackgroundSizeChanged = false;
14431                }
14432
14433                if ((scrollX | scrollY) == 0) {
14434                    background.draw(canvas);
14435                } else {
14436                    canvas.translate(scrollX, scrollY);
14437                    background.draw(canvas);
14438                    canvas.translate(-scrollX, -scrollY);
14439                }
14440            }
14441        }
14442
14443        // skip step 2 & 5 if possible (common case)
14444        final int viewFlags = mViewFlags;
14445        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
14446        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
14447        if (!verticalEdges && !horizontalEdges) {
14448            // Step 3, draw the content
14449            if (!dirtyOpaque) onDraw(canvas);
14450
14451            // Step 4, draw the children
14452            dispatchDraw(canvas);
14453
14454            // Step 6, draw decorations (scrollbars)
14455            onDrawScrollBars(canvas);
14456
14457            if (mOverlay != null && !mOverlay.isEmpty()) {
14458                mOverlay.getOverlayView().dispatchDraw(canvas);
14459            }
14460
14461            // we're done...
14462            return;
14463        }
14464
14465        /*
14466         * Here we do the full fledged routine...
14467         * (this is an uncommon case where speed matters less,
14468         * this is why we repeat some of the tests that have been
14469         * done above)
14470         */
14471
14472        boolean drawTop = false;
14473        boolean drawBottom = false;
14474        boolean drawLeft = false;
14475        boolean drawRight = false;
14476
14477        float topFadeStrength = 0.0f;
14478        float bottomFadeStrength = 0.0f;
14479        float leftFadeStrength = 0.0f;
14480        float rightFadeStrength = 0.0f;
14481
14482        // Step 2, save the canvas' layers
14483        int paddingLeft = mPaddingLeft;
14484
14485        final boolean offsetRequired = isPaddingOffsetRequired();
14486        if (offsetRequired) {
14487            paddingLeft += getLeftPaddingOffset();
14488        }
14489
14490        int left = mScrollX + paddingLeft;
14491        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
14492        int top = mScrollY + getFadeTop(offsetRequired);
14493        int bottom = top + getFadeHeight(offsetRequired);
14494
14495        if (offsetRequired) {
14496            right += getRightPaddingOffset();
14497            bottom += getBottomPaddingOffset();
14498        }
14499
14500        final ScrollabilityCache scrollabilityCache = mScrollCache;
14501        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
14502        int length = (int) fadeHeight;
14503
14504        // clip the fade length if top and bottom fades overlap
14505        // overlapping fades produce odd-looking artifacts
14506        if (verticalEdges && (top + length > bottom - length)) {
14507            length = (bottom - top) / 2;
14508        }
14509
14510        // also clip horizontal fades if necessary
14511        if (horizontalEdges && (left + length > right - length)) {
14512            length = (right - left) / 2;
14513        }
14514
14515        if (verticalEdges) {
14516            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
14517            drawTop = topFadeStrength * fadeHeight > 1.0f;
14518            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
14519            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
14520        }
14521
14522        if (horizontalEdges) {
14523            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
14524            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
14525            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
14526            drawRight = rightFadeStrength * fadeHeight > 1.0f;
14527        }
14528
14529        saveCount = canvas.getSaveCount();
14530
14531        int solidColor = getSolidColor();
14532        if (solidColor == 0) {
14533            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
14534
14535            if (drawTop) {
14536                canvas.saveLayer(left, top, right, top + length, null, flags);
14537            }
14538
14539            if (drawBottom) {
14540                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
14541            }
14542
14543            if (drawLeft) {
14544                canvas.saveLayer(left, top, left + length, bottom, null, flags);
14545            }
14546
14547            if (drawRight) {
14548                canvas.saveLayer(right - length, top, right, bottom, null, flags);
14549            }
14550        } else {
14551            scrollabilityCache.setFadeColor(solidColor);
14552        }
14553
14554        // Step 3, draw the content
14555        if (!dirtyOpaque) onDraw(canvas);
14556
14557        // Step 4, draw the children
14558        dispatchDraw(canvas);
14559
14560        // Step 5, draw the fade effect and restore layers
14561        final Paint p = scrollabilityCache.paint;
14562        final Matrix matrix = scrollabilityCache.matrix;
14563        final Shader fade = scrollabilityCache.shader;
14564
14565        if (drawTop) {
14566            matrix.setScale(1, fadeHeight * topFadeStrength);
14567            matrix.postTranslate(left, top);
14568            fade.setLocalMatrix(matrix);
14569            canvas.drawRect(left, top, right, top + length, p);
14570        }
14571
14572        if (drawBottom) {
14573            matrix.setScale(1, fadeHeight * bottomFadeStrength);
14574            matrix.postRotate(180);
14575            matrix.postTranslate(left, bottom);
14576            fade.setLocalMatrix(matrix);
14577            canvas.drawRect(left, bottom - length, right, bottom, p);
14578        }
14579
14580        if (drawLeft) {
14581            matrix.setScale(1, fadeHeight * leftFadeStrength);
14582            matrix.postRotate(-90);
14583            matrix.postTranslate(left, top);
14584            fade.setLocalMatrix(matrix);
14585            canvas.drawRect(left, top, left + length, bottom, p);
14586        }
14587
14588        if (drawRight) {
14589            matrix.setScale(1, fadeHeight * rightFadeStrength);
14590            matrix.postRotate(90);
14591            matrix.postTranslate(right, top);
14592            fade.setLocalMatrix(matrix);
14593            canvas.drawRect(right - length, top, right, bottom, p);
14594        }
14595
14596        canvas.restoreToCount(saveCount);
14597
14598        // Step 6, draw decorations (scrollbars)
14599        onDrawScrollBars(canvas);
14600
14601        if (mOverlay != null && !mOverlay.isEmpty()) {
14602            mOverlay.getOverlayView().dispatchDraw(canvas);
14603        }
14604    }
14605
14606    /**
14607     * Returns the overlay for this view, creating it if it does not yet exist.
14608     * Adding drawables to the overlay will cause them to be displayed whenever
14609     * the view itself is redrawn. Objects in the overlay should be actively
14610     * managed: remove them when they should not be displayed anymore. The
14611     * overlay will always have the same size as its host view.
14612     *
14613     * <p>Note: Overlays do not currently work correctly with {@link
14614     * SurfaceView} or {@link TextureView}; contents in overlays for these
14615     * types of views may not display correctly.</p>
14616     *
14617     * @return The ViewOverlay object for this view.
14618     * @see ViewOverlay
14619     */
14620    public ViewOverlay getOverlay() {
14621        if (mOverlay == null) {
14622            mOverlay = new ViewOverlay(mContext, this);
14623        }
14624        return mOverlay;
14625    }
14626
14627    /**
14628     * Override this if your view is known to always be drawn on top of a solid color background,
14629     * and needs to draw fading edges. Returning a non-zero color enables the view system to
14630     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
14631     * should be set to 0xFF.
14632     *
14633     * @see #setVerticalFadingEdgeEnabled(boolean)
14634     * @see #setHorizontalFadingEdgeEnabled(boolean)
14635     *
14636     * @return The known solid color background for this view, or 0 if the color may vary
14637     */
14638    @ViewDebug.ExportedProperty(category = "drawing")
14639    public int getSolidColor() {
14640        return 0;
14641    }
14642
14643    /**
14644     * Build a human readable string representation of the specified view flags.
14645     *
14646     * @param flags the view flags to convert to a string
14647     * @return a String representing the supplied flags
14648     */
14649    private static String printFlags(int flags) {
14650        String output = "";
14651        int numFlags = 0;
14652        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
14653            output += "TAKES_FOCUS";
14654            numFlags++;
14655        }
14656
14657        switch (flags & VISIBILITY_MASK) {
14658        case INVISIBLE:
14659            if (numFlags > 0) {
14660                output += " ";
14661            }
14662            output += "INVISIBLE";
14663            // USELESS HERE numFlags++;
14664            break;
14665        case GONE:
14666            if (numFlags > 0) {
14667                output += " ";
14668            }
14669            output += "GONE";
14670            // USELESS HERE numFlags++;
14671            break;
14672        default:
14673            break;
14674        }
14675        return output;
14676    }
14677
14678    /**
14679     * Build a human readable string representation of the specified private
14680     * view flags.
14681     *
14682     * @param privateFlags the private view flags to convert to a string
14683     * @return a String representing the supplied flags
14684     */
14685    private static String printPrivateFlags(int privateFlags) {
14686        String output = "";
14687        int numFlags = 0;
14688
14689        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
14690            output += "WANTS_FOCUS";
14691            numFlags++;
14692        }
14693
14694        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
14695            if (numFlags > 0) {
14696                output += " ";
14697            }
14698            output += "FOCUSED";
14699            numFlags++;
14700        }
14701
14702        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
14703            if (numFlags > 0) {
14704                output += " ";
14705            }
14706            output += "SELECTED";
14707            numFlags++;
14708        }
14709
14710        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
14711            if (numFlags > 0) {
14712                output += " ";
14713            }
14714            output += "IS_ROOT_NAMESPACE";
14715            numFlags++;
14716        }
14717
14718        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
14719            if (numFlags > 0) {
14720                output += " ";
14721            }
14722            output += "HAS_BOUNDS";
14723            numFlags++;
14724        }
14725
14726        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
14727            if (numFlags > 0) {
14728                output += " ";
14729            }
14730            output += "DRAWN";
14731            // USELESS HERE numFlags++;
14732        }
14733        return output;
14734    }
14735
14736    /**
14737     * <p>Indicates whether or not this view's layout will be requested during
14738     * the next hierarchy layout pass.</p>
14739     *
14740     * @return true if the layout will be forced during next layout pass
14741     */
14742    public boolean isLayoutRequested() {
14743        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
14744    }
14745
14746    /**
14747     * Return true if o is a ViewGroup that is laying out using optical bounds.
14748     * @hide
14749     */
14750    public static boolean isLayoutModeOptical(Object o) {
14751        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
14752    }
14753
14754    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
14755        Insets parentInsets = mParent instanceof View ?
14756                ((View) mParent).getOpticalInsets() : Insets.NONE;
14757        Insets childInsets = getOpticalInsets();
14758        return setFrame(
14759                left   + parentInsets.left - childInsets.left,
14760                top    + parentInsets.top  - childInsets.top,
14761                right  + parentInsets.left + childInsets.right,
14762                bottom + parentInsets.top  + childInsets.bottom);
14763    }
14764
14765    /**
14766     * Assign a size and position to a view and all of its
14767     * descendants
14768     *
14769     * <p>This is the second phase of the layout mechanism.
14770     * (The first is measuring). In this phase, each parent calls
14771     * layout on all of its children to position them.
14772     * This is typically done using the child measurements
14773     * that were stored in the measure pass().</p>
14774     *
14775     * <p>Derived classes should not override this method.
14776     * Derived classes with children should override
14777     * onLayout. In that method, they should
14778     * call layout on each of their children.</p>
14779     *
14780     * @param l Left position, relative to parent
14781     * @param t Top position, relative to parent
14782     * @param r Right position, relative to parent
14783     * @param b Bottom position, relative to parent
14784     */
14785    @SuppressWarnings({"unchecked"})
14786    public void layout(int l, int t, int r, int b) {
14787        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
14788            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
14789            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
14790        }
14791
14792        int oldL = mLeft;
14793        int oldT = mTop;
14794        int oldB = mBottom;
14795        int oldR = mRight;
14796
14797        boolean changed = isLayoutModeOptical(mParent) ?
14798                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
14799
14800        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
14801            onLayout(changed, l, t, r, b);
14802            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
14803
14804            ListenerInfo li = mListenerInfo;
14805            if (li != null && li.mOnLayoutChangeListeners != null) {
14806                ArrayList<OnLayoutChangeListener> listenersCopy =
14807                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
14808                int numListeners = listenersCopy.size();
14809                for (int i = 0; i < numListeners; ++i) {
14810                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
14811                }
14812            }
14813        }
14814
14815        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
14816        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
14817    }
14818
14819    /**
14820     * Called from layout when this view should
14821     * assign a size and position to each of its children.
14822     *
14823     * Derived classes with children should override
14824     * this method and call layout on each of
14825     * their children.
14826     * @param changed This is a new size or position for this view
14827     * @param left Left position, relative to parent
14828     * @param top Top position, relative to parent
14829     * @param right Right position, relative to parent
14830     * @param bottom Bottom position, relative to parent
14831     */
14832    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
14833    }
14834
14835    /**
14836     * Assign a size and position to this view.
14837     *
14838     * This is called from layout.
14839     *
14840     * @param left Left position, relative to parent
14841     * @param top Top position, relative to parent
14842     * @param right Right position, relative to parent
14843     * @param bottom Bottom position, relative to parent
14844     * @return true if the new size and position are different than the
14845     *         previous ones
14846     * {@hide}
14847     */
14848    protected boolean setFrame(int left, int top, int right, int bottom) {
14849        boolean changed = false;
14850
14851        if (DBG) {
14852            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
14853                    + right + "," + bottom + ")");
14854        }
14855
14856        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
14857            changed = true;
14858
14859            // Remember our drawn bit
14860            int drawn = mPrivateFlags & PFLAG_DRAWN;
14861
14862            int oldWidth = mRight - mLeft;
14863            int oldHeight = mBottom - mTop;
14864            int newWidth = right - left;
14865            int newHeight = bottom - top;
14866            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
14867
14868            // Invalidate our old position
14869            invalidate(sizeChanged);
14870
14871            mLeft = left;
14872            mTop = top;
14873            mRight = right;
14874            mBottom = bottom;
14875            if (mDisplayList != null) {
14876                mDisplayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
14877            }
14878
14879            mPrivateFlags |= PFLAG_HAS_BOUNDS;
14880
14881
14882            if (sizeChanged) {
14883                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
14884                    // A change in dimension means an auto-centered pivot point changes, too
14885                    if (mTransformationInfo != null) {
14886                        mTransformationInfo.mMatrixDirty = true;
14887                    }
14888                }
14889                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
14890            }
14891
14892            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
14893                // If we are visible, force the DRAWN bit to on so that
14894                // this invalidate will go through (at least to our parent).
14895                // This is because someone may have invalidated this view
14896                // before this call to setFrame came in, thereby clearing
14897                // the DRAWN bit.
14898                mPrivateFlags |= PFLAG_DRAWN;
14899                invalidate(sizeChanged);
14900                // parent display list may need to be recreated based on a change in the bounds
14901                // of any child
14902                invalidateParentCaches();
14903            }
14904
14905            // Reset drawn bit to original value (invalidate turns it off)
14906            mPrivateFlags |= drawn;
14907
14908            mBackgroundSizeChanged = true;
14909
14910            notifySubtreeAccessibilityStateChangedIfNeeded();
14911        }
14912        return changed;
14913    }
14914
14915    private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
14916        onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
14917        if (mOverlay != null) {
14918            mOverlay.getOverlayView().setRight(newWidth);
14919            mOverlay.getOverlayView().setBottom(newHeight);
14920        }
14921    }
14922
14923    /**
14924     * Finalize inflating a view from XML.  This is called as the last phase
14925     * of inflation, after all child views have been added.
14926     *
14927     * <p>Even if the subclass overrides onFinishInflate, they should always be
14928     * sure to call the super method, so that we get called.
14929     */
14930    protected void onFinishInflate() {
14931    }
14932
14933    /**
14934     * Returns the resources associated with this view.
14935     *
14936     * @return Resources object.
14937     */
14938    public Resources getResources() {
14939        return mResources;
14940    }
14941
14942    /**
14943     * Invalidates the specified Drawable.
14944     *
14945     * @param drawable the drawable to invalidate
14946     */
14947    public void invalidateDrawable(Drawable drawable) {
14948        if (verifyDrawable(drawable)) {
14949            final Rect dirty = drawable.getBounds();
14950            final int scrollX = mScrollX;
14951            final int scrollY = mScrollY;
14952
14953            invalidate(dirty.left + scrollX, dirty.top + scrollY,
14954                    dirty.right + scrollX, dirty.bottom + scrollY);
14955        }
14956    }
14957
14958    /**
14959     * Schedules an action on a drawable to occur at a specified time.
14960     *
14961     * @param who the recipient of the action
14962     * @param what the action to run on the drawable
14963     * @param when the time at which the action must occur. Uses the
14964     *        {@link SystemClock#uptimeMillis} timebase.
14965     */
14966    public void scheduleDrawable(Drawable who, Runnable what, long when) {
14967        if (verifyDrawable(who) && what != null) {
14968            final long delay = when - SystemClock.uptimeMillis();
14969            if (mAttachInfo != null) {
14970                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
14971                        Choreographer.CALLBACK_ANIMATION, what, who,
14972                        Choreographer.subtractFrameDelay(delay));
14973            } else {
14974                ViewRootImpl.getRunQueue().postDelayed(what, delay);
14975            }
14976        }
14977    }
14978
14979    /**
14980     * Cancels a scheduled action on a drawable.
14981     *
14982     * @param who the recipient of the action
14983     * @param what the action to cancel
14984     */
14985    public void unscheduleDrawable(Drawable who, Runnable what) {
14986        if (verifyDrawable(who) && what != null) {
14987            if (mAttachInfo != null) {
14988                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
14989                        Choreographer.CALLBACK_ANIMATION, what, who);
14990            } else {
14991                ViewRootImpl.getRunQueue().removeCallbacks(what);
14992            }
14993        }
14994    }
14995
14996    /**
14997     * Unschedule any events associated with the given Drawable.  This can be
14998     * used when selecting a new Drawable into a view, so that the previous
14999     * one is completely unscheduled.
15000     *
15001     * @param who The Drawable to unschedule.
15002     *
15003     * @see #drawableStateChanged
15004     */
15005    public void unscheduleDrawable(Drawable who) {
15006        if (mAttachInfo != null && who != null) {
15007            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
15008                    Choreographer.CALLBACK_ANIMATION, null, who);
15009        }
15010    }
15011
15012    /**
15013     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
15014     * that the View directionality can and will be resolved before its Drawables.
15015     *
15016     * Will call {@link View#onResolveDrawables} when resolution is done.
15017     *
15018     * @hide
15019     */
15020    protected void resolveDrawables() {
15021        // Drawables resolution may need to happen before resolving the layout direction (which is
15022        // done only during the measure() call).
15023        // If the layout direction is not resolved yet, we cannot resolve the Drawables except in
15024        // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT.
15025        // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or
15026        // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout
15027        // direction to be resolved as its resolved value will be the same as its raw value.
15028        if (!isLayoutDirectionResolved() &&
15029                getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) {
15030            return;
15031        }
15032
15033        final int layoutDirection = isLayoutDirectionResolved() ?
15034                getLayoutDirection() : getRawLayoutDirection();
15035
15036        if (mBackground != null) {
15037            mBackground.setLayoutDirection(layoutDirection);
15038        }
15039        mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
15040        onResolveDrawables(layoutDirection);
15041    }
15042
15043    /**
15044     * Called when layout direction has been resolved.
15045     *
15046     * The default implementation does nothing.
15047     *
15048     * @param layoutDirection The resolved layout direction.
15049     *
15050     * @see #LAYOUT_DIRECTION_LTR
15051     * @see #LAYOUT_DIRECTION_RTL
15052     *
15053     * @hide
15054     */
15055    public void onResolveDrawables(int layoutDirection) {
15056    }
15057
15058    /**
15059     * @hide
15060     */
15061    protected void resetResolvedDrawables() {
15062        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
15063    }
15064
15065    private boolean isDrawablesResolved() {
15066        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
15067    }
15068
15069    /**
15070     * If your view subclass is displaying its own Drawable objects, it should
15071     * override this function and return true for any Drawable it is
15072     * displaying.  This allows animations for those drawables to be
15073     * scheduled.
15074     *
15075     * <p>Be sure to call through to the super class when overriding this
15076     * function.
15077     *
15078     * @param who The Drawable to verify.  Return true if it is one you are
15079     *            displaying, else return the result of calling through to the
15080     *            super class.
15081     *
15082     * @return boolean If true than the Drawable is being displayed in the
15083     *         view; else false and it is not allowed to animate.
15084     *
15085     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
15086     * @see #drawableStateChanged()
15087     */
15088    protected boolean verifyDrawable(Drawable who) {
15089        return who == mBackground;
15090    }
15091
15092    /**
15093     * This function is called whenever the state of the view changes in such
15094     * a way that it impacts the state of drawables being shown.
15095     *
15096     * <p>Be sure to call through to the superclass when overriding this
15097     * function.
15098     *
15099     * @see Drawable#setState(int[])
15100     */
15101    protected void drawableStateChanged() {
15102        Drawable d = mBackground;
15103        if (d != null && d.isStateful()) {
15104            d.setState(getDrawableState());
15105        }
15106    }
15107
15108    /**
15109     * Call this to force a view to update its drawable state. This will cause
15110     * drawableStateChanged to be called on this view. Views that are interested
15111     * in the new state should call getDrawableState.
15112     *
15113     * @see #drawableStateChanged
15114     * @see #getDrawableState
15115     */
15116    public void refreshDrawableState() {
15117        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
15118        drawableStateChanged();
15119
15120        ViewParent parent = mParent;
15121        if (parent != null) {
15122            parent.childDrawableStateChanged(this);
15123        }
15124    }
15125
15126    /**
15127     * Return an array of resource IDs of the drawable states representing the
15128     * current state of the view.
15129     *
15130     * @return The current drawable state
15131     *
15132     * @see Drawable#setState(int[])
15133     * @see #drawableStateChanged()
15134     * @see #onCreateDrawableState(int)
15135     */
15136    public final int[] getDrawableState() {
15137        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
15138            return mDrawableState;
15139        } else {
15140            mDrawableState = onCreateDrawableState(0);
15141            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
15142            return mDrawableState;
15143        }
15144    }
15145
15146    /**
15147     * Generate the new {@link android.graphics.drawable.Drawable} state for
15148     * this view. This is called by the view
15149     * system when the cached Drawable state is determined to be invalid.  To
15150     * retrieve the current state, you should use {@link #getDrawableState}.
15151     *
15152     * @param extraSpace if non-zero, this is the number of extra entries you
15153     * would like in the returned array in which you can place your own
15154     * states.
15155     *
15156     * @return Returns an array holding the current {@link Drawable} state of
15157     * the view.
15158     *
15159     * @see #mergeDrawableStates(int[], int[])
15160     */
15161    protected int[] onCreateDrawableState(int extraSpace) {
15162        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
15163                mParent instanceof View) {
15164            return ((View) mParent).onCreateDrawableState(extraSpace);
15165        }
15166
15167        int[] drawableState;
15168
15169        int privateFlags = mPrivateFlags;
15170
15171        int viewStateIndex = 0;
15172        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
15173        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
15174        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
15175        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
15176        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
15177        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
15178        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
15179                HardwareRenderer.isAvailable()) {
15180            // This is set if HW acceleration is requested, even if the current
15181            // process doesn't allow it.  This is just to allow app preview
15182            // windows to better match their app.
15183            viewStateIndex |= VIEW_STATE_ACCELERATED;
15184        }
15185        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
15186
15187        final int privateFlags2 = mPrivateFlags2;
15188        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
15189        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
15190
15191        drawableState = VIEW_STATE_SETS[viewStateIndex];
15192
15193        //noinspection ConstantIfStatement
15194        if (false) {
15195            Log.i("View", "drawableStateIndex=" + viewStateIndex);
15196            Log.i("View", toString()
15197                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
15198                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
15199                    + " fo=" + hasFocus()
15200                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
15201                    + " wf=" + hasWindowFocus()
15202                    + ": " + Arrays.toString(drawableState));
15203        }
15204
15205        if (extraSpace == 0) {
15206            return drawableState;
15207        }
15208
15209        final int[] fullState;
15210        if (drawableState != null) {
15211            fullState = new int[drawableState.length + extraSpace];
15212            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
15213        } else {
15214            fullState = new int[extraSpace];
15215        }
15216
15217        return fullState;
15218    }
15219
15220    /**
15221     * Merge your own state values in <var>additionalState</var> into the base
15222     * state values <var>baseState</var> that were returned by
15223     * {@link #onCreateDrawableState(int)}.
15224     *
15225     * @param baseState The base state values returned by
15226     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
15227     * own additional state values.
15228     *
15229     * @param additionalState The additional state values you would like
15230     * added to <var>baseState</var>; this array is not modified.
15231     *
15232     * @return As a convenience, the <var>baseState</var> array you originally
15233     * passed into the function is returned.
15234     *
15235     * @see #onCreateDrawableState(int)
15236     */
15237    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
15238        final int N = baseState.length;
15239        int i = N - 1;
15240        while (i >= 0 && baseState[i] == 0) {
15241            i--;
15242        }
15243        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
15244        return baseState;
15245    }
15246
15247    /**
15248     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
15249     * on all Drawable objects associated with this view.
15250     */
15251    public void jumpDrawablesToCurrentState() {
15252        if (mBackground != null) {
15253            mBackground.jumpToCurrentState();
15254        }
15255    }
15256
15257    /**
15258     * Sets the background color for this view.
15259     * @param color the color of the background
15260     */
15261    @RemotableViewMethod
15262    public void setBackgroundColor(int color) {
15263        if (mBackground instanceof ColorDrawable) {
15264            ((ColorDrawable) mBackground.mutate()).setColor(color);
15265            computeOpaqueFlags();
15266            mBackgroundResource = 0;
15267        } else {
15268            setBackground(new ColorDrawable(color));
15269        }
15270    }
15271
15272    /**
15273     * Set the background to a given resource. The resource should refer to
15274     * a Drawable object or 0 to remove the background.
15275     * @param resid The identifier of the resource.
15276     *
15277     * @attr ref android.R.styleable#View_background
15278     */
15279    @RemotableViewMethod
15280    public void setBackgroundResource(int resid) {
15281        if (resid != 0 && resid == mBackgroundResource) {
15282            return;
15283        }
15284
15285        Drawable d= null;
15286        if (resid != 0) {
15287            d = mResources.getDrawable(resid);
15288        }
15289        setBackground(d);
15290
15291        mBackgroundResource = resid;
15292    }
15293
15294    /**
15295     * Set the background to a given Drawable, or remove the background. If the
15296     * background has padding, this View's padding is set to the background's
15297     * padding. However, when a background is removed, this View's padding isn't
15298     * touched. If setting the padding is desired, please use
15299     * {@link #setPadding(int, int, int, int)}.
15300     *
15301     * @param background The Drawable to use as the background, or null to remove the
15302     *        background
15303     */
15304    public void setBackground(Drawable background) {
15305        //noinspection deprecation
15306        setBackgroundDrawable(background);
15307    }
15308
15309    /**
15310     * @deprecated use {@link #setBackground(Drawable)} instead
15311     */
15312    @Deprecated
15313    public void setBackgroundDrawable(Drawable background) {
15314        computeOpaqueFlags();
15315
15316        if (background == mBackground) {
15317            return;
15318        }
15319
15320        boolean requestLayout = false;
15321
15322        mBackgroundResource = 0;
15323
15324        /*
15325         * Regardless of whether we're setting a new background or not, we want
15326         * to clear the previous drawable.
15327         */
15328        if (mBackground != null) {
15329            mBackground.setCallback(null);
15330            unscheduleDrawable(mBackground);
15331        }
15332
15333        if (background != null) {
15334            Rect padding = sThreadLocal.get();
15335            if (padding == null) {
15336                padding = new Rect();
15337                sThreadLocal.set(padding);
15338            }
15339            resetResolvedDrawables();
15340            background.setLayoutDirection(getLayoutDirection());
15341            if (background.getPadding(padding)) {
15342                resetResolvedPadding();
15343                switch (background.getLayoutDirection()) {
15344                    case LAYOUT_DIRECTION_RTL:
15345                        mUserPaddingLeftInitial = padding.right;
15346                        mUserPaddingRightInitial = padding.left;
15347                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
15348                        break;
15349                    case LAYOUT_DIRECTION_LTR:
15350                    default:
15351                        mUserPaddingLeftInitial = padding.left;
15352                        mUserPaddingRightInitial = padding.right;
15353                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
15354                }
15355                mUseBackgroundPadding = true;
15356            } else {
15357                mUseBackgroundPadding = false;
15358            }
15359
15360            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
15361            // if it has a different minimum size, we should layout again
15362            if (mBackground == null || mBackground.getMinimumHeight() != background.getMinimumHeight() ||
15363                    mBackground.getMinimumWidth() != background.getMinimumWidth()) {
15364                requestLayout = true;
15365            }
15366
15367            background.setCallback(this);
15368            if (background.isStateful()) {
15369                background.setState(getDrawableState());
15370            }
15371            background.setVisible(getVisibility() == VISIBLE, false);
15372            mBackground = background;
15373
15374            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
15375                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
15376                mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
15377                requestLayout = true;
15378            }
15379        } else {
15380            /* Remove the background */
15381            mBackground = null;
15382
15383            mUseBackgroundPadding = false;
15384
15385            if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) {
15386                /*
15387                 * This view ONLY drew the background before and we're removing
15388                 * the background, so now it won't draw anything
15389                 * (hence we SKIP_DRAW)
15390                 */
15391                mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND;
15392                mPrivateFlags |= PFLAG_SKIP_DRAW;
15393            }
15394
15395            /*
15396             * When the background is set, we try to apply its padding to this
15397             * View. When the background is removed, we don't touch this View's
15398             * padding. This is noted in the Javadocs. Hence, we don't need to
15399             * requestLayout(), the invalidate() below is sufficient.
15400             */
15401
15402            // The old background's minimum size could have affected this
15403            // View's layout, so let's requestLayout
15404            requestLayout = true;
15405        }
15406
15407        computeOpaqueFlags();
15408
15409        if (requestLayout) {
15410            requestLayout();
15411        }
15412
15413        mBackgroundSizeChanged = true;
15414        invalidate(true);
15415    }
15416
15417    /**
15418     * Gets the background drawable
15419     *
15420     * @return The drawable used as the background for this view, if any.
15421     *
15422     * @see #setBackground(Drawable)
15423     *
15424     * @attr ref android.R.styleable#View_background
15425     */
15426    public Drawable getBackground() {
15427        return mBackground;
15428    }
15429
15430    /**
15431     * Sets the padding. The view may add on the space required to display
15432     * the scrollbars, depending on the style and visibility of the scrollbars.
15433     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
15434     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
15435     * from the values set in this call.
15436     *
15437     * @attr ref android.R.styleable#View_padding
15438     * @attr ref android.R.styleable#View_paddingBottom
15439     * @attr ref android.R.styleable#View_paddingLeft
15440     * @attr ref android.R.styleable#View_paddingRight
15441     * @attr ref android.R.styleable#View_paddingTop
15442     * @param left the left padding in pixels
15443     * @param top the top padding in pixels
15444     * @param right the right padding in pixels
15445     * @param bottom the bottom padding in pixels
15446     */
15447    public void setPadding(int left, int top, int right, int bottom) {
15448        resetResolvedPadding();
15449
15450        mUserPaddingStart = UNDEFINED_PADDING;
15451        mUserPaddingEnd = UNDEFINED_PADDING;
15452
15453        mUserPaddingLeftInitial = left;
15454        mUserPaddingRightInitial = right;
15455
15456        mUseBackgroundPadding = false;
15457
15458        internalSetPadding(left, top, right, bottom);
15459    }
15460
15461    /**
15462     * @hide
15463     */
15464    protected void internalSetPadding(int left, int top, int right, int bottom) {
15465        mUserPaddingLeft = left;
15466        mUserPaddingRight = right;
15467        mUserPaddingBottom = bottom;
15468
15469        final int viewFlags = mViewFlags;
15470        boolean changed = false;
15471
15472        // Common case is there are no scroll bars.
15473        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
15474            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
15475                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
15476                        ? 0 : getVerticalScrollbarWidth();
15477                switch (mVerticalScrollbarPosition) {
15478                    case SCROLLBAR_POSITION_DEFAULT:
15479                        if (isLayoutRtl()) {
15480                            left += offset;
15481                        } else {
15482                            right += offset;
15483                        }
15484                        break;
15485                    case SCROLLBAR_POSITION_RIGHT:
15486                        right += offset;
15487                        break;
15488                    case SCROLLBAR_POSITION_LEFT:
15489                        left += offset;
15490                        break;
15491                }
15492            }
15493            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
15494                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
15495                        ? 0 : getHorizontalScrollbarHeight();
15496            }
15497        }
15498
15499        if (mPaddingLeft != left) {
15500            changed = true;
15501            mPaddingLeft = left;
15502        }
15503        if (mPaddingTop != top) {
15504            changed = true;
15505            mPaddingTop = top;
15506        }
15507        if (mPaddingRight != right) {
15508            changed = true;
15509            mPaddingRight = right;
15510        }
15511        if (mPaddingBottom != bottom) {
15512            changed = true;
15513            mPaddingBottom = bottom;
15514        }
15515
15516        if (changed) {
15517            requestLayout();
15518        }
15519    }
15520
15521    /**
15522     * Sets the relative padding. The view may add on the space required to display
15523     * the scrollbars, depending on the style and visibility of the scrollbars.
15524     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
15525     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
15526     * from the values set in this call.
15527     *
15528     * @attr ref android.R.styleable#View_padding
15529     * @attr ref android.R.styleable#View_paddingBottom
15530     * @attr ref android.R.styleable#View_paddingStart
15531     * @attr ref android.R.styleable#View_paddingEnd
15532     * @attr ref android.R.styleable#View_paddingTop
15533     * @param start the start padding in pixels
15534     * @param top the top padding in pixels
15535     * @param end the end padding in pixels
15536     * @param bottom the bottom padding in pixels
15537     */
15538    public void setPaddingRelative(int start, int top, int end, int bottom) {
15539        resetResolvedPadding();
15540
15541        mUserPaddingStart = start;
15542        mUserPaddingEnd = end;
15543
15544        mUseBackgroundPadding = false;
15545
15546        switch(getLayoutDirection()) {
15547            case LAYOUT_DIRECTION_RTL:
15548                mUserPaddingLeftInitial = end;
15549                mUserPaddingRightInitial = start;
15550                internalSetPadding(end, top, start, bottom);
15551                break;
15552            case LAYOUT_DIRECTION_LTR:
15553            default:
15554                mUserPaddingLeftInitial = start;
15555                mUserPaddingRightInitial = end;
15556                internalSetPadding(start, top, end, bottom);
15557        }
15558    }
15559
15560    /**
15561     * Returns the top padding of this view.
15562     *
15563     * @return the top padding in pixels
15564     */
15565    public int getPaddingTop() {
15566        return mPaddingTop;
15567    }
15568
15569    /**
15570     * Returns the bottom padding of this view. If there are inset and enabled
15571     * scrollbars, this value may include the space required to display the
15572     * scrollbars as well.
15573     *
15574     * @return the bottom padding in pixels
15575     */
15576    public int getPaddingBottom() {
15577        return mPaddingBottom;
15578    }
15579
15580    /**
15581     * Returns the left padding of this view. If there are inset and enabled
15582     * scrollbars, this value may include the space required to display the
15583     * scrollbars as well.
15584     *
15585     * @return the left padding in pixels
15586     */
15587    public int getPaddingLeft() {
15588        if (!isPaddingResolved()) {
15589            resolvePadding();
15590        }
15591        return mPaddingLeft;
15592    }
15593
15594    /**
15595     * Returns the start padding of this view depending on its resolved layout direction.
15596     * If there are inset and enabled scrollbars, this value may include the space
15597     * required to display the scrollbars as well.
15598     *
15599     * @return the start padding in pixels
15600     */
15601    public int getPaddingStart() {
15602        if (!isPaddingResolved()) {
15603            resolvePadding();
15604        }
15605        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
15606                mPaddingRight : mPaddingLeft;
15607    }
15608
15609    /**
15610     * Returns the right padding of this view. If there are inset and enabled
15611     * scrollbars, this value may include the space required to display the
15612     * scrollbars as well.
15613     *
15614     * @return the right padding in pixels
15615     */
15616    public int getPaddingRight() {
15617        if (!isPaddingResolved()) {
15618            resolvePadding();
15619        }
15620        return mPaddingRight;
15621    }
15622
15623    /**
15624     * Returns the end padding of this view depending on its resolved layout direction.
15625     * If there are inset and enabled scrollbars, this value may include the space
15626     * required to display the scrollbars as well.
15627     *
15628     * @return the end padding in pixels
15629     */
15630    public int getPaddingEnd() {
15631        if (!isPaddingResolved()) {
15632            resolvePadding();
15633        }
15634        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
15635                mPaddingLeft : mPaddingRight;
15636    }
15637
15638    /**
15639     * Return if the padding as been set thru relative values
15640     * {@link #setPaddingRelative(int, int, int, int)} or thru
15641     * @attr ref android.R.styleable#View_paddingStart or
15642     * @attr ref android.R.styleable#View_paddingEnd
15643     *
15644     * @return true if the padding is relative or false if it is not.
15645     */
15646    public boolean isPaddingRelative() {
15647        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
15648    }
15649
15650    Insets computeOpticalInsets() {
15651        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
15652    }
15653
15654    /**
15655     * @hide
15656     */
15657    public void resetPaddingToInitialValues() {
15658        if (isRtlCompatibilityMode()) {
15659            mPaddingLeft = mUserPaddingLeftInitial;
15660            mPaddingRight = mUserPaddingRightInitial;
15661            return;
15662        }
15663        if (isLayoutRtl()) {
15664            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
15665            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
15666        } else {
15667            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
15668            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
15669        }
15670    }
15671
15672    /**
15673     * @hide
15674     */
15675    public Insets getOpticalInsets() {
15676        if (mLayoutInsets == null) {
15677            mLayoutInsets = computeOpticalInsets();
15678        }
15679        return mLayoutInsets;
15680    }
15681
15682    /**
15683     * Changes the selection state of this view. A view can be selected or not.
15684     * Note that selection is not the same as focus. Views are typically
15685     * selected in the context of an AdapterView like ListView or GridView;
15686     * the selected view is the view that is highlighted.
15687     *
15688     * @param selected true if the view must be selected, false otherwise
15689     */
15690    public void setSelected(boolean selected) {
15691        //noinspection DoubleNegation
15692        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
15693            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
15694            if (!selected) resetPressedState();
15695            invalidate(true);
15696            refreshDrawableState();
15697            dispatchSetSelected(selected);
15698            notifyViewAccessibilityStateChangedIfNeeded(
15699                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
15700        }
15701    }
15702
15703    /**
15704     * Dispatch setSelected to all of this View's children.
15705     *
15706     * @see #setSelected(boolean)
15707     *
15708     * @param selected The new selected state
15709     */
15710    protected void dispatchSetSelected(boolean selected) {
15711    }
15712
15713    /**
15714     * Indicates the selection state of this view.
15715     *
15716     * @return true if the view is selected, false otherwise
15717     */
15718    @ViewDebug.ExportedProperty
15719    public boolean isSelected() {
15720        return (mPrivateFlags & PFLAG_SELECTED) != 0;
15721    }
15722
15723    /**
15724     * Changes the activated state of this view. A view can be activated or not.
15725     * Note that activation is not the same as selection.  Selection is
15726     * a transient property, representing the view (hierarchy) the user is
15727     * currently interacting with.  Activation is a longer-term state that the
15728     * user can move views in and out of.  For example, in a list view with
15729     * single or multiple selection enabled, the views in the current selection
15730     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
15731     * here.)  The activated state is propagated down to children of the view it
15732     * is set on.
15733     *
15734     * @param activated true if the view must be activated, false otherwise
15735     */
15736    public void setActivated(boolean activated) {
15737        //noinspection DoubleNegation
15738        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
15739            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
15740            invalidate(true);
15741            refreshDrawableState();
15742            dispatchSetActivated(activated);
15743        }
15744    }
15745
15746    /**
15747     * Dispatch setActivated to all of this View's children.
15748     *
15749     * @see #setActivated(boolean)
15750     *
15751     * @param activated The new activated state
15752     */
15753    protected void dispatchSetActivated(boolean activated) {
15754    }
15755
15756    /**
15757     * Indicates the activation state of this view.
15758     *
15759     * @return true if the view is activated, false otherwise
15760     */
15761    @ViewDebug.ExportedProperty
15762    public boolean isActivated() {
15763        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
15764    }
15765
15766    /**
15767     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
15768     * observer can be used to get notifications when global events, like
15769     * layout, happen.
15770     *
15771     * The returned ViewTreeObserver observer is not guaranteed to remain
15772     * valid for the lifetime of this View. If the caller of this method keeps
15773     * a long-lived reference to ViewTreeObserver, it should always check for
15774     * the return value of {@link ViewTreeObserver#isAlive()}.
15775     *
15776     * @return The ViewTreeObserver for this view's hierarchy.
15777     */
15778    public ViewTreeObserver getViewTreeObserver() {
15779        if (mAttachInfo != null) {
15780            return mAttachInfo.mTreeObserver;
15781        }
15782        if (mFloatingTreeObserver == null) {
15783            mFloatingTreeObserver = new ViewTreeObserver();
15784        }
15785        return mFloatingTreeObserver;
15786    }
15787
15788    /**
15789     * <p>Finds the topmost view in the current view hierarchy.</p>
15790     *
15791     * @return the topmost view containing this view
15792     */
15793    public View getRootView() {
15794        if (mAttachInfo != null) {
15795            final View v = mAttachInfo.mRootView;
15796            if (v != null) {
15797                return v;
15798            }
15799        }
15800
15801        View parent = this;
15802
15803        while (parent.mParent != null && parent.mParent instanceof View) {
15804            parent = (View) parent.mParent;
15805        }
15806
15807        return parent;
15808    }
15809
15810    /**
15811     * Transforms a motion event from view-local coordinates to on-screen
15812     * coordinates.
15813     *
15814     * @param ev the view-local motion event
15815     * @return false if the transformation could not be applied
15816     * @hide
15817     */
15818    public boolean toGlobalMotionEvent(MotionEvent ev) {
15819        final AttachInfo info = mAttachInfo;
15820        if (info == null) {
15821            return false;
15822        }
15823
15824        transformMotionEventToGlobal(ev);
15825        ev.offsetLocation(info.mWindowLeft, info.mWindowTop);
15826        return true;
15827    }
15828
15829    /**
15830     * Transforms a motion event from on-screen coordinates to view-local
15831     * coordinates.
15832     *
15833     * @param ev the on-screen motion event
15834     * @return false if the transformation could not be applied
15835     * @hide
15836     */
15837    public boolean toLocalMotionEvent(MotionEvent ev) {
15838        final AttachInfo info = mAttachInfo;
15839        if (info == null) {
15840            return false;
15841        }
15842
15843        ev.offsetLocation(-info.mWindowLeft, -info.mWindowTop);
15844        transformMotionEventToLocal(ev);
15845        return true;
15846    }
15847
15848    /**
15849     * Recursive helper method that applies transformations in post-order.
15850     *
15851     * @param ev the on-screen motion event
15852     */
15853    private void transformMotionEventToLocal(MotionEvent ev) {
15854        final ViewParent parent = mParent;
15855        if (parent instanceof View) {
15856            final View vp = (View) parent;
15857            vp.transformMotionEventToLocal(ev);
15858            ev.offsetLocation(vp.mScrollX, vp.mScrollY);
15859        } else if (parent instanceof ViewRootImpl) {
15860            final ViewRootImpl vr = (ViewRootImpl) parent;
15861            ev.offsetLocation(0, vr.mCurScrollY);
15862        }
15863
15864        ev.offsetLocation(-mLeft, -mTop);
15865
15866        if (!hasIdentityMatrix()) {
15867            ev.transform(getInverseMatrix());
15868        }
15869    }
15870
15871    /**
15872     * Recursive helper method that applies transformations in pre-order.
15873     *
15874     * @param ev the on-screen motion event
15875     */
15876    private void transformMotionEventToGlobal(MotionEvent ev) {
15877        if (!hasIdentityMatrix()) {
15878            ev.transform(getMatrix());
15879        }
15880
15881        ev.offsetLocation(mLeft, mTop);
15882
15883        final ViewParent parent = mParent;
15884        if (parent instanceof View) {
15885            final View vp = (View) parent;
15886            ev.offsetLocation(-vp.mScrollX, -vp.mScrollY);
15887            vp.transformMotionEventToGlobal(ev);
15888        } else if (parent instanceof ViewRootImpl) {
15889            final ViewRootImpl vr = (ViewRootImpl) parent;
15890            ev.offsetLocation(0, -vr.mCurScrollY);
15891        }
15892    }
15893
15894    /**
15895     * <p>Computes the coordinates of this view on the screen. The argument
15896     * must be an array of two integers. After the method returns, the array
15897     * contains the x and y location in that order.</p>
15898     *
15899     * @param location an array of two integers in which to hold the coordinates
15900     */
15901    public void getLocationOnScreen(int[] location) {
15902        getLocationInWindow(location);
15903
15904        final AttachInfo info = mAttachInfo;
15905        if (info != null) {
15906            location[0] += info.mWindowLeft;
15907            location[1] += info.mWindowTop;
15908        }
15909    }
15910
15911    /**
15912     * <p>Computes the coordinates of this view in its window. The argument
15913     * must be an array of two integers. After the method returns, the array
15914     * contains the x and y location in that order.</p>
15915     *
15916     * @param location an array of two integers in which to hold the coordinates
15917     */
15918    public void getLocationInWindow(int[] location) {
15919        if (location == null || location.length < 2) {
15920            throw new IllegalArgumentException("location must be an array of two integers");
15921        }
15922
15923        if (mAttachInfo == null) {
15924            // When the view is not attached to a window, this method does not make sense
15925            location[0] = location[1] = 0;
15926            return;
15927        }
15928
15929        float[] position = mAttachInfo.mTmpTransformLocation;
15930        position[0] = position[1] = 0.0f;
15931
15932        if (!hasIdentityMatrix()) {
15933            getMatrix().mapPoints(position);
15934        }
15935
15936        position[0] += mLeft;
15937        position[1] += mTop;
15938
15939        ViewParent viewParent = mParent;
15940        while (viewParent instanceof View) {
15941            final View view = (View) viewParent;
15942
15943            position[0] -= view.mScrollX;
15944            position[1] -= view.mScrollY;
15945
15946            if (!view.hasIdentityMatrix()) {
15947                view.getMatrix().mapPoints(position);
15948            }
15949
15950            position[0] += view.mLeft;
15951            position[1] += view.mTop;
15952
15953            viewParent = view.mParent;
15954         }
15955
15956        if (viewParent instanceof ViewRootImpl) {
15957            // *cough*
15958            final ViewRootImpl vr = (ViewRootImpl) viewParent;
15959            position[1] -= vr.mCurScrollY;
15960        }
15961
15962        location[0] = (int) (position[0] + 0.5f);
15963        location[1] = (int) (position[1] + 0.5f);
15964    }
15965
15966    /**
15967     * {@hide}
15968     * @param id the id of the view to be found
15969     * @return the view of the specified id, null if cannot be found
15970     */
15971    protected View findViewTraversal(int id) {
15972        if (id == mID) {
15973            return this;
15974        }
15975        return null;
15976    }
15977
15978    /**
15979     * {@hide}
15980     * @param tag the tag of the view to be found
15981     * @return the view of specified tag, null if cannot be found
15982     */
15983    protected View findViewWithTagTraversal(Object tag) {
15984        if (tag != null && tag.equals(mTag)) {
15985            return this;
15986        }
15987        return null;
15988    }
15989
15990    /**
15991     * {@hide}
15992     * @param predicate The predicate to evaluate.
15993     * @param childToSkip If not null, ignores this child during the recursive traversal.
15994     * @return The first view that matches the predicate or null.
15995     */
15996    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
15997        if (predicate.apply(this)) {
15998            return this;
15999        }
16000        return null;
16001    }
16002
16003    /**
16004     * Look for a child view with the given id.  If this view has the given
16005     * id, return this view.
16006     *
16007     * @param id The id to search for.
16008     * @return The view that has the given id in the hierarchy or null
16009     */
16010    public final View findViewById(int id) {
16011        if (id < 0) {
16012            return null;
16013        }
16014        return findViewTraversal(id);
16015    }
16016
16017    /**
16018     * Finds a view by its unuque and stable accessibility id.
16019     *
16020     * @param accessibilityId The searched accessibility id.
16021     * @return The found view.
16022     */
16023    final View findViewByAccessibilityId(int accessibilityId) {
16024        if (accessibilityId < 0) {
16025            return null;
16026        }
16027        return findViewByAccessibilityIdTraversal(accessibilityId);
16028    }
16029
16030    /**
16031     * Performs the traversal to find a view by its unuque and stable accessibility id.
16032     *
16033     * <strong>Note:</strong>This method does not stop at the root namespace
16034     * boundary since the user can touch the screen at an arbitrary location
16035     * potentially crossing the root namespace bounday which will send an
16036     * accessibility event to accessibility services and they should be able
16037     * to obtain the event source. Also accessibility ids are guaranteed to be
16038     * unique in the window.
16039     *
16040     * @param accessibilityId The accessibility id.
16041     * @return The found view.
16042     *
16043     * @hide
16044     */
16045    public View findViewByAccessibilityIdTraversal(int accessibilityId) {
16046        if (getAccessibilityViewId() == accessibilityId) {
16047            return this;
16048        }
16049        return null;
16050    }
16051
16052    /**
16053     * Look for a child view with the given tag.  If this view has the given
16054     * tag, return this view.
16055     *
16056     * @param tag The tag to search for, using "tag.equals(getTag())".
16057     * @return The View that has the given tag in the hierarchy or null
16058     */
16059    public final View findViewWithTag(Object tag) {
16060        if (tag == null) {
16061            return null;
16062        }
16063        return findViewWithTagTraversal(tag);
16064    }
16065
16066    /**
16067     * {@hide}
16068     * Look for a child view that matches the specified predicate.
16069     * If this view matches the predicate, return this view.
16070     *
16071     * @param predicate The predicate to evaluate.
16072     * @return The first view that matches the predicate or null.
16073     */
16074    public final View findViewByPredicate(Predicate<View> predicate) {
16075        return findViewByPredicateTraversal(predicate, null);
16076    }
16077
16078    /**
16079     * {@hide}
16080     * Look for a child view that matches the specified predicate,
16081     * starting with the specified view and its descendents and then
16082     * recusively searching the ancestors and siblings of that view
16083     * until this view is reached.
16084     *
16085     * This method is useful in cases where the predicate does not match
16086     * a single unique view (perhaps multiple views use the same id)
16087     * and we are trying to find the view that is "closest" in scope to the
16088     * starting view.
16089     *
16090     * @param start The view to start from.
16091     * @param predicate The predicate to evaluate.
16092     * @return The first view that matches the predicate or null.
16093     */
16094    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
16095        View childToSkip = null;
16096        for (;;) {
16097            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
16098            if (view != null || start == this) {
16099                return view;
16100            }
16101
16102            ViewParent parent = start.getParent();
16103            if (parent == null || !(parent instanceof View)) {
16104                return null;
16105            }
16106
16107            childToSkip = start;
16108            start = (View) parent;
16109        }
16110    }
16111
16112    /**
16113     * Sets the identifier for this view. The identifier does not have to be
16114     * unique in this view's hierarchy. The identifier should be a positive
16115     * number.
16116     *
16117     * @see #NO_ID
16118     * @see #getId()
16119     * @see #findViewById(int)
16120     *
16121     * @param id a number used to identify the view
16122     *
16123     * @attr ref android.R.styleable#View_id
16124     */
16125    public void setId(int id) {
16126        mID = id;
16127        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
16128            mID = generateViewId();
16129        }
16130    }
16131
16132    /**
16133     * {@hide}
16134     *
16135     * @param isRoot true if the view belongs to the root namespace, false
16136     *        otherwise
16137     */
16138    public void setIsRootNamespace(boolean isRoot) {
16139        if (isRoot) {
16140            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
16141        } else {
16142            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
16143        }
16144    }
16145
16146    /**
16147     * {@hide}
16148     *
16149     * @return true if the view belongs to the root namespace, false otherwise
16150     */
16151    public boolean isRootNamespace() {
16152        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
16153    }
16154
16155    /**
16156     * Returns this view's identifier.
16157     *
16158     * @return a positive integer used to identify the view or {@link #NO_ID}
16159     *         if the view has no ID
16160     *
16161     * @see #setId(int)
16162     * @see #findViewById(int)
16163     * @attr ref android.R.styleable#View_id
16164     */
16165    @ViewDebug.CapturedViewProperty
16166    public int getId() {
16167        return mID;
16168    }
16169
16170    /**
16171     * Returns this view's tag.
16172     *
16173     * @return the Object stored in this view as a tag
16174     *
16175     * @see #setTag(Object)
16176     * @see #getTag(int)
16177     */
16178    @ViewDebug.ExportedProperty
16179    public Object getTag() {
16180        return mTag;
16181    }
16182
16183    /**
16184     * Sets the tag associated with this view. A tag can be used to mark
16185     * a view in its hierarchy and does not have to be unique within the
16186     * hierarchy. Tags can also be used to store data within a view without
16187     * resorting to another data structure.
16188     *
16189     * @param tag an Object to tag the view with
16190     *
16191     * @see #getTag()
16192     * @see #setTag(int, Object)
16193     */
16194    public void setTag(final Object tag) {
16195        mTag = tag;
16196    }
16197
16198    /**
16199     * Returns the tag associated with this view and the specified key.
16200     *
16201     * @param key The key identifying the tag
16202     *
16203     * @return the Object stored in this view as a tag
16204     *
16205     * @see #setTag(int, Object)
16206     * @see #getTag()
16207     */
16208    public Object getTag(int key) {
16209        if (mKeyedTags != null) return mKeyedTags.get(key);
16210        return null;
16211    }
16212
16213    /**
16214     * Sets a tag associated with this view and a key. A tag can be used
16215     * to mark a view in its hierarchy and does not have to be unique within
16216     * the hierarchy. Tags can also be used to store data within a view
16217     * without resorting to another data structure.
16218     *
16219     * The specified key should be an id declared in the resources of the
16220     * application to ensure it is unique (see the <a
16221     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
16222     * Keys identified as belonging to
16223     * the Android framework or not associated with any package will cause
16224     * an {@link IllegalArgumentException} to be thrown.
16225     *
16226     * @param key The key identifying the tag
16227     * @param tag An Object to tag the view with
16228     *
16229     * @throws IllegalArgumentException If they specified key is not valid
16230     *
16231     * @see #setTag(Object)
16232     * @see #getTag(int)
16233     */
16234    public void setTag(int key, final Object tag) {
16235        // If the package id is 0x00 or 0x01, it's either an undefined package
16236        // or a framework id
16237        if ((key >>> 24) < 2) {
16238            throw new IllegalArgumentException("The key must be an application-specific "
16239                    + "resource id.");
16240        }
16241
16242        setKeyedTag(key, tag);
16243    }
16244
16245    /**
16246     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
16247     * framework id.
16248     *
16249     * @hide
16250     */
16251    public void setTagInternal(int key, Object tag) {
16252        if ((key >>> 24) != 0x1) {
16253            throw new IllegalArgumentException("The key must be a framework-specific "
16254                    + "resource id.");
16255        }
16256
16257        setKeyedTag(key, tag);
16258    }
16259
16260    private void setKeyedTag(int key, Object tag) {
16261        if (mKeyedTags == null) {
16262            mKeyedTags = new SparseArray<Object>(2);
16263        }
16264
16265        mKeyedTags.put(key, tag);
16266    }
16267
16268    /**
16269     * Prints information about this view in the log output, with the tag
16270     * {@link #VIEW_LOG_TAG}.
16271     *
16272     * @hide
16273     */
16274    public void debug() {
16275        debug(0);
16276    }
16277
16278    /**
16279     * Prints information about this view in the log output, with the tag
16280     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
16281     * indentation defined by the <code>depth</code>.
16282     *
16283     * @param depth the indentation level
16284     *
16285     * @hide
16286     */
16287    protected void debug(int depth) {
16288        String output = debugIndent(depth - 1);
16289
16290        output += "+ " + this;
16291        int id = getId();
16292        if (id != -1) {
16293            output += " (id=" + id + ")";
16294        }
16295        Object tag = getTag();
16296        if (tag != null) {
16297            output += " (tag=" + tag + ")";
16298        }
16299        Log.d(VIEW_LOG_TAG, output);
16300
16301        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
16302            output = debugIndent(depth) + " FOCUSED";
16303            Log.d(VIEW_LOG_TAG, output);
16304        }
16305
16306        output = debugIndent(depth);
16307        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
16308                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
16309                + "} ";
16310        Log.d(VIEW_LOG_TAG, output);
16311
16312        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
16313                || mPaddingBottom != 0) {
16314            output = debugIndent(depth);
16315            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
16316                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
16317            Log.d(VIEW_LOG_TAG, output);
16318        }
16319
16320        output = debugIndent(depth);
16321        output += "mMeasureWidth=" + mMeasuredWidth +
16322                " mMeasureHeight=" + mMeasuredHeight;
16323        Log.d(VIEW_LOG_TAG, output);
16324
16325        output = debugIndent(depth);
16326        if (mLayoutParams == null) {
16327            output += "BAD! no layout params";
16328        } else {
16329            output = mLayoutParams.debug(output);
16330        }
16331        Log.d(VIEW_LOG_TAG, output);
16332
16333        output = debugIndent(depth);
16334        output += "flags={";
16335        output += View.printFlags(mViewFlags);
16336        output += "}";
16337        Log.d(VIEW_LOG_TAG, output);
16338
16339        output = debugIndent(depth);
16340        output += "privateFlags={";
16341        output += View.printPrivateFlags(mPrivateFlags);
16342        output += "}";
16343        Log.d(VIEW_LOG_TAG, output);
16344    }
16345
16346    /**
16347     * Creates a string of whitespaces used for indentation.
16348     *
16349     * @param depth the indentation level
16350     * @return a String containing (depth * 2 + 3) * 2 white spaces
16351     *
16352     * @hide
16353     */
16354    protected static String debugIndent(int depth) {
16355        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
16356        for (int i = 0; i < (depth * 2) + 3; i++) {
16357            spaces.append(' ').append(' ');
16358        }
16359        return spaces.toString();
16360    }
16361
16362    /**
16363     * <p>Return the offset of the widget's text baseline from the widget's top
16364     * boundary. If this widget does not support baseline alignment, this
16365     * method returns -1. </p>
16366     *
16367     * @return the offset of the baseline within the widget's bounds or -1
16368     *         if baseline alignment is not supported
16369     */
16370    @ViewDebug.ExportedProperty(category = "layout")
16371    public int getBaseline() {
16372        return -1;
16373    }
16374
16375    /**
16376     * Returns whether the view hierarchy is currently undergoing a layout pass. This
16377     * information is useful to avoid situations such as calling {@link #requestLayout()} during
16378     * a layout pass.
16379     *
16380     * @return whether the view hierarchy is currently undergoing a layout pass
16381     */
16382    public boolean isInLayout() {
16383        ViewRootImpl viewRoot = getViewRootImpl();
16384        return (viewRoot != null && viewRoot.isInLayout());
16385    }
16386
16387    /**
16388     * Call this when something has changed which has invalidated the
16389     * layout of this view. This will schedule a layout pass of the view
16390     * tree. This should not be called while the view hierarchy is currently in a layout
16391     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
16392     * end of the current layout pass (and then layout will run again) or after the current
16393     * frame is drawn and the next layout occurs.
16394     *
16395     * <p>Subclasses which override this method should call the superclass method to
16396     * handle possible request-during-layout errors correctly.</p>
16397     */
16398    public void requestLayout() {
16399        if (mMeasureCache != null) mMeasureCache.clear();
16400
16401        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
16402            // Only trigger request-during-layout logic if this is the view requesting it,
16403            // not the views in its parent hierarchy
16404            ViewRootImpl viewRoot = getViewRootImpl();
16405            if (viewRoot != null && viewRoot.isInLayout()) {
16406                if (!viewRoot.requestLayoutDuringLayout(this)) {
16407                    return;
16408                }
16409            }
16410            mAttachInfo.mViewRequestingLayout = this;
16411        }
16412
16413        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
16414        mPrivateFlags |= PFLAG_INVALIDATED;
16415
16416        if (mParent != null && !mParent.isLayoutRequested()) {
16417            mParent.requestLayout();
16418        }
16419        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
16420            mAttachInfo.mViewRequestingLayout = null;
16421        }
16422    }
16423
16424    /**
16425     * Forces this view to be laid out during the next layout pass.
16426     * This method does not call requestLayout() or forceLayout()
16427     * on the parent.
16428     */
16429    public void forceLayout() {
16430        if (mMeasureCache != null) mMeasureCache.clear();
16431
16432        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
16433        mPrivateFlags |= PFLAG_INVALIDATED;
16434    }
16435
16436    /**
16437     * <p>
16438     * This is called to find out how big a view should be. The parent
16439     * supplies constraint information in the width and height parameters.
16440     * </p>
16441     *
16442     * <p>
16443     * The actual measurement work of a view is performed in
16444     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
16445     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
16446     * </p>
16447     *
16448     *
16449     * @param widthMeasureSpec Horizontal space requirements as imposed by the
16450     *        parent
16451     * @param heightMeasureSpec Vertical space requirements as imposed by the
16452     *        parent
16453     *
16454     * @see #onMeasure(int, int)
16455     */
16456    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
16457        boolean optical = isLayoutModeOptical(this);
16458        if (optical != isLayoutModeOptical(mParent)) {
16459            Insets insets = getOpticalInsets();
16460            int oWidth  = insets.left + insets.right;
16461            int oHeight = insets.top  + insets.bottom;
16462            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
16463            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
16464        }
16465
16466        // Suppress sign extension for the low bytes
16467        long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
16468        if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
16469
16470        if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ||
16471                widthMeasureSpec != mOldWidthMeasureSpec ||
16472                heightMeasureSpec != mOldHeightMeasureSpec) {
16473
16474            // first clears the measured dimension flag
16475            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
16476
16477            resolveRtlPropertiesIfNeeded();
16478
16479            int cacheIndex = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ? -1 :
16480                    mMeasureCache.indexOfKey(key);
16481            if (cacheIndex < 0 || sIgnoreMeasureCache) {
16482                // measure ourselves, this should set the measured dimension flag back
16483                onMeasure(widthMeasureSpec, heightMeasureSpec);
16484                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
16485            } else {
16486                long value = mMeasureCache.valueAt(cacheIndex);
16487                // Casting a long to int drops the high 32 bits, no mask needed
16488                setMeasuredDimension((int) (value >> 32), (int) value);
16489                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
16490            }
16491
16492            // flag not set, setMeasuredDimension() was not invoked, we raise
16493            // an exception to warn the developer
16494            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
16495                throw new IllegalStateException("onMeasure() did not set the"
16496                        + " measured dimension by calling"
16497                        + " setMeasuredDimension()");
16498            }
16499
16500            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
16501        }
16502
16503        mOldWidthMeasureSpec = widthMeasureSpec;
16504        mOldHeightMeasureSpec = heightMeasureSpec;
16505
16506        mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
16507                (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
16508    }
16509
16510    /**
16511     * <p>
16512     * Measure the view and its content to determine the measured width and the
16513     * measured height. This method is invoked by {@link #measure(int, int)} and
16514     * should be overriden by subclasses to provide accurate and efficient
16515     * measurement of their contents.
16516     * </p>
16517     *
16518     * <p>
16519     * <strong>CONTRACT:</strong> When overriding this method, you
16520     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
16521     * measured width and height of this view. Failure to do so will trigger an
16522     * <code>IllegalStateException</code>, thrown by
16523     * {@link #measure(int, int)}. Calling the superclass'
16524     * {@link #onMeasure(int, int)} is a valid use.
16525     * </p>
16526     *
16527     * <p>
16528     * The base class implementation of measure defaults to the background size,
16529     * unless a larger size is allowed by the MeasureSpec. Subclasses should
16530     * override {@link #onMeasure(int, int)} to provide better measurements of
16531     * their content.
16532     * </p>
16533     *
16534     * <p>
16535     * If this method is overridden, it is the subclass's responsibility to make
16536     * sure the measured height and width are at least the view's minimum height
16537     * and width ({@link #getSuggestedMinimumHeight()} and
16538     * {@link #getSuggestedMinimumWidth()}).
16539     * </p>
16540     *
16541     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
16542     *                         The requirements are encoded with
16543     *                         {@link android.view.View.MeasureSpec}.
16544     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
16545     *                         The requirements are encoded with
16546     *                         {@link android.view.View.MeasureSpec}.
16547     *
16548     * @see #getMeasuredWidth()
16549     * @see #getMeasuredHeight()
16550     * @see #setMeasuredDimension(int, int)
16551     * @see #getSuggestedMinimumHeight()
16552     * @see #getSuggestedMinimumWidth()
16553     * @see android.view.View.MeasureSpec#getMode(int)
16554     * @see android.view.View.MeasureSpec#getSize(int)
16555     */
16556    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
16557        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
16558                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
16559    }
16560
16561    /**
16562     * <p>This method must be called by {@link #onMeasure(int, int)} to store the
16563     * measured width and measured height. Failing to do so will trigger an
16564     * exception at measurement time.</p>
16565     *
16566     * @param measuredWidth The measured width of this view.  May be a complex
16567     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
16568     * {@link #MEASURED_STATE_TOO_SMALL}.
16569     * @param measuredHeight The measured height of this view.  May be a complex
16570     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
16571     * {@link #MEASURED_STATE_TOO_SMALL}.
16572     */
16573    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
16574        boolean optical = isLayoutModeOptical(this);
16575        if (optical != isLayoutModeOptical(mParent)) {
16576            Insets insets = getOpticalInsets();
16577            int opticalWidth  = insets.left + insets.right;
16578            int opticalHeight = insets.top  + insets.bottom;
16579
16580            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
16581            measuredHeight += optical ? opticalHeight : -opticalHeight;
16582        }
16583        mMeasuredWidth = measuredWidth;
16584        mMeasuredHeight = measuredHeight;
16585
16586        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
16587    }
16588
16589    /**
16590     * Merge two states as returned by {@link #getMeasuredState()}.
16591     * @param curState The current state as returned from a view or the result
16592     * of combining multiple views.
16593     * @param newState The new view state to combine.
16594     * @return Returns a new integer reflecting the combination of the two
16595     * states.
16596     */
16597    public static int combineMeasuredStates(int curState, int newState) {
16598        return curState | newState;
16599    }
16600
16601    /**
16602     * Version of {@link #resolveSizeAndState(int, int, int)}
16603     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
16604     */
16605    public static int resolveSize(int size, int measureSpec) {
16606        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
16607    }
16608
16609    /**
16610     * Utility to reconcile a desired size and state, with constraints imposed
16611     * by a MeasureSpec.  Will take the desired size, unless a different size
16612     * is imposed by the constraints.  The returned value is a compound integer,
16613     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
16614     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
16615     * size is smaller than the size the view wants to be.
16616     *
16617     * @param size How big the view wants to be
16618     * @param measureSpec Constraints imposed by the parent
16619     * @return Size information bit mask as defined by
16620     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
16621     */
16622    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
16623        int result = size;
16624        int specMode = MeasureSpec.getMode(measureSpec);
16625        int specSize =  MeasureSpec.getSize(measureSpec);
16626        switch (specMode) {
16627        case MeasureSpec.UNSPECIFIED:
16628            result = size;
16629            break;
16630        case MeasureSpec.AT_MOST:
16631            if (specSize < size) {
16632                result = specSize | MEASURED_STATE_TOO_SMALL;
16633            } else {
16634                result = size;
16635            }
16636            break;
16637        case MeasureSpec.EXACTLY:
16638            result = specSize;
16639            break;
16640        }
16641        return result | (childMeasuredState&MEASURED_STATE_MASK);
16642    }
16643
16644    /**
16645     * Utility to return a default size. Uses the supplied size if the
16646     * MeasureSpec imposed no constraints. Will get larger if allowed
16647     * by the MeasureSpec.
16648     *
16649     * @param size Default size for this view
16650     * @param measureSpec Constraints imposed by the parent
16651     * @return The size this view should be.
16652     */
16653    public static int getDefaultSize(int size, int measureSpec) {
16654        int result = size;
16655        int specMode = MeasureSpec.getMode(measureSpec);
16656        int specSize = MeasureSpec.getSize(measureSpec);
16657
16658        switch (specMode) {
16659        case MeasureSpec.UNSPECIFIED:
16660            result = size;
16661            break;
16662        case MeasureSpec.AT_MOST:
16663        case MeasureSpec.EXACTLY:
16664            result = specSize;
16665            break;
16666        }
16667        return result;
16668    }
16669
16670    /**
16671     * Returns the suggested minimum height that the view should use. This
16672     * returns the maximum of the view's minimum height
16673     * and the background's minimum height
16674     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
16675     * <p>
16676     * When being used in {@link #onMeasure(int, int)}, the caller should still
16677     * ensure the returned height is within the requirements of the parent.
16678     *
16679     * @return The suggested minimum height of the view.
16680     */
16681    protected int getSuggestedMinimumHeight() {
16682        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
16683
16684    }
16685
16686    /**
16687     * Returns the suggested minimum width that the view should use. This
16688     * returns the maximum of the view's minimum width)
16689     * and the background's minimum width
16690     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
16691     * <p>
16692     * When being used in {@link #onMeasure(int, int)}, the caller should still
16693     * ensure the returned width is within the requirements of the parent.
16694     *
16695     * @return The suggested minimum width of the view.
16696     */
16697    protected int getSuggestedMinimumWidth() {
16698        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
16699    }
16700
16701    /**
16702     * Returns the minimum height of the view.
16703     *
16704     * @return the minimum height the view will try to be.
16705     *
16706     * @see #setMinimumHeight(int)
16707     *
16708     * @attr ref android.R.styleable#View_minHeight
16709     */
16710    public int getMinimumHeight() {
16711        return mMinHeight;
16712    }
16713
16714    /**
16715     * Sets the minimum height of the view. It is not guaranteed the view will
16716     * be able to achieve this minimum height (for example, if its parent layout
16717     * constrains it with less available height).
16718     *
16719     * @param minHeight The minimum height the view will try to be.
16720     *
16721     * @see #getMinimumHeight()
16722     *
16723     * @attr ref android.R.styleable#View_minHeight
16724     */
16725    public void setMinimumHeight(int minHeight) {
16726        mMinHeight = minHeight;
16727        requestLayout();
16728    }
16729
16730    /**
16731     * Returns the minimum width of the view.
16732     *
16733     * @return the minimum width the view will try to be.
16734     *
16735     * @see #setMinimumWidth(int)
16736     *
16737     * @attr ref android.R.styleable#View_minWidth
16738     */
16739    public int getMinimumWidth() {
16740        return mMinWidth;
16741    }
16742
16743    /**
16744     * Sets the minimum width of the view. It is not guaranteed the view will
16745     * be able to achieve this minimum width (for example, if its parent layout
16746     * constrains it with less available width).
16747     *
16748     * @param minWidth The minimum width the view will try to be.
16749     *
16750     * @see #getMinimumWidth()
16751     *
16752     * @attr ref android.R.styleable#View_minWidth
16753     */
16754    public void setMinimumWidth(int minWidth) {
16755        mMinWidth = minWidth;
16756        requestLayout();
16757
16758    }
16759
16760    /**
16761     * Get the animation currently associated with this view.
16762     *
16763     * @return The animation that is currently playing or
16764     *         scheduled to play for this view.
16765     */
16766    public Animation getAnimation() {
16767        return mCurrentAnimation;
16768    }
16769
16770    /**
16771     * Start the specified animation now.
16772     *
16773     * @param animation the animation to start now
16774     */
16775    public void startAnimation(Animation animation) {
16776        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
16777        setAnimation(animation);
16778        invalidateParentCaches();
16779        invalidate(true);
16780    }
16781
16782    /**
16783     * Cancels any animations for this view.
16784     */
16785    public void clearAnimation() {
16786        if (mCurrentAnimation != null) {
16787            mCurrentAnimation.detach();
16788        }
16789        mCurrentAnimation = null;
16790        invalidateParentIfNeeded();
16791    }
16792
16793    /**
16794     * Sets the next animation to play for this view.
16795     * If you want the animation to play immediately, use
16796     * {@link #startAnimation(android.view.animation.Animation)} instead.
16797     * This method provides allows fine-grained
16798     * control over the start time and invalidation, but you
16799     * must make sure that 1) the animation has a start time set, and
16800     * 2) the view's parent (which controls animations on its children)
16801     * will be invalidated when the animation is supposed to
16802     * start.
16803     *
16804     * @param animation The next animation, or null.
16805     */
16806    public void setAnimation(Animation animation) {
16807        mCurrentAnimation = animation;
16808
16809        if (animation != null) {
16810            // If the screen is off assume the animation start time is now instead of
16811            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
16812            // would cause the animation to start when the screen turns back on
16813            if (mAttachInfo != null && !mAttachInfo.mScreenOn &&
16814                    animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
16815                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
16816            }
16817            animation.reset();
16818        }
16819    }
16820
16821    /**
16822     * Invoked by a parent ViewGroup to notify the start of the animation
16823     * currently associated with this view. If you override this method,
16824     * always call super.onAnimationStart();
16825     *
16826     * @see #setAnimation(android.view.animation.Animation)
16827     * @see #getAnimation()
16828     */
16829    protected void onAnimationStart() {
16830        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
16831    }
16832
16833    /**
16834     * Invoked by a parent ViewGroup to notify the end of the animation
16835     * currently associated with this view. If you override this method,
16836     * always call super.onAnimationEnd();
16837     *
16838     * @see #setAnimation(android.view.animation.Animation)
16839     * @see #getAnimation()
16840     */
16841    protected void onAnimationEnd() {
16842        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
16843    }
16844
16845    /**
16846     * Invoked if there is a Transform that involves alpha. Subclass that can
16847     * draw themselves with the specified alpha should return true, and then
16848     * respect that alpha when their onDraw() is called. If this returns false
16849     * then the view may be redirected to draw into an offscreen buffer to
16850     * fulfill the request, which will look fine, but may be slower than if the
16851     * subclass handles it internally. The default implementation returns false.
16852     *
16853     * @param alpha The alpha (0..255) to apply to the view's drawing
16854     * @return true if the view can draw with the specified alpha.
16855     */
16856    protected boolean onSetAlpha(int alpha) {
16857        return false;
16858    }
16859
16860    /**
16861     * This is used by the RootView to perform an optimization when
16862     * the view hierarchy contains one or several SurfaceView.
16863     * SurfaceView is always considered transparent, but its children are not,
16864     * therefore all View objects remove themselves from the global transparent
16865     * region (passed as a parameter to this function).
16866     *
16867     * @param region The transparent region for this ViewAncestor (window).
16868     *
16869     * @return Returns true if the effective visibility of the view at this
16870     * point is opaque, regardless of the transparent region; returns false
16871     * if it is possible for underlying windows to be seen behind the view.
16872     *
16873     * {@hide}
16874     */
16875    public boolean gatherTransparentRegion(Region region) {
16876        final AttachInfo attachInfo = mAttachInfo;
16877        if (region != null && attachInfo != null) {
16878            final int pflags = mPrivateFlags;
16879            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
16880                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
16881                // remove it from the transparent region.
16882                final int[] location = attachInfo.mTransparentLocation;
16883                getLocationInWindow(location);
16884                region.op(location[0], location[1], location[0] + mRight - mLeft,
16885                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
16886            } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) {
16887                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
16888                // exists, so we remove the background drawable's non-transparent
16889                // parts from this transparent region.
16890                applyDrawableToTransparentRegion(mBackground, region);
16891            }
16892        }
16893        return true;
16894    }
16895
16896    /**
16897     * Play a sound effect for this view.
16898     *
16899     * <p>The framework will play sound effects for some built in actions, such as
16900     * clicking, but you may wish to play these effects in your widget,
16901     * for instance, for internal navigation.
16902     *
16903     * <p>The sound effect will only be played if sound effects are enabled by the user, and
16904     * {@link #isSoundEffectsEnabled()} is true.
16905     *
16906     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
16907     */
16908    public void playSoundEffect(int soundConstant) {
16909        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
16910            return;
16911        }
16912        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
16913    }
16914
16915    /**
16916     * BZZZTT!!1!
16917     *
16918     * <p>Provide haptic feedback to the user for this view.
16919     *
16920     * <p>The framework will provide haptic feedback for some built in actions,
16921     * such as long presses, but you may wish to provide feedback for your
16922     * own widget.
16923     *
16924     * <p>The feedback will only be performed if
16925     * {@link #isHapticFeedbackEnabled()} is true.
16926     *
16927     * @param feedbackConstant One of the constants defined in
16928     * {@link HapticFeedbackConstants}
16929     */
16930    public boolean performHapticFeedback(int feedbackConstant) {
16931        return performHapticFeedback(feedbackConstant, 0);
16932    }
16933
16934    /**
16935     * BZZZTT!!1!
16936     *
16937     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
16938     *
16939     * @param feedbackConstant One of the constants defined in
16940     * {@link HapticFeedbackConstants}
16941     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
16942     */
16943    public boolean performHapticFeedback(int feedbackConstant, int flags) {
16944        if (mAttachInfo == null) {
16945            return false;
16946        }
16947        //noinspection SimplifiableIfStatement
16948        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
16949                && !isHapticFeedbackEnabled()) {
16950            return false;
16951        }
16952        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
16953                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
16954    }
16955
16956    /**
16957     * Request that the visibility of the status bar or other screen/window
16958     * decorations be changed.
16959     *
16960     * <p>This method is used to put the over device UI into temporary modes
16961     * where the user's attention is focused more on the application content,
16962     * by dimming or hiding surrounding system affordances.  This is typically
16963     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
16964     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
16965     * to be placed behind the action bar (and with these flags other system
16966     * affordances) so that smooth transitions between hiding and showing them
16967     * can be done.
16968     *
16969     * <p>Two representative examples of the use of system UI visibility is
16970     * implementing a content browsing application (like a magazine reader)
16971     * and a video playing application.
16972     *
16973     * <p>The first code shows a typical implementation of a View in a content
16974     * browsing application.  In this implementation, the application goes
16975     * into a content-oriented mode by hiding the status bar and action bar,
16976     * and putting the navigation elements into lights out mode.  The user can
16977     * then interact with content while in this mode.  Such an application should
16978     * provide an easy way for the user to toggle out of the mode (such as to
16979     * check information in the status bar or access notifications).  In the
16980     * implementation here, this is done simply by tapping on the content.
16981     *
16982     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
16983     *      content}
16984     *
16985     * <p>This second code sample shows a typical implementation of a View
16986     * in a video playing application.  In this situation, while the video is
16987     * playing the application would like to go into a complete full-screen mode,
16988     * to use as much of the display as possible for the video.  When in this state
16989     * the user can not interact with the application; the system intercepts
16990     * touching on the screen to pop the UI out of full screen mode.  See
16991     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
16992     *
16993     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
16994     *      content}
16995     *
16996     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
16997     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
16998     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
16999     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
17000     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
17001     */
17002    public void setSystemUiVisibility(int visibility) {
17003        if (visibility != mSystemUiVisibility) {
17004            mSystemUiVisibility = visibility;
17005            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
17006                mParent.recomputeViewAttributes(this);
17007            }
17008        }
17009    }
17010
17011    /**
17012     * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested.
17013     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
17014     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
17015     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
17016     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
17017     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
17018     */
17019    public int getSystemUiVisibility() {
17020        return mSystemUiVisibility;
17021    }
17022
17023    /**
17024     * Returns the current system UI visibility that is currently set for
17025     * the entire window.  This is the combination of the
17026     * {@link #setSystemUiVisibility(int)} values supplied by all of the
17027     * views in the window.
17028     */
17029    public int getWindowSystemUiVisibility() {
17030        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
17031    }
17032
17033    /**
17034     * Override to find out when the window's requested system UI visibility
17035     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
17036     * This is different from the callbacks received through
17037     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
17038     * in that this is only telling you about the local request of the window,
17039     * not the actual values applied by the system.
17040     */
17041    public void onWindowSystemUiVisibilityChanged(int visible) {
17042    }
17043
17044    /**
17045     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
17046     * the view hierarchy.
17047     */
17048    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
17049        onWindowSystemUiVisibilityChanged(visible);
17050    }
17051
17052    /**
17053     * Set a listener to receive callbacks when the visibility of the system bar changes.
17054     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
17055     */
17056    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
17057        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
17058        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
17059            mParent.recomputeViewAttributes(this);
17060        }
17061    }
17062
17063    /**
17064     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
17065     * the view hierarchy.
17066     */
17067    public void dispatchSystemUiVisibilityChanged(int visibility) {
17068        ListenerInfo li = mListenerInfo;
17069        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
17070            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
17071                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
17072        }
17073    }
17074
17075    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
17076        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
17077        if (val != mSystemUiVisibility) {
17078            setSystemUiVisibility(val);
17079            return true;
17080        }
17081        return false;
17082    }
17083
17084    /** @hide */
17085    public void setDisabledSystemUiVisibility(int flags) {
17086        if (mAttachInfo != null) {
17087            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
17088                mAttachInfo.mDisabledSystemUiVisibility = flags;
17089                if (mParent != null) {
17090                    mParent.recomputeViewAttributes(this);
17091                }
17092            }
17093        }
17094    }
17095
17096    /**
17097     * Creates an image that the system displays during the drag and drop
17098     * operation. This is called a &quot;drag shadow&quot;. The default implementation
17099     * for a DragShadowBuilder based on a View returns an image that has exactly the same
17100     * appearance as the given View. The default also positions the center of the drag shadow
17101     * directly under the touch point. If no View is provided (the constructor with no parameters
17102     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
17103     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
17104     * default is an invisible drag shadow.
17105     * <p>
17106     * You are not required to use the View you provide to the constructor as the basis of the
17107     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
17108     * anything you want as the drag shadow.
17109     * </p>
17110     * <p>
17111     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
17112     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
17113     *  size and position of the drag shadow. It uses this data to construct a
17114     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
17115     *  so that your application can draw the shadow image in the Canvas.
17116     * </p>
17117     *
17118     * <div class="special reference">
17119     * <h3>Developer Guides</h3>
17120     * <p>For a guide to implementing drag and drop features, read the
17121     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
17122     * </div>
17123     */
17124    public static class DragShadowBuilder {
17125        private final WeakReference<View> mView;
17126
17127        /**
17128         * Constructs a shadow image builder based on a View. By default, the resulting drag
17129         * shadow will have the same appearance and dimensions as the View, with the touch point
17130         * over the center of the View.
17131         * @param view A View. Any View in scope can be used.
17132         */
17133        public DragShadowBuilder(View view) {
17134            mView = new WeakReference<View>(view);
17135        }
17136
17137        /**
17138         * Construct a shadow builder object with no associated View.  This
17139         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
17140         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
17141         * to supply the drag shadow's dimensions and appearance without
17142         * reference to any View object. If they are not overridden, then the result is an
17143         * invisible drag shadow.
17144         */
17145        public DragShadowBuilder() {
17146            mView = new WeakReference<View>(null);
17147        }
17148
17149        /**
17150         * Returns the View object that had been passed to the
17151         * {@link #View.DragShadowBuilder(View)}
17152         * constructor.  If that View parameter was {@code null} or if the
17153         * {@link #View.DragShadowBuilder()}
17154         * constructor was used to instantiate the builder object, this method will return
17155         * null.
17156         *
17157         * @return The View object associate with this builder object.
17158         */
17159        @SuppressWarnings({"JavadocReference"})
17160        final public View getView() {
17161            return mView.get();
17162        }
17163
17164        /**
17165         * Provides the metrics for the shadow image. These include the dimensions of
17166         * the shadow image, and the point within that shadow that should
17167         * be centered under the touch location while dragging.
17168         * <p>
17169         * The default implementation sets the dimensions of the shadow to be the
17170         * same as the dimensions of the View itself and centers the shadow under
17171         * the touch point.
17172         * </p>
17173         *
17174         * @param shadowSize A {@link android.graphics.Point} containing the width and height
17175         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
17176         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
17177         * image.
17178         *
17179         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
17180         * shadow image that should be underneath the touch point during the drag and drop
17181         * operation. Your application must set {@link android.graphics.Point#x} to the
17182         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
17183         */
17184        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
17185            final View view = mView.get();
17186            if (view != null) {
17187                shadowSize.set(view.getWidth(), view.getHeight());
17188                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
17189            } else {
17190                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
17191            }
17192        }
17193
17194        /**
17195         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
17196         * based on the dimensions it received from the
17197         * {@link #onProvideShadowMetrics(Point, Point)} callback.
17198         *
17199         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
17200         */
17201        public void onDrawShadow(Canvas canvas) {
17202            final View view = mView.get();
17203            if (view != null) {
17204                view.draw(canvas);
17205            } else {
17206                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
17207            }
17208        }
17209    }
17210
17211    /**
17212     * Starts a drag and drop operation. When your application calls this method, it passes a
17213     * {@link android.view.View.DragShadowBuilder} object to the system. The
17214     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
17215     * to get metrics for the drag shadow, and then calls the object's
17216     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
17217     * <p>
17218     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
17219     *  drag events to all the View objects in your application that are currently visible. It does
17220     *  this either by calling the View object's drag listener (an implementation of
17221     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
17222     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
17223     *  Both are passed a {@link android.view.DragEvent} object that has a
17224     *  {@link android.view.DragEvent#getAction()} value of
17225     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
17226     * </p>
17227     * <p>
17228     * Your application can invoke startDrag() on any attached View object. The View object does not
17229     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
17230     * be related to the View the user selected for dragging.
17231     * </p>
17232     * @param data A {@link android.content.ClipData} object pointing to the data to be
17233     * transferred by the drag and drop operation.
17234     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
17235     * drag shadow.
17236     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
17237     * drop operation. This Object is put into every DragEvent object sent by the system during the
17238     * current drag.
17239     * <p>
17240     * myLocalState is a lightweight mechanism for the sending information from the dragged View
17241     * to the target Views. For example, it can contain flags that differentiate between a
17242     * a copy operation and a move operation.
17243     * </p>
17244     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
17245     * so the parameter should be set to 0.
17246     * @return {@code true} if the method completes successfully, or
17247     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
17248     * do a drag, and so no drag operation is in progress.
17249     */
17250    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
17251            Object myLocalState, int flags) {
17252        if (ViewDebug.DEBUG_DRAG) {
17253            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
17254        }
17255        boolean okay = false;
17256
17257        Point shadowSize = new Point();
17258        Point shadowTouchPoint = new Point();
17259        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
17260
17261        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
17262                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
17263            throw new IllegalStateException("Drag shadow dimensions must not be negative");
17264        }
17265
17266        if (ViewDebug.DEBUG_DRAG) {
17267            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
17268                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
17269        }
17270        Surface surface = new Surface();
17271        try {
17272            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
17273                    flags, shadowSize.x, shadowSize.y, surface);
17274            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
17275                    + " surface=" + surface);
17276            if (token != null) {
17277                Canvas canvas = surface.lockCanvas(null);
17278                try {
17279                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
17280                    shadowBuilder.onDrawShadow(canvas);
17281                } finally {
17282                    surface.unlockCanvasAndPost(canvas);
17283                }
17284
17285                final ViewRootImpl root = getViewRootImpl();
17286
17287                // Cache the local state object for delivery with DragEvents
17288                root.setLocalDragState(myLocalState);
17289
17290                // repurpose 'shadowSize' for the last touch point
17291                root.getLastTouchPoint(shadowSize);
17292
17293                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
17294                        shadowSize.x, shadowSize.y,
17295                        shadowTouchPoint.x, shadowTouchPoint.y, data);
17296                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
17297
17298                // Off and running!  Release our local surface instance; the drag
17299                // shadow surface is now managed by the system process.
17300                surface.release();
17301            }
17302        } catch (Exception e) {
17303            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
17304            surface.destroy();
17305        }
17306
17307        return okay;
17308    }
17309
17310    /**
17311     * Handles drag events sent by the system following a call to
17312     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
17313     *<p>
17314     * When the system calls this method, it passes a
17315     * {@link android.view.DragEvent} object. A call to
17316     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
17317     * in DragEvent. The method uses these to determine what is happening in the drag and drop
17318     * operation.
17319     * @param event The {@link android.view.DragEvent} sent by the system.
17320     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
17321     * in DragEvent, indicating the type of drag event represented by this object.
17322     * @return {@code true} if the method was successful, otherwise {@code false}.
17323     * <p>
17324     *  The method should return {@code true} in response to an action type of
17325     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
17326     *  operation.
17327     * </p>
17328     * <p>
17329     *  The method should also return {@code true} in response to an action type of
17330     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
17331     *  {@code false} if it didn't.
17332     * </p>
17333     */
17334    public boolean onDragEvent(DragEvent event) {
17335        return false;
17336    }
17337
17338    /**
17339     * Detects if this View is enabled and has a drag event listener.
17340     * If both are true, then it calls the drag event listener with the
17341     * {@link android.view.DragEvent} it received. If the drag event listener returns
17342     * {@code true}, then dispatchDragEvent() returns {@code true}.
17343     * <p>
17344     * For all other cases, the method calls the
17345     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
17346     * method and returns its result.
17347     * </p>
17348     * <p>
17349     * This ensures that a drag event is always consumed, even if the View does not have a drag
17350     * event listener. However, if the View has a listener and the listener returns true, then
17351     * onDragEvent() is not called.
17352     * </p>
17353     */
17354    public boolean dispatchDragEvent(DragEvent event) {
17355        ListenerInfo li = mListenerInfo;
17356        //noinspection SimplifiableIfStatement
17357        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
17358                && li.mOnDragListener.onDrag(this, event)) {
17359            return true;
17360        }
17361        return onDragEvent(event);
17362    }
17363
17364    boolean canAcceptDrag() {
17365        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
17366    }
17367
17368    /**
17369     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
17370     * it is ever exposed at all.
17371     * @hide
17372     */
17373    public void onCloseSystemDialogs(String reason) {
17374    }
17375
17376    /**
17377     * Given a Drawable whose bounds have been set to draw into this view,
17378     * update a Region being computed for
17379     * {@link #gatherTransparentRegion(android.graphics.Region)} so
17380     * that any non-transparent parts of the Drawable are removed from the
17381     * given transparent region.
17382     *
17383     * @param dr The Drawable whose transparency is to be applied to the region.
17384     * @param region A Region holding the current transparency information,
17385     * where any parts of the region that are set are considered to be
17386     * transparent.  On return, this region will be modified to have the
17387     * transparency information reduced by the corresponding parts of the
17388     * Drawable that are not transparent.
17389     * {@hide}
17390     */
17391    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
17392        if (DBG) {
17393            Log.i("View", "Getting transparent region for: " + this);
17394        }
17395        final Region r = dr.getTransparentRegion();
17396        final Rect db = dr.getBounds();
17397        final AttachInfo attachInfo = mAttachInfo;
17398        if (r != null && attachInfo != null) {
17399            final int w = getRight()-getLeft();
17400            final int h = getBottom()-getTop();
17401            if (db.left > 0) {
17402                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
17403                r.op(0, 0, db.left, h, Region.Op.UNION);
17404            }
17405            if (db.right < w) {
17406                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
17407                r.op(db.right, 0, w, h, Region.Op.UNION);
17408            }
17409            if (db.top > 0) {
17410                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
17411                r.op(0, 0, w, db.top, Region.Op.UNION);
17412            }
17413            if (db.bottom < h) {
17414                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
17415                r.op(0, db.bottom, w, h, Region.Op.UNION);
17416            }
17417            final int[] location = attachInfo.mTransparentLocation;
17418            getLocationInWindow(location);
17419            r.translate(location[0], location[1]);
17420            region.op(r, Region.Op.INTERSECT);
17421        } else {
17422            region.op(db, Region.Op.DIFFERENCE);
17423        }
17424    }
17425
17426    private void checkForLongClick(int delayOffset) {
17427        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
17428            mHasPerformedLongPress = false;
17429
17430            if (mPendingCheckForLongPress == null) {
17431                mPendingCheckForLongPress = new CheckForLongPress();
17432            }
17433            mPendingCheckForLongPress.rememberWindowAttachCount();
17434            postDelayed(mPendingCheckForLongPress,
17435                    ViewConfiguration.getLongPressTimeout() - delayOffset);
17436        }
17437    }
17438
17439    /**
17440     * Inflate a view from an XML resource.  This convenience method wraps the {@link
17441     * LayoutInflater} class, which provides a full range of options for view inflation.
17442     *
17443     * @param context The Context object for your activity or application.
17444     * @param resource The resource ID to inflate
17445     * @param root A view group that will be the parent.  Used to properly inflate the
17446     * layout_* parameters.
17447     * @see LayoutInflater
17448     */
17449    public static View inflate(Context context, int resource, ViewGroup root) {
17450        LayoutInflater factory = LayoutInflater.from(context);
17451        return factory.inflate(resource, root);
17452    }
17453
17454    /**
17455     * Scroll the view with standard behavior for scrolling beyond the normal
17456     * content boundaries. Views that call this method should override
17457     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
17458     * results of an over-scroll operation.
17459     *
17460     * Views can use this method to handle any touch or fling-based scrolling.
17461     *
17462     * @param deltaX Change in X in pixels
17463     * @param deltaY Change in Y in pixels
17464     * @param scrollX Current X scroll value in pixels before applying deltaX
17465     * @param scrollY Current Y scroll value in pixels before applying deltaY
17466     * @param scrollRangeX Maximum content scroll range along the X axis
17467     * @param scrollRangeY Maximum content scroll range along the Y axis
17468     * @param maxOverScrollX Number of pixels to overscroll by in either direction
17469     *          along the X axis.
17470     * @param maxOverScrollY Number of pixels to overscroll by in either direction
17471     *          along the Y axis.
17472     * @param isTouchEvent true if this scroll operation is the result of a touch event.
17473     * @return true if scrolling was clamped to an over-scroll boundary along either
17474     *          axis, false otherwise.
17475     */
17476    @SuppressWarnings({"UnusedParameters"})
17477    protected boolean overScrollBy(int deltaX, int deltaY,
17478            int scrollX, int scrollY,
17479            int scrollRangeX, int scrollRangeY,
17480            int maxOverScrollX, int maxOverScrollY,
17481            boolean isTouchEvent) {
17482        final int overScrollMode = mOverScrollMode;
17483        final boolean canScrollHorizontal =
17484                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
17485        final boolean canScrollVertical =
17486                computeVerticalScrollRange() > computeVerticalScrollExtent();
17487        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
17488                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
17489        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
17490                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
17491
17492        int newScrollX = scrollX + deltaX;
17493        if (!overScrollHorizontal) {
17494            maxOverScrollX = 0;
17495        }
17496
17497        int newScrollY = scrollY + deltaY;
17498        if (!overScrollVertical) {
17499            maxOverScrollY = 0;
17500        }
17501
17502        // Clamp values if at the limits and record
17503        final int left = -maxOverScrollX;
17504        final int right = maxOverScrollX + scrollRangeX;
17505        final int top = -maxOverScrollY;
17506        final int bottom = maxOverScrollY + scrollRangeY;
17507
17508        boolean clampedX = false;
17509        if (newScrollX > right) {
17510            newScrollX = right;
17511            clampedX = true;
17512        } else if (newScrollX < left) {
17513            newScrollX = left;
17514            clampedX = true;
17515        }
17516
17517        boolean clampedY = false;
17518        if (newScrollY > bottom) {
17519            newScrollY = bottom;
17520            clampedY = true;
17521        } else if (newScrollY < top) {
17522            newScrollY = top;
17523            clampedY = true;
17524        }
17525
17526        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
17527
17528        return clampedX || clampedY;
17529    }
17530
17531    /**
17532     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
17533     * respond to the results of an over-scroll operation.
17534     *
17535     * @param scrollX New X scroll value in pixels
17536     * @param scrollY New Y scroll value in pixels
17537     * @param clampedX True if scrollX was clamped to an over-scroll boundary
17538     * @param clampedY True if scrollY was clamped to an over-scroll boundary
17539     */
17540    protected void onOverScrolled(int scrollX, int scrollY,
17541            boolean clampedX, boolean clampedY) {
17542        // Intentionally empty.
17543    }
17544
17545    /**
17546     * Returns the over-scroll mode for this view. The result will be
17547     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
17548     * (allow over-scrolling only if the view content is larger than the container),
17549     * or {@link #OVER_SCROLL_NEVER}.
17550     *
17551     * @return This view's over-scroll mode.
17552     */
17553    public int getOverScrollMode() {
17554        return mOverScrollMode;
17555    }
17556
17557    /**
17558     * Set the over-scroll mode for this view. Valid over-scroll modes are
17559     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
17560     * (allow over-scrolling only if the view content is larger than the container),
17561     * or {@link #OVER_SCROLL_NEVER}.
17562     *
17563     * Setting the over-scroll mode of a view will have an effect only if the
17564     * view is capable of scrolling.
17565     *
17566     * @param overScrollMode The new over-scroll mode for this view.
17567     */
17568    public void setOverScrollMode(int overScrollMode) {
17569        if (overScrollMode != OVER_SCROLL_ALWAYS &&
17570                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
17571                overScrollMode != OVER_SCROLL_NEVER) {
17572            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
17573        }
17574        mOverScrollMode = overScrollMode;
17575    }
17576
17577    /**
17578     * Gets a scale factor that determines the distance the view should scroll
17579     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
17580     * @return The vertical scroll scale factor.
17581     * @hide
17582     */
17583    protected float getVerticalScrollFactor() {
17584        if (mVerticalScrollFactor == 0) {
17585            TypedValue outValue = new TypedValue();
17586            if (!mContext.getTheme().resolveAttribute(
17587                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
17588                throw new IllegalStateException(
17589                        "Expected theme to define listPreferredItemHeight.");
17590            }
17591            mVerticalScrollFactor = outValue.getDimension(
17592                    mContext.getResources().getDisplayMetrics());
17593        }
17594        return mVerticalScrollFactor;
17595    }
17596
17597    /**
17598     * Gets a scale factor that determines the distance the view should scroll
17599     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
17600     * @return The horizontal scroll scale factor.
17601     * @hide
17602     */
17603    protected float getHorizontalScrollFactor() {
17604        // TODO: Should use something else.
17605        return getVerticalScrollFactor();
17606    }
17607
17608    /**
17609     * Return the value specifying the text direction or policy that was set with
17610     * {@link #setTextDirection(int)}.
17611     *
17612     * @return the defined text direction. It can be one of:
17613     *
17614     * {@link #TEXT_DIRECTION_INHERIT},
17615     * {@link #TEXT_DIRECTION_FIRST_STRONG}
17616     * {@link #TEXT_DIRECTION_ANY_RTL},
17617     * {@link #TEXT_DIRECTION_LTR},
17618     * {@link #TEXT_DIRECTION_RTL},
17619     * {@link #TEXT_DIRECTION_LOCALE}
17620     *
17621     * @attr ref android.R.styleable#View_textDirection
17622     *
17623     * @hide
17624     */
17625    @ViewDebug.ExportedProperty(category = "text", mapping = {
17626            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
17627            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
17628            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
17629            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
17630            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
17631            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
17632    })
17633    public int getRawTextDirection() {
17634        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
17635    }
17636
17637    /**
17638     * Set the text direction.
17639     *
17640     * @param textDirection the direction to set. Should be one of:
17641     *
17642     * {@link #TEXT_DIRECTION_INHERIT},
17643     * {@link #TEXT_DIRECTION_FIRST_STRONG}
17644     * {@link #TEXT_DIRECTION_ANY_RTL},
17645     * {@link #TEXT_DIRECTION_LTR},
17646     * {@link #TEXT_DIRECTION_RTL},
17647     * {@link #TEXT_DIRECTION_LOCALE}
17648     *
17649     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
17650     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
17651     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
17652     *
17653     * @attr ref android.R.styleable#View_textDirection
17654     */
17655    public void setTextDirection(int textDirection) {
17656        if (getRawTextDirection() != textDirection) {
17657            // Reset the current text direction and the resolved one
17658            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
17659            resetResolvedTextDirection();
17660            // Set the new text direction
17661            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
17662            // Do resolution
17663            resolveTextDirection();
17664            // Notify change
17665            onRtlPropertiesChanged(getLayoutDirection());
17666            // Refresh
17667            requestLayout();
17668            invalidate(true);
17669        }
17670    }
17671
17672    /**
17673     * Return the resolved text direction.
17674     *
17675     * @return the resolved text direction. Returns one of:
17676     *
17677     * {@link #TEXT_DIRECTION_FIRST_STRONG}
17678     * {@link #TEXT_DIRECTION_ANY_RTL},
17679     * {@link #TEXT_DIRECTION_LTR},
17680     * {@link #TEXT_DIRECTION_RTL},
17681     * {@link #TEXT_DIRECTION_LOCALE}
17682     *
17683     * @attr ref android.R.styleable#View_textDirection
17684     */
17685    @ViewDebug.ExportedProperty(category = "text", mapping = {
17686            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
17687            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
17688            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
17689            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
17690            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
17691            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
17692    })
17693    public int getTextDirection() {
17694        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
17695    }
17696
17697    /**
17698     * Resolve the text direction.
17699     *
17700     * @return true if resolution has been done, false otherwise.
17701     *
17702     * @hide
17703     */
17704    public boolean resolveTextDirection() {
17705        // Reset any previous text direction resolution
17706        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
17707
17708        if (hasRtlSupport()) {
17709            // Set resolved text direction flag depending on text direction flag
17710            final int textDirection = getRawTextDirection();
17711            switch(textDirection) {
17712                case TEXT_DIRECTION_INHERIT:
17713                    if (!canResolveTextDirection()) {
17714                        // We cannot do the resolution if there is no parent, so use the default one
17715                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17716                        // Resolution will need to happen again later
17717                        return false;
17718                    }
17719
17720                    // Parent has not yet resolved, so we still return the default
17721                    try {
17722                        if (!mParent.isTextDirectionResolved()) {
17723                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17724                            // Resolution will need to happen again later
17725                            return false;
17726                        }
17727                    } catch (AbstractMethodError e) {
17728                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
17729                                " does not fully implement ViewParent", e);
17730                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED |
17731                                PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17732                        return true;
17733                    }
17734
17735                    // Set current resolved direction to the same value as the parent's one
17736                    int parentResolvedDirection;
17737                    try {
17738                        parentResolvedDirection = mParent.getTextDirection();
17739                    } catch (AbstractMethodError e) {
17740                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
17741                                " does not fully implement ViewParent", e);
17742                        parentResolvedDirection = TEXT_DIRECTION_LTR;
17743                    }
17744                    switch (parentResolvedDirection) {
17745                        case TEXT_DIRECTION_FIRST_STRONG:
17746                        case TEXT_DIRECTION_ANY_RTL:
17747                        case TEXT_DIRECTION_LTR:
17748                        case TEXT_DIRECTION_RTL:
17749                        case TEXT_DIRECTION_LOCALE:
17750                            mPrivateFlags2 |=
17751                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
17752                            break;
17753                        default:
17754                            // Default resolved direction is "first strong" heuristic
17755                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17756                    }
17757                    break;
17758                case TEXT_DIRECTION_FIRST_STRONG:
17759                case TEXT_DIRECTION_ANY_RTL:
17760                case TEXT_DIRECTION_LTR:
17761                case TEXT_DIRECTION_RTL:
17762                case TEXT_DIRECTION_LOCALE:
17763                    // Resolved direction is the same as text direction
17764                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
17765                    break;
17766                default:
17767                    // Default resolved direction is "first strong" heuristic
17768                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17769            }
17770        } else {
17771            // Default resolved direction is "first strong" heuristic
17772            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17773        }
17774
17775        // Set to resolved
17776        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
17777        return true;
17778    }
17779
17780    /**
17781     * Check if text direction resolution can be done.
17782     *
17783     * @return true if text direction resolution can be done otherwise return false.
17784     */
17785    public boolean canResolveTextDirection() {
17786        switch (getRawTextDirection()) {
17787            case TEXT_DIRECTION_INHERIT:
17788                if (mParent != null) {
17789                    try {
17790                        return mParent.canResolveTextDirection();
17791                    } catch (AbstractMethodError e) {
17792                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
17793                                " does not fully implement ViewParent", e);
17794                    }
17795                }
17796                return false;
17797
17798            default:
17799                return true;
17800        }
17801    }
17802
17803    /**
17804     * Reset resolved text direction. Text direction will be resolved during a call to
17805     * {@link #onMeasure(int, int)}.
17806     *
17807     * @hide
17808     */
17809    public void resetResolvedTextDirection() {
17810        // Reset any previous text direction resolution
17811        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
17812        // Set to default value
17813        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17814    }
17815
17816    /**
17817     * @return true if text direction is inherited.
17818     *
17819     * @hide
17820     */
17821    public boolean isTextDirectionInherited() {
17822        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
17823    }
17824
17825    /**
17826     * @return true if text direction is resolved.
17827     */
17828    public boolean isTextDirectionResolved() {
17829        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
17830    }
17831
17832    /**
17833     * Return the value specifying the text alignment or policy that was set with
17834     * {@link #setTextAlignment(int)}.
17835     *
17836     * @return the defined text alignment. It can be one of:
17837     *
17838     * {@link #TEXT_ALIGNMENT_INHERIT},
17839     * {@link #TEXT_ALIGNMENT_GRAVITY},
17840     * {@link #TEXT_ALIGNMENT_CENTER},
17841     * {@link #TEXT_ALIGNMENT_TEXT_START},
17842     * {@link #TEXT_ALIGNMENT_TEXT_END},
17843     * {@link #TEXT_ALIGNMENT_VIEW_START},
17844     * {@link #TEXT_ALIGNMENT_VIEW_END}
17845     *
17846     * @attr ref android.R.styleable#View_textAlignment
17847     *
17848     * @hide
17849     */
17850    @ViewDebug.ExportedProperty(category = "text", mapping = {
17851            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
17852            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
17853            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
17854            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
17855            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
17856            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
17857            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
17858    })
17859    public int getRawTextAlignment() {
17860        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
17861    }
17862
17863    /**
17864     * Set the text alignment.
17865     *
17866     * @param textAlignment The text alignment to set. Should be one of
17867     *
17868     * {@link #TEXT_ALIGNMENT_INHERIT},
17869     * {@link #TEXT_ALIGNMENT_GRAVITY},
17870     * {@link #TEXT_ALIGNMENT_CENTER},
17871     * {@link #TEXT_ALIGNMENT_TEXT_START},
17872     * {@link #TEXT_ALIGNMENT_TEXT_END},
17873     * {@link #TEXT_ALIGNMENT_VIEW_START},
17874     * {@link #TEXT_ALIGNMENT_VIEW_END}
17875     *
17876     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
17877     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
17878     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
17879     *
17880     * @attr ref android.R.styleable#View_textAlignment
17881     */
17882    public void setTextAlignment(int textAlignment) {
17883        if (textAlignment != getRawTextAlignment()) {
17884            // Reset the current and resolved text alignment
17885            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
17886            resetResolvedTextAlignment();
17887            // Set the new text alignment
17888            mPrivateFlags2 |=
17889                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
17890            // Do resolution
17891            resolveTextAlignment();
17892            // Notify change
17893            onRtlPropertiesChanged(getLayoutDirection());
17894            // Refresh
17895            requestLayout();
17896            invalidate(true);
17897        }
17898    }
17899
17900    /**
17901     * Return the resolved text alignment.
17902     *
17903     * @return the resolved text alignment. Returns one of:
17904     *
17905     * {@link #TEXT_ALIGNMENT_GRAVITY},
17906     * {@link #TEXT_ALIGNMENT_CENTER},
17907     * {@link #TEXT_ALIGNMENT_TEXT_START},
17908     * {@link #TEXT_ALIGNMENT_TEXT_END},
17909     * {@link #TEXT_ALIGNMENT_VIEW_START},
17910     * {@link #TEXT_ALIGNMENT_VIEW_END}
17911     *
17912     * @attr ref android.R.styleable#View_textAlignment
17913     */
17914    @ViewDebug.ExportedProperty(category = "text", mapping = {
17915            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
17916            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
17917            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
17918            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
17919            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
17920            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
17921            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
17922    })
17923    public int getTextAlignment() {
17924        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
17925                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
17926    }
17927
17928    /**
17929     * Resolve the text alignment.
17930     *
17931     * @return true if resolution has been done, false otherwise.
17932     *
17933     * @hide
17934     */
17935    public boolean resolveTextAlignment() {
17936        // Reset any previous text alignment resolution
17937        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
17938
17939        if (hasRtlSupport()) {
17940            // Set resolved text alignment flag depending on text alignment flag
17941            final int textAlignment = getRawTextAlignment();
17942            switch (textAlignment) {
17943                case TEXT_ALIGNMENT_INHERIT:
17944                    // Check if we can resolve the text alignment
17945                    if (!canResolveTextAlignment()) {
17946                        // We cannot do the resolution if there is no parent so use the default
17947                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17948                        // Resolution will need to happen again later
17949                        return false;
17950                    }
17951
17952                    // Parent has not yet resolved, so we still return the default
17953                    try {
17954                        if (!mParent.isTextAlignmentResolved()) {
17955                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17956                            // Resolution will need to happen again later
17957                            return false;
17958                        }
17959                    } catch (AbstractMethodError e) {
17960                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
17961                                " does not fully implement ViewParent", e);
17962                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED |
17963                                PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17964                        return true;
17965                    }
17966
17967                    int parentResolvedTextAlignment;
17968                    try {
17969                        parentResolvedTextAlignment = mParent.getTextAlignment();
17970                    } catch (AbstractMethodError e) {
17971                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
17972                                " does not fully implement ViewParent", e);
17973                        parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY;
17974                    }
17975                    switch (parentResolvedTextAlignment) {
17976                        case TEXT_ALIGNMENT_GRAVITY:
17977                        case TEXT_ALIGNMENT_TEXT_START:
17978                        case TEXT_ALIGNMENT_TEXT_END:
17979                        case TEXT_ALIGNMENT_CENTER:
17980                        case TEXT_ALIGNMENT_VIEW_START:
17981                        case TEXT_ALIGNMENT_VIEW_END:
17982                            // Resolved text alignment is the same as the parent resolved
17983                            // text alignment
17984                            mPrivateFlags2 |=
17985                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
17986                            break;
17987                        default:
17988                            // Use default resolved text alignment
17989                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17990                    }
17991                    break;
17992                case TEXT_ALIGNMENT_GRAVITY:
17993                case TEXT_ALIGNMENT_TEXT_START:
17994                case TEXT_ALIGNMENT_TEXT_END:
17995                case TEXT_ALIGNMENT_CENTER:
17996                case TEXT_ALIGNMENT_VIEW_START:
17997                case TEXT_ALIGNMENT_VIEW_END:
17998                    // Resolved text alignment is the same as text alignment
17999                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
18000                    break;
18001                default:
18002                    // Use default resolved text alignment
18003                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18004            }
18005        } else {
18006            // Use default resolved text alignment
18007            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18008        }
18009
18010        // Set the resolved
18011        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
18012        return true;
18013    }
18014
18015    /**
18016     * Check if text alignment resolution can be done.
18017     *
18018     * @return true if text alignment resolution can be done otherwise return false.
18019     */
18020    public boolean canResolveTextAlignment() {
18021        switch (getRawTextAlignment()) {
18022            case TEXT_DIRECTION_INHERIT:
18023                if (mParent != null) {
18024                    try {
18025                        return mParent.canResolveTextAlignment();
18026                    } catch (AbstractMethodError e) {
18027                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18028                                " does not fully implement ViewParent", e);
18029                    }
18030                }
18031                return false;
18032
18033            default:
18034                return true;
18035        }
18036    }
18037
18038    /**
18039     * Reset resolved text alignment. Text alignment will be resolved during a call to
18040     * {@link #onMeasure(int, int)}.
18041     *
18042     * @hide
18043     */
18044    public void resetResolvedTextAlignment() {
18045        // Reset any previous text alignment resolution
18046        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
18047        // Set to default
18048        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
18049    }
18050
18051    /**
18052     * @return true if text alignment is inherited.
18053     *
18054     * @hide
18055     */
18056    public boolean isTextAlignmentInherited() {
18057        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
18058    }
18059
18060    /**
18061     * @return true if text alignment is resolved.
18062     */
18063    public boolean isTextAlignmentResolved() {
18064        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
18065    }
18066
18067    /**
18068     * Generate a value suitable for use in {@link #setId(int)}.
18069     * This value will not collide with ID values generated at build time by aapt for R.id.
18070     *
18071     * @return a generated ID value
18072     */
18073    public static int generateViewId() {
18074        for (;;) {
18075            final int result = sNextGeneratedId.get();
18076            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
18077            int newValue = result + 1;
18078            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
18079            if (sNextGeneratedId.compareAndSet(result, newValue)) {
18080                return result;
18081            }
18082        }
18083    }
18084
18085    //
18086    // Properties
18087    //
18088    /**
18089     * A Property wrapper around the <code>alpha</code> functionality handled by the
18090     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
18091     */
18092    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
18093        @Override
18094        public void setValue(View object, float value) {
18095            object.setAlpha(value);
18096        }
18097
18098        @Override
18099        public Float get(View object) {
18100            return object.getAlpha();
18101        }
18102    };
18103
18104    /**
18105     * A Property wrapper around the <code>translationX</code> functionality handled by the
18106     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
18107     */
18108    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
18109        @Override
18110        public void setValue(View object, float value) {
18111            object.setTranslationX(value);
18112        }
18113
18114                @Override
18115        public Float get(View object) {
18116            return object.getTranslationX();
18117        }
18118    };
18119
18120    /**
18121     * A Property wrapper around the <code>translationY</code> functionality handled by the
18122     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
18123     */
18124    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
18125        @Override
18126        public void setValue(View object, float value) {
18127            object.setTranslationY(value);
18128        }
18129
18130        @Override
18131        public Float get(View object) {
18132            return object.getTranslationY();
18133        }
18134    };
18135
18136    /**
18137     * A Property wrapper around the <code>x</code> functionality handled by the
18138     * {@link View#setX(float)} and {@link View#getX()} methods.
18139     */
18140    public static final Property<View, Float> X = new FloatProperty<View>("x") {
18141        @Override
18142        public void setValue(View object, float value) {
18143            object.setX(value);
18144        }
18145
18146        @Override
18147        public Float get(View object) {
18148            return object.getX();
18149        }
18150    };
18151
18152    /**
18153     * A Property wrapper around the <code>y</code> functionality handled by the
18154     * {@link View#setY(float)} and {@link View#getY()} methods.
18155     */
18156    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
18157        @Override
18158        public void setValue(View object, float value) {
18159            object.setY(value);
18160        }
18161
18162        @Override
18163        public Float get(View object) {
18164            return object.getY();
18165        }
18166    };
18167
18168    /**
18169     * A Property wrapper around the <code>rotation</code> functionality handled by the
18170     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
18171     */
18172    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
18173        @Override
18174        public void setValue(View object, float value) {
18175            object.setRotation(value);
18176        }
18177
18178        @Override
18179        public Float get(View object) {
18180            return object.getRotation();
18181        }
18182    };
18183
18184    /**
18185     * A Property wrapper around the <code>rotationX</code> functionality handled by the
18186     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
18187     */
18188    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
18189        @Override
18190        public void setValue(View object, float value) {
18191            object.setRotationX(value);
18192        }
18193
18194        @Override
18195        public Float get(View object) {
18196            return object.getRotationX();
18197        }
18198    };
18199
18200    /**
18201     * A Property wrapper around the <code>rotationY</code> functionality handled by the
18202     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
18203     */
18204    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
18205        @Override
18206        public void setValue(View object, float value) {
18207            object.setRotationY(value);
18208        }
18209
18210        @Override
18211        public Float get(View object) {
18212            return object.getRotationY();
18213        }
18214    };
18215
18216    /**
18217     * A Property wrapper around the <code>scaleX</code> functionality handled by the
18218     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
18219     */
18220    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
18221        @Override
18222        public void setValue(View object, float value) {
18223            object.setScaleX(value);
18224        }
18225
18226        @Override
18227        public Float get(View object) {
18228            return object.getScaleX();
18229        }
18230    };
18231
18232    /**
18233     * A Property wrapper around the <code>scaleY</code> functionality handled by the
18234     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
18235     */
18236    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
18237        @Override
18238        public void setValue(View object, float value) {
18239            object.setScaleY(value);
18240        }
18241
18242        @Override
18243        public Float get(View object) {
18244            return object.getScaleY();
18245        }
18246    };
18247
18248    /**
18249     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
18250     * Each MeasureSpec represents a requirement for either the width or the height.
18251     * A MeasureSpec is comprised of a size and a mode. There are three possible
18252     * modes:
18253     * <dl>
18254     * <dt>UNSPECIFIED</dt>
18255     * <dd>
18256     * The parent has not imposed any constraint on the child. It can be whatever size
18257     * it wants.
18258     * </dd>
18259     *
18260     * <dt>EXACTLY</dt>
18261     * <dd>
18262     * The parent has determined an exact size for the child. The child is going to be
18263     * given those bounds regardless of how big it wants to be.
18264     * </dd>
18265     *
18266     * <dt>AT_MOST</dt>
18267     * <dd>
18268     * The child can be as large as it wants up to the specified size.
18269     * </dd>
18270     * </dl>
18271     *
18272     * MeasureSpecs are implemented as ints to reduce object allocation. This class
18273     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
18274     */
18275    public static class MeasureSpec {
18276        private static final int MODE_SHIFT = 30;
18277        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
18278
18279        /**
18280         * Measure specification mode: The parent has not imposed any constraint
18281         * on the child. It can be whatever size it wants.
18282         */
18283        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
18284
18285        /**
18286         * Measure specification mode: The parent has determined an exact size
18287         * for the child. The child is going to be given those bounds regardless
18288         * of how big it wants to be.
18289         */
18290        public static final int EXACTLY     = 1 << MODE_SHIFT;
18291
18292        /**
18293         * Measure specification mode: The child can be as large as it wants up
18294         * to the specified size.
18295         */
18296        public static final int AT_MOST     = 2 << MODE_SHIFT;
18297
18298        /**
18299         * Creates a measure specification based on the supplied size and mode.
18300         *
18301         * The mode must always be one of the following:
18302         * <ul>
18303         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
18304         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
18305         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
18306         * </ul>
18307         *
18308         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
18309         * implementation was such that the order of arguments did not matter
18310         * and overflow in either value could impact the resulting MeasureSpec.
18311         * {@link android.widget.RelativeLayout} was affected by this bug.
18312         * Apps targeting API levels greater than 17 will get the fixed, more strict
18313         * behavior.</p>
18314         *
18315         * @param size the size of the measure specification
18316         * @param mode the mode of the measure specification
18317         * @return the measure specification based on size and mode
18318         */
18319        public static int makeMeasureSpec(int size, int mode) {
18320            if (sUseBrokenMakeMeasureSpec) {
18321                return size + mode;
18322            } else {
18323                return (size & ~MODE_MASK) | (mode & MODE_MASK);
18324            }
18325        }
18326
18327        /**
18328         * Extracts the mode from the supplied measure specification.
18329         *
18330         * @param measureSpec the measure specification to extract the mode from
18331         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
18332         *         {@link android.view.View.MeasureSpec#AT_MOST} or
18333         *         {@link android.view.View.MeasureSpec#EXACTLY}
18334         */
18335        public static int getMode(int measureSpec) {
18336            return (measureSpec & MODE_MASK);
18337        }
18338
18339        /**
18340         * Extracts the size from the supplied measure specification.
18341         *
18342         * @param measureSpec the measure specification to extract the size from
18343         * @return the size in pixels defined in the supplied measure specification
18344         */
18345        public static int getSize(int measureSpec) {
18346            return (measureSpec & ~MODE_MASK);
18347        }
18348
18349        static int adjust(int measureSpec, int delta) {
18350            return makeMeasureSpec(getSize(measureSpec + delta), getMode(measureSpec));
18351        }
18352
18353        /**
18354         * Returns a String representation of the specified measure
18355         * specification.
18356         *
18357         * @param measureSpec the measure specification to convert to a String
18358         * @return a String with the following format: "MeasureSpec: MODE SIZE"
18359         */
18360        public static String toString(int measureSpec) {
18361            int mode = getMode(measureSpec);
18362            int size = getSize(measureSpec);
18363
18364            StringBuilder sb = new StringBuilder("MeasureSpec: ");
18365
18366            if (mode == UNSPECIFIED)
18367                sb.append("UNSPECIFIED ");
18368            else if (mode == EXACTLY)
18369                sb.append("EXACTLY ");
18370            else if (mode == AT_MOST)
18371                sb.append("AT_MOST ");
18372            else
18373                sb.append(mode).append(" ");
18374
18375            sb.append(size);
18376            return sb.toString();
18377        }
18378    }
18379
18380    class CheckForLongPress implements Runnable {
18381
18382        private int mOriginalWindowAttachCount;
18383
18384        public void run() {
18385            if (isPressed() && (mParent != null)
18386                    && mOriginalWindowAttachCount == mWindowAttachCount) {
18387                if (performLongClick()) {
18388                    mHasPerformedLongPress = true;
18389                }
18390            }
18391        }
18392
18393        public void rememberWindowAttachCount() {
18394            mOriginalWindowAttachCount = mWindowAttachCount;
18395        }
18396    }
18397
18398    private final class CheckForTap implements Runnable {
18399        public void run() {
18400            mPrivateFlags &= ~PFLAG_PREPRESSED;
18401            setPressed(true);
18402            checkForLongClick(ViewConfiguration.getTapTimeout());
18403        }
18404    }
18405
18406    private final class PerformClick implements Runnable {
18407        public void run() {
18408            performClick();
18409        }
18410    }
18411
18412    /** @hide */
18413    public void hackTurnOffWindowResizeAnim(boolean off) {
18414        mAttachInfo.mTurnOffWindowResizeAnim = off;
18415    }
18416
18417    /**
18418     * This method returns a ViewPropertyAnimator object, which can be used to animate
18419     * specific properties on this View.
18420     *
18421     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
18422     */
18423    public ViewPropertyAnimator animate() {
18424        if (mAnimator == null) {
18425            mAnimator = new ViewPropertyAnimator(this);
18426        }
18427        return mAnimator;
18428    }
18429
18430    /**
18431     * Interface definition for a callback to be invoked when a hardware key event is
18432     * dispatched to this view. The callback will be invoked before the key event is
18433     * given to the view. This is only useful for hardware keyboards; a software input
18434     * method has no obligation to trigger this listener.
18435     */
18436    public interface OnKeyListener {
18437        /**
18438         * Called when a hardware key is dispatched to a view. This allows listeners to
18439         * get a chance to respond before the target view.
18440         * <p>Key presses in software keyboards will generally NOT trigger this method,
18441         * although some may elect to do so in some situations. Do not assume a
18442         * software input method has to be key-based; even if it is, it may use key presses
18443         * in a different way than you expect, so there is no way to reliably catch soft
18444         * input key presses.
18445         *
18446         * @param v The view the key has been dispatched to.
18447         * @param keyCode The code for the physical key that was pressed
18448         * @param event The KeyEvent object containing full information about
18449         *        the event.
18450         * @return True if the listener has consumed the event, false otherwise.
18451         */
18452        boolean onKey(View v, int keyCode, KeyEvent event);
18453    }
18454
18455    /**
18456     * Interface definition for a callback to be invoked when a touch event is
18457     * dispatched to this view. The callback will be invoked before the touch
18458     * event is given to the view.
18459     */
18460    public interface OnTouchListener {
18461        /**
18462         * Called when a touch event is dispatched to a view. This allows listeners to
18463         * get a chance to respond before the target view.
18464         *
18465         * @param v The view the touch event has been dispatched to.
18466         * @param event The MotionEvent object containing full information about
18467         *        the event.
18468         * @return True if the listener has consumed the event, false otherwise.
18469         */
18470        boolean onTouch(View v, MotionEvent event);
18471    }
18472
18473    /**
18474     * Interface definition for a callback to be invoked when a hover event is
18475     * dispatched to this view. The callback will be invoked before the hover
18476     * event is given to the view.
18477     */
18478    public interface OnHoverListener {
18479        /**
18480         * Called when a hover event is dispatched to a view. This allows listeners to
18481         * get a chance to respond before the target view.
18482         *
18483         * @param v The view the hover event has been dispatched to.
18484         * @param event The MotionEvent object containing full information about
18485         *        the event.
18486         * @return True if the listener has consumed the event, false otherwise.
18487         */
18488        boolean onHover(View v, MotionEvent event);
18489    }
18490
18491    /**
18492     * Interface definition for a callback to be invoked when a generic motion event is
18493     * dispatched to this view. The callback will be invoked before the generic motion
18494     * event is given to the view.
18495     */
18496    public interface OnGenericMotionListener {
18497        /**
18498         * Called when a generic motion event is dispatched to a view. This allows listeners to
18499         * get a chance to respond before the target view.
18500         *
18501         * @param v The view the generic motion event has been dispatched to.
18502         * @param event The MotionEvent object containing full information about
18503         *        the event.
18504         * @return True if the listener has consumed the event, false otherwise.
18505         */
18506        boolean onGenericMotion(View v, MotionEvent event);
18507    }
18508
18509    /**
18510     * Interface definition for a callback to be invoked when a view has been clicked and held.
18511     */
18512    public interface OnLongClickListener {
18513        /**
18514         * Called when a view has been clicked and held.
18515         *
18516         * @param v The view that was clicked and held.
18517         *
18518         * @return true if the callback consumed the long click, false otherwise.
18519         */
18520        boolean onLongClick(View v);
18521    }
18522
18523    /**
18524     * Interface definition for a callback to be invoked when a drag is being dispatched
18525     * to this view.  The callback will be invoked before the hosting view's own
18526     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
18527     * onDrag(event) behavior, it should return 'false' from this callback.
18528     *
18529     * <div class="special reference">
18530     * <h3>Developer Guides</h3>
18531     * <p>For a guide to implementing drag and drop features, read the
18532     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
18533     * </div>
18534     */
18535    public interface OnDragListener {
18536        /**
18537         * Called when a drag event is dispatched to a view. This allows listeners
18538         * to get a chance to override base View behavior.
18539         *
18540         * @param v The View that received the drag event.
18541         * @param event The {@link android.view.DragEvent} object for the drag event.
18542         * @return {@code true} if the drag event was handled successfully, or {@code false}
18543         * if the drag event was not handled. Note that {@code false} will trigger the View
18544         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
18545         */
18546        boolean onDrag(View v, DragEvent event);
18547    }
18548
18549    /**
18550     * Interface definition for a callback to be invoked when the focus state of
18551     * a view changed.
18552     */
18553    public interface OnFocusChangeListener {
18554        /**
18555         * Called when the focus state of a view has changed.
18556         *
18557         * @param v The view whose state has changed.
18558         * @param hasFocus The new focus state of v.
18559         */
18560        void onFocusChange(View v, boolean hasFocus);
18561    }
18562
18563    /**
18564     * Interface definition for a callback to be invoked when a view is clicked.
18565     */
18566    public interface OnClickListener {
18567        /**
18568         * Called when a view has been clicked.
18569         *
18570         * @param v The view that was clicked.
18571         */
18572        void onClick(View v);
18573    }
18574
18575    /**
18576     * Interface definition for a callback to be invoked when the context menu
18577     * for this view is being built.
18578     */
18579    public interface OnCreateContextMenuListener {
18580        /**
18581         * Called when the context menu for this view is being built. It is not
18582         * safe to hold onto the menu after this method returns.
18583         *
18584         * @param menu The context menu that is being built
18585         * @param v The view for which the context menu is being built
18586         * @param menuInfo Extra information about the item for which the
18587         *            context menu should be shown. This information will vary
18588         *            depending on the class of v.
18589         */
18590        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
18591    }
18592
18593    /**
18594     * Interface definition for a callback to be invoked when the status bar changes
18595     * visibility.  This reports <strong>global</strong> changes to the system UI
18596     * state, not what the application is requesting.
18597     *
18598     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
18599     */
18600    public interface OnSystemUiVisibilityChangeListener {
18601        /**
18602         * Called when the status bar changes visibility because of a call to
18603         * {@link View#setSystemUiVisibility(int)}.
18604         *
18605         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
18606         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
18607         * This tells you the <strong>global</strong> state of these UI visibility
18608         * flags, not what your app is currently applying.
18609         */
18610        public void onSystemUiVisibilityChange(int visibility);
18611    }
18612
18613    /**
18614     * Interface definition for a callback to be invoked when this view is attached
18615     * or detached from its window.
18616     */
18617    public interface OnAttachStateChangeListener {
18618        /**
18619         * Called when the view is attached to a window.
18620         * @param v The view that was attached
18621         */
18622        public void onViewAttachedToWindow(View v);
18623        /**
18624         * Called when the view is detached from a window.
18625         * @param v The view that was detached
18626         */
18627        public void onViewDetachedFromWindow(View v);
18628    }
18629
18630    private final class UnsetPressedState implements Runnable {
18631        public void run() {
18632            setPressed(false);
18633        }
18634    }
18635
18636    /**
18637     * Base class for derived classes that want to save and restore their own
18638     * state in {@link android.view.View#onSaveInstanceState()}.
18639     */
18640    public static class BaseSavedState extends AbsSavedState {
18641        /**
18642         * Constructor used when reading from a parcel. Reads the state of the superclass.
18643         *
18644         * @param source
18645         */
18646        public BaseSavedState(Parcel source) {
18647            super(source);
18648        }
18649
18650        /**
18651         * Constructor called by derived classes when creating their SavedState objects
18652         *
18653         * @param superState The state of the superclass of this view
18654         */
18655        public BaseSavedState(Parcelable superState) {
18656            super(superState);
18657        }
18658
18659        public static final Parcelable.Creator<BaseSavedState> CREATOR =
18660                new Parcelable.Creator<BaseSavedState>() {
18661            public BaseSavedState createFromParcel(Parcel in) {
18662                return new BaseSavedState(in);
18663            }
18664
18665            public BaseSavedState[] newArray(int size) {
18666                return new BaseSavedState[size];
18667            }
18668        };
18669    }
18670
18671    /**
18672     * A set of information given to a view when it is attached to its parent
18673     * window.
18674     */
18675    static class AttachInfo {
18676        interface Callbacks {
18677            void playSoundEffect(int effectId);
18678            boolean performHapticFeedback(int effectId, boolean always);
18679        }
18680
18681        /**
18682         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
18683         * to a Handler. This class contains the target (View) to invalidate and
18684         * the coordinates of the dirty rectangle.
18685         *
18686         * For performance purposes, this class also implements a pool of up to
18687         * POOL_LIMIT objects that get reused. This reduces memory allocations
18688         * whenever possible.
18689         */
18690        static class InvalidateInfo {
18691            private static final int POOL_LIMIT = 10;
18692
18693            private static final SynchronizedPool<InvalidateInfo> sPool =
18694                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
18695
18696            View target;
18697
18698            int left;
18699            int top;
18700            int right;
18701            int bottom;
18702
18703            public static InvalidateInfo obtain() {
18704                InvalidateInfo instance = sPool.acquire();
18705                return (instance != null) ? instance : new InvalidateInfo();
18706            }
18707
18708            public void recycle() {
18709                target = null;
18710                sPool.release(this);
18711            }
18712        }
18713
18714        final IWindowSession mSession;
18715
18716        final IWindow mWindow;
18717
18718        final IBinder mWindowToken;
18719
18720        final Display mDisplay;
18721
18722        final Callbacks mRootCallbacks;
18723
18724        HardwareCanvas mHardwareCanvas;
18725
18726        IWindowId mIWindowId;
18727        WindowId mWindowId;
18728
18729        /**
18730         * The top view of the hierarchy.
18731         */
18732        View mRootView;
18733
18734        IBinder mPanelParentWindowToken;
18735        Surface mSurface;
18736
18737        boolean mHardwareAccelerated;
18738        boolean mHardwareAccelerationRequested;
18739        HardwareRenderer mHardwareRenderer;
18740
18741        boolean mScreenOn;
18742
18743        /**
18744         * Scale factor used by the compatibility mode
18745         */
18746        float mApplicationScale;
18747
18748        /**
18749         * Indicates whether the application is in compatibility mode
18750         */
18751        boolean mScalingRequired;
18752
18753        /**
18754         * If set, ViewRootImpl doesn't use its lame animation for when the window resizes.
18755         */
18756        boolean mTurnOffWindowResizeAnim;
18757
18758        /**
18759         * Left position of this view's window
18760         */
18761        int mWindowLeft;
18762
18763        /**
18764         * Top position of this view's window
18765         */
18766        int mWindowTop;
18767
18768        /**
18769         * Indicates whether views need to use 32-bit drawing caches
18770         */
18771        boolean mUse32BitDrawingCache;
18772
18773        /**
18774         * For windows that are full-screen but using insets to layout inside
18775         * of the screen areas, these are the current insets to appear inside
18776         * the overscan area of the display.
18777         */
18778        final Rect mOverscanInsets = new Rect();
18779
18780        /**
18781         * For windows that are full-screen but using insets to layout inside
18782         * of the screen decorations, these are the current insets for the
18783         * content of the window.
18784         */
18785        final Rect mContentInsets = new Rect();
18786
18787        /**
18788         * For windows that are full-screen but using insets to layout inside
18789         * of the screen decorations, these are the current insets for the
18790         * actual visible parts of the window.
18791         */
18792        final Rect mVisibleInsets = new Rect();
18793
18794        /**
18795         * The internal insets given by this window.  This value is
18796         * supplied by the client (through
18797         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
18798         * be given to the window manager when changed to be used in laying
18799         * out windows behind it.
18800         */
18801        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
18802                = new ViewTreeObserver.InternalInsetsInfo();
18803
18804        /**
18805         * Set to true when mGivenInternalInsets is non-empty.
18806         */
18807        boolean mHasNonEmptyGivenInternalInsets;
18808
18809        /**
18810         * All views in the window's hierarchy that serve as scroll containers,
18811         * used to determine if the window can be resized or must be panned
18812         * to adjust for a soft input area.
18813         */
18814        final ArrayList<View> mScrollContainers = new ArrayList<View>();
18815
18816        final KeyEvent.DispatcherState mKeyDispatchState
18817                = new KeyEvent.DispatcherState();
18818
18819        /**
18820         * Indicates whether the view's window currently has the focus.
18821         */
18822        boolean mHasWindowFocus;
18823
18824        /**
18825         * The current visibility of the window.
18826         */
18827        int mWindowVisibility;
18828
18829        /**
18830         * Indicates the time at which drawing started to occur.
18831         */
18832        long mDrawingTime;
18833
18834        /**
18835         * Indicates whether or not ignoring the DIRTY_MASK flags.
18836         */
18837        boolean mIgnoreDirtyState;
18838
18839        /**
18840         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
18841         * to avoid clearing that flag prematurely.
18842         */
18843        boolean mSetIgnoreDirtyState = false;
18844
18845        /**
18846         * Indicates whether the view's window is currently in touch mode.
18847         */
18848        boolean mInTouchMode;
18849
18850        /**
18851         * Indicates that ViewAncestor should trigger a global layout change
18852         * the next time it performs a traversal
18853         */
18854        boolean mRecomputeGlobalAttributes;
18855
18856        /**
18857         * Always report new attributes at next traversal.
18858         */
18859        boolean mForceReportNewAttributes;
18860
18861        /**
18862         * Set during a traveral if any views want to keep the screen on.
18863         */
18864        boolean mKeepScreenOn;
18865
18866        /**
18867         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
18868         */
18869        int mSystemUiVisibility;
18870
18871        /**
18872         * Hack to force certain system UI visibility flags to be cleared.
18873         */
18874        int mDisabledSystemUiVisibility;
18875
18876        /**
18877         * Last global system UI visibility reported by the window manager.
18878         */
18879        int mGlobalSystemUiVisibility;
18880
18881        /**
18882         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
18883         * attached.
18884         */
18885        boolean mHasSystemUiListeners;
18886
18887        /**
18888         * Set if the window has requested to extend into the overscan region
18889         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
18890         */
18891        boolean mOverscanRequested;
18892
18893        /**
18894         * Set if the visibility of any views has changed.
18895         */
18896        boolean mViewVisibilityChanged;
18897
18898        /**
18899         * Set to true if a view has been scrolled.
18900         */
18901        boolean mViewScrollChanged;
18902
18903        /**
18904         * Global to the view hierarchy used as a temporary for dealing with
18905         * x/y points in the transparent region computations.
18906         */
18907        final int[] mTransparentLocation = new int[2];
18908
18909        /**
18910         * Global to the view hierarchy used as a temporary for dealing with
18911         * x/y points in the ViewGroup.invalidateChild implementation.
18912         */
18913        final int[] mInvalidateChildLocation = new int[2];
18914
18915
18916        /**
18917         * Global to the view hierarchy used as a temporary for dealing with
18918         * x/y location when view is transformed.
18919         */
18920        final float[] mTmpTransformLocation = new float[2];
18921
18922        /**
18923         * The view tree observer used to dispatch global events like
18924         * layout, pre-draw, touch mode change, etc.
18925         */
18926        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
18927
18928        /**
18929         * A Canvas used by the view hierarchy to perform bitmap caching.
18930         */
18931        Canvas mCanvas;
18932
18933        /**
18934         * The view root impl.
18935         */
18936        final ViewRootImpl mViewRootImpl;
18937
18938        /**
18939         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
18940         * handler can be used to pump events in the UI events queue.
18941         */
18942        final Handler mHandler;
18943
18944        /**
18945         * Temporary for use in computing invalidate rectangles while
18946         * calling up the hierarchy.
18947         */
18948        final Rect mTmpInvalRect = new Rect();
18949
18950        /**
18951         * Temporary for use in computing hit areas with transformed views
18952         */
18953        final RectF mTmpTransformRect = new RectF();
18954
18955        /**
18956         * Temporary for use in transforming invalidation rect
18957         */
18958        final Matrix mTmpMatrix = new Matrix();
18959
18960        /**
18961         * Temporary for use in transforming invalidation rect
18962         */
18963        final Transformation mTmpTransformation = new Transformation();
18964
18965        /**
18966         * Temporary list for use in collecting focusable descendents of a view.
18967         */
18968        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
18969
18970        /**
18971         * The id of the window for accessibility purposes.
18972         */
18973        int mAccessibilityWindowId = View.NO_ID;
18974
18975        /**
18976         * Flags related to accessibility processing.
18977         *
18978         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
18979         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
18980         */
18981        int mAccessibilityFetchFlags;
18982
18983        /**
18984         * The drawable for highlighting accessibility focus.
18985         */
18986        Drawable mAccessibilityFocusDrawable;
18987
18988        /**
18989         * Show where the margins, bounds and layout bounds are for each view.
18990         */
18991        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
18992
18993        /**
18994         * Point used to compute visible regions.
18995         */
18996        final Point mPoint = new Point();
18997
18998        /**
18999         * Used to track which View originated a requestLayout() call, used when
19000         * requestLayout() is called during layout.
19001         */
19002        View mViewRequestingLayout;
19003
19004        /**
19005         * Creates a new set of attachment information with the specified
19006         * events handler and thread.
19007         *
19008         * @param handler the events handler the view must use
19009         */
19010        AttachInfo(IWindowSession session, IWindow window, Display display,
19011                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
19012            mSession = session;
19013            mWindow = window;
19014            mWindowToken = window.asBinder();
19015            mDisplay = display;
19016            mViewRootImpl = viewRootImpl;
19017            mHandler = handler;
19018            mRootCallbacks = effectPlayer;
19019        }
19020    }
19021
19022    /**
19023     * <p>ScrollabilityCache holds various fields used by a View when scrolling
19024     * is supported. This avoids keeping too many unused fields in most
19025     * instances of View.</p>
19026     */
19027    private static class ScrollabilityCache implements Runnable {
19028
19029        /**
19030         * Scrollbars are not visible
19031         */
19032        public static final int OFF = 0;
19033
19034        /**
19035         * Scrollbars are visible
19036         */
19037        public static final int ON = 1;
19038
19039        /**
19040         * Scrollbars are fading away
19041         */
19042        public static final int FADING = 2;
19043
19044        public boolean fadeScrollBars;
19045
19046        public int fadingEdgeLength;
19047        public int scrollBarDefaultDelayBeforeFade;
19048        public int scrollBarFadeDuration;
19049
19050        public int scrollBarSize;
19051        public ScrollBarDrawable scrollBar;
19052        public float[] interpolatorValues;
19053        public View host;
19054
19055        public final Paint paint;
19056        public final Matrix matrix;
19057        public Shader shader;
19058
19059        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
19060
19061        private static final float[] OPAQUE = { 255 };
19062        private static final float[] TRANSPARENT = { 0.0f };
19063
19064        /**
19065         * When fading should start. This time moves into the future every time
19066         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
19067         */
19068        public long fadeStartTime;
19069
19070
19071        /**
19072         * The current state of the scrollbars: ON, OFF, or FADING
19073         */
19074        public int state = OFF;
19075
19076        private int mLastColor;
19077
19078        public ScrollabilityCache(ViewConfiguration configuration, View host) {
19079            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
19080            scrollBarSize = configuration.getScaledScrollBarSize();
19081            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
19082            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
19083
19084            paint = new Paint();
19085            matrix = new Matrix();
19086            // use use a height of 1, and then wack the matrix each time we
19087            // actually use it.
19088            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
19089            paint.setShader(shader);
19090            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
19091
19092            this.host = host;
19093        }
19094
19095        public void setFadeColor(int color) {
19096            if (color != mLastColor) {
19097                mLastColor = color;
19098
19099                if (color != 0) {
19100                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
19101                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
19102                    paint.setShader(shader);
19103                    // Restore the default transfer mode (src_over)
19104                    paint.setXfermode(null);
19105                } else {
19106                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
19107                    paint.setShader(shader);
19108                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
19109                }
19110            }
19111        }
19112
19113        public void run() {
19114            long now = AnimationUtils.currentAnimationTimeMillis();
19115            if (now >= fadeStartTime) {
19116
19117                // the animation fades the scrollbars out by changing
19118                // the opacity (alpha) from fully opaque to fully
19119                // transparent
19120                int nextFrame = (int) now;
19121                int framesCount = 0;
19122
19123                Interpolator interpolator = scrollBarInterpolator;
19124
19125                // Start opaque
19126                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
19127
19128                // End transparent
19129                nextFrame += scrollBarFadeDuration;
19130                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
19131
19132                state = FADING;
19133
19134                // Kick off the fade animation
19135                host.invalidate(true);
19136            }
19137        }
19138    }
19139
19140    /**
19141     * Resuable callback for sending
19142     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
19143     */
19144    private class SendViewScrolledAccessibilityEvent implements Runnable {
19145        public volatile boolean mIsPending;
19146
19147        public void run() {
19148            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
19149            mIsPending = false;
19150        }
19151    }
19152
19153    /**
19154     * <p>
19155     * This class represents a delegate that can be registered in a {@link View}
19156     * to enhance accessibility support via composition rather via inheritance.
19157     * It is specifically targeted to widget developers that extend basic View
19158     * classes i.e. classes in package android.view, that would like their
19159     * applications to be backwards compatible.
19160     * </p>
19161     * <div class="special reference">
19162     * <h3>Developer Guides</h3>
19163     * <p>For more information about making applications accessible, read the
19164     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
19165     * developer guide.</p>
19166     * </div>
19167     * <p>
19168     * A scenario in which a developer would like to use an accessibility delegate
19169     * is overriding a method introduced in a later API version then the minimal API
19170     * version supported by the application. For example, the method
19171     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
19172     * in API version 4 when the accessibility APIs were first introduced. If a
19173     * developer would like his application to run on API version 4 devices (assuming
19174     * all other APIs used by the application are version 4 or lower) and take advantage
19175     * of this method, instead of overriding the method which would break the application's
19176     * backwards compatibility, he can override the corresponding method in this
19177     * delegate and register the delegate in the target View if the API version of
19178     * the system is high enough i.e. the API version is same or higher to the API
19179     * version that introduced
19180     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
19181     * </p>
19182     * <p>
19183     * Here is an example implementation:
19184     * </p>
19185     * <code><pre><p>
19186     * if (Build.VERSION.SDK_INT >= 14) {
19187     *     // If the API version is equal of higher than the version in
19188     *     // which onInitializeAccessibilityNodeInfo was introduced we
19189     *     // register a delegate with a customized implementation.
19190     *     View view = findViewById(R.id.view_id);
19191     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
19192     *         public void onInitializeAccessibilityNodeInfo(View host,
19193     *                 AccessibilityNodeInfo info) {
19194     *             // Let the default implementation populate the info.
19195     *             super.onInitializeAccessibilityNodeInfo(host, info);
19196     *             // Set some other information.
19197     *             info.setEnabled(host.isEnabled());
19198     *         }
19199     *     });
19200     * }
19201     * </code></pre></p>
19202     * <p>
19203     * This delegate contains methods that correspond to the accessibility methods
19204     * in View. If a delegate has been specified the implementation in View hands
19205     * off handling to the corresponding method in this delegate. The default
19206     * implementation the delegate methods behaves exactly as the corresponding
19207     * method in View for the case of no accessibility delegate been set. Hence,
19208     * to customize the behavior of a View method, clients can override only the
19209     * corresponding delegate method without altering the behavior of the rest
19210     * accessibility related methods of the host view.
19211     * </p>
19212     */
19213    public static class AccessibilityDelegate {
19214
19215        /**
19216         * Sends an accessibility event of the given type. If accessibility is not
19217         * enabled this method has no effect.
19218         * <p>
19219         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
19220         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
19221         * been set.
19222         * </p>
19223         *
19224         * @param host The View hosting the delegate.
19225         * @param eventType The type of the event to send.
19226         *
19227         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
19228         */
19229        public void sendAccessibilityEvent(View host, int eventType) {
19230            host.sendAccessibilityEventInternal(eventType);
19231        }
19232
19233        /**
19234         * Performs the specified accessibility action on the view. For
19235         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
19236         * <p>
19237         * The default implementation behaves as
19238         * {@link View#performAccessibilityAction(int, Bundle)
19239         *  View#performAccessibilityAction(int, Bundle)} for the case of
19240         *  no accessibility delegate been set.
19241         * </p>
19242         *
19243         * @param action The action to perform.
19244         * @return Whether the action was performed.
19245         *
19246         * @see View#performAccessibilityAction(int, Bundle)
19247         *      View#performAccessibilityAction(int, Bundle)
19248         */
19249        public boolean performAccessibilityAction(View host, int action, Bundle args) {
19250            return host.performAccessibilityActionInternal(action, args);
19251        }
19252
19253        /**
19254         * Sends an accessibility event. This method behaves exactly as
19255         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
19256         * empty {@link AccessibilityEvent} and does not perform a check whether
19257         * accessibility is enabled.
19258         * <p>
19259         * The default implementation behaves as
19260         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
19261         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
19262         * the case of no accessibility delegate been set.
19263         * </p>
19264         *
19265         * @param host The View hosting the delegate.
19266         * @param event The event to send.
19267         *
19268         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
19269         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
19270         */
19271        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
19272            host.sendAccessibilityEventUncheckedInternal(event);
19273        }
19274
19275        /**
19276         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
19277         * to its children for adding their text content to the event.
19278         * <p>
19279         * The default implementation behaves as
19280         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
19281         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
19282         * the case of no accessibility delegate been set.
19283         * </p>
19284         *
19285         * @param host The View hosting the delegate.
19286         * @param event The event.
19287         * @return True if the event population was completed.
19288         *
19289         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
19290         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
19291         */
19292        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
19293            return host.dispatchPopulateAccessibilityEventInternal(event);
19294        }
19295
19296        /**
19297         * Gives a chance to the host View to populate the accessibility event with its
19298         * text content.
19299         * <p>
19300         * The default implementation behaves as
19301         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
19302         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
19303         * the case of no accessibility delegate been set.
19304         * </p>
19305         *
19306         * @param host The View hosting the delegate.
19307         * @param event The accessibility event which to populate.
19308         *
19309         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
19310         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
19311         */
19312        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
19313            host.onPopulateAccessibilityEventInternal(event);
19314        }
19315
19316        /**
19317         * Initializes an {@link AccessibilityEvent} with information about the
19318         * the host View which is the event source.
19319         * <p>
19320         * The default implementation behaves as
19321         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
19322         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
19323         * the case of no accessibility delegate been set.
19324         * </p>
19325         *
19326         * @param host The View hosting the delegate.
19327         * @param event The event to initialize.
19328         *
19329         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
19330         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
19331         */
19332        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
19333            host.onInitializeAccessibilityEventInternal(event);
19334        }
19335
19336        /**
19337         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
19338         * <p>
19339         * The default implementation behaves as
19340         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
19341         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
19342         * the case of no accessibility delegate been set.
19343         * </p>
19344         *
19345         * @param host The View hosting the delegate.
19346         * @param info The instance to initialize.
19347         *
19348         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
19349         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
19350         */
19351        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
19352            host.onInitializeAccessibilityNodeInfoInternal(info);
19353        }
19354
19355        /**
19356         * Called when a child of the host View has requested sending an
19357         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
19358         * to augment the event.
19359         * <p>
19360         * The default implementation behaves as
19361         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
19362         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
19363         * the case of no accessibility delegate been set.
19364         * </p>
19365         *
19366         * @param host The View hosting the delegate.
19367         * @param child The child which requests sending the event.
19368         * @param event The event to be sent.
19369         * @return True if the event should be sent
19370         *
19371         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
19372         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
19373         */
19374        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
19375                AccessibilityEvent event) {
19376            return host.onRequestSendAccessibilityEventInternal(child, event);
19377        }
19378
19379        /**
19380         * Gets the provider for managing a virtual view hierarchy rooted at this View
19381         * and reported to {@link android.accessibilityservice.AccessibilityService}s
19382         * that explore the window content.
19383         * <p>
19384         * The default implementation behaves as
19385         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
19386         * the case of no accessibility delegate been set.
19387         * </p>
19388         *
19389         * @return The provider.
19390         *
19391         * @see AccessibilityNodeProvider
19392         */
19393        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
19394            return null;
19395        }
19396
19397        /**
19398         * Returns an {@link AccessibilityNodeInfo} representing the host view from the
19399         * point of view of an {@link android.accessibilityservice.AccessibilityService}.
19400         * This method is responsible for obtaining an accessibility node info from a
19401         * pool of reusable instances and calling
19402         * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host
19403         * view to initialize the former.
19404         * <p>
19405         * <strong>Note:</strong> The client is responsible for recycling the obtained
19406         * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object
19407         * creation.
19408         * </p>
19409         * <p>
19410         * The default implementation behaves as
19411         * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for
19412         * the case of no accessibility delegate been set.
19413         * </p>
19414         * @return A populated {@link AccessibilityNodeInfo}.
19415         *
19416         * @see AccessibilityNodeInfo
19417         *
19418         * @hide
19419         */
19420        public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) {
19421            return host.createAccessibilityNodeInfoInternal();
19422        }
19423    }
19424
19425    private class MatchIdPredicate implements Predicate<View> {
19426        public int mId;
19427
19428        @Override
19429        public boolean apply(View view) {
19430            return (view.mID == mId);
19431        }
19432    }
19433
19434    private class MatchLabelForPredicate implements Predicate<View> {
19435        private int mLabeledId;
19436
19437        @Override
19438        public boolean apply(View view) {
19439            return (view.mLabelForId == mLabeledId);
19440        }
19441    }
19442
19443    private class SendViewStateChangedAccessibilityEvent implements Runnable {
19444        private int mChangeTypes = 0;
19445        private boolean mPosted;
19446        private boolean mPostedWithDelay;
19447        private long mLastEventTimeMillis;
19448
19449        @Override
19450        public void run() {
19451            mPosted = false;
19452            mPostedWithDelay = false;
19453            mLastEventTimeMillis = SystemClock.uptimeMillis();
19454            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
19455                final AccessibilityEvent event = AccessibilityEvent.obtain();
19456                event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
19457                event.setContentChangeTypes(mChangeTypes);
19458                sendAccessibilityEventUnchecked(event);
19459            }
19460            mChangeTypes = 0;
19461        }
19462
19463        public void runOrPost(int changeType) {
19464            mChangeTypes |= changeType;
19465
19466            // If this is a live region or the child of a live region, collect
19467            // all events from this frame and send them on the next frame.
19468            if (inLiveRegion()) {
19469                // If we're already posted with a delay, remove that.
19470                if (mPostedWithDelay) {
19471                    removeCallbacks(this);
19472                    mPostedWithDelay = false;
19473                }
19474                // Only post if we're not already posted.
19475                if (!mPosted) {
19476                    post(this);
19477                    mPosted = true;
19478                }
19479                return;
19480            }
19481
19482            if (mPosted) {
19483                return;
19484            }
19485            final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
19486            final long minEventIntevalMillis =
19487                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
19488            if (timeSinceLastMillis >= minEventIntevalMillis) {
19489                removeCallbacks(this);
19490                run();
19491            } else {
19492                postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
19493                mPosted = true;
19494                mPostedWithDelay = true;
19495            }
19496        }
19497    }
19498
19499    private boolean inLiveRegion() {
19500        if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) {
19501            return true;
19502        }
19503
19504        ViewParent parent = getParent();
19505        while (parent instanceof View) {
19506            if (((View) parent).getAccessibilityLiveRegion()
19507                    != View.ACCESSIBILITY_LIVE_REGION_NONE) {
19508                return true;
19509            }
19510            parent = parent.getParent();
19511        }
19512
19513        return false;
19514    }
19515
19516    /**
19517     * Dump all private flags in readable format, useful for documentation and
19518     * sanity checking.
19519     */
19520    private static void dumpFlags() {
19521        final HashMap<String, String> found = Maps.newHashMap();
19522        try {
19523            for (Field field : View.class.getDeclaredFields()) {
19524                final int modifiers = field.getModifiers();
19525                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
19526                    if (field.getType().equals(int.class)) {
19527                        final int value = field.getInt(null);
19528                        dumpFlag(found, field.getName(), value);
19529                    } else if (field.getType().equals(int[].class)) {
19530                        final int[] values = (int[]) field.get(null);
19531                        for (int i = 0; i < values.length; i++) {
19532                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
19533                        }
19534                    }
19535                }
19536            }
19537        } catch (IllegalAccessException e) {
19538            throw new RuntimeException(e);
19539        }
19540
19541        final ArrayList<String> keys = Lists.newArrayList();
19542        keys.addAll(found.keySet());
19543        Collections.sort(keys);
19544        for (String key : keys) {
19545            Log.d(VIEW_LOG_TAG, found.get(key));
19546        }
19547    }
19548
19549    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
19550        // Sort flags by prefix, then by bits, always keeping unique keys
19551        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
19552        final int prefix = name.indexOf('_');
19553        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
19554        final String output = bits + " " + name;
19555        found.put(key, output);
19556    }
19557}
19558