View.java revision 4155e2e175d73bb98b13ecb2fbbe6a6dffe28fe5
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.res.Configuration;
22import android.content.res.Resources;
23import android.content.res.TypedArray;
24import android.graphics.Bitmap;
25import android.graphics.Camera;
26import android.graphics.Canvas;
27import android.graphics.Insets;
28import android.graphics.Interpolator;
29import android.graphics.LinearGradient;
30import android.graphics.Matrix;
31import android.graphics.Paint;
32import android.graphics.PixelFormat;
33import android.graphics.Point;
34import android.graphics.PorterDuff;
35import android.graphics.PorterDuffXfermode;
36import android.graphics.Rect;
37import android.graphics.RectF;
38import android.graphics.Region;
39import android.graphics.Shader;
40import android.graphics.drawable.ColorDrawable;
41import android.graphics.drawable.Drawable;
42import android.hardware.display.DisplayManagerGlobal;
43import android.os.Bundle;
44import android.os.Handler;
45import android.os.IBinder;
46import android.os.Parcel;
47import android.os.Parcelable;
48import android.os.RemoteException;
49import android.os.SystemClock;
50import android.os.SystemProperties;
51import android.text.TextUtils;
52import android.util.AttributeSet;
53import android.util.FloatProperty;
54import android.util.LayoutDirection;
55import android.util.Log;
56import android.util.LongSparseLongArray;
57import android.util.Pools.SynchronizedPool;
58import android.util.Property;
59import android.util.SparseArray;
60import android.util.TypedValue;
61import android.view.ContextMenu.ContextMenuInfo;
62import android.view.AccessibilityIterators.TextSegmentIterator;
63import android.view.AccessibilityIterators.CharacterTextSegmentIterator;
64import android.view.AccessibilityIterators.WordTextSegmentIterator;
65import android.view.AccessibilityIterators.ParagraphTextSegmentIterator;
66import android.view.accessibility.AccessibilityEvent;
67import android.view.accessibility.AccessibilityEventSource;
68import android.view.accessibility.AccessibilityManager;
69import android.view.accessibility.AccessibilityNodeInfo;
70import android.view.accessibility.AccessibilityNodeProvider;
71import android.view.animation.Animation;
72import android.view.animation.AnimationUtils;
73import android.view.animation.Transformation;
74import android.view.inputmethod.EditorInfo;
75import android.view.inputmethod.InputConnection;
76import android.view.inputmethod.InputMethodManager;
77import android.view.transition.Scene;
78import android.widget.ScrollBarDrawable;
79
80import static android.os.Build.VERSION_CODES.*;
81import static java.lang.Math.max;
82
83import com.android.internal.R;
84import com.android.internal.util.Predicate;
85import com.android.internal.view.menu.MenuBuilder;
86import com.google.android.collect.Lists;
87import com.google.android.collect.Maps;
88
89import java.lang.ref.WeakReference;
90import java.lang.reflect.Field;
91import java.lang.reflect.InvocationTargetException;
92import java.lang.reflect.Method;
93import java.lang.reflect.Modifier;
94import java.util.ArrayList;
95import java.util.Arrays;
96import java.util.Collections;
97import java.util.HashMap;
98import java.util.Locale;
99import java.util.concurrent.CopyOnWriteArrayList;
100import java.util.concurrent.atomic.AtomicInteger;
101
102/**
103 * <p>
104 * This class represents the basic building block for user interface components. A View
105 * occupies a rectangular area on the screen and is responsible for drawing and
106 * event handling. View is the base class for <em>widgets</em>, which are
107 * used to create interactive UI components (buttons, text fields, etc.). The
108 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
109 * are invisible containers that hold other Views (or other ViewGroups) and define
110 * their layout properties.
111 * </p>
112 *
113 * <div class="special reference">
114 * <h3>Developer Guides</h3>
115 * <p>For information about using this class to develop your application's user interface,
116 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
117 * </div>
118 *
119 * <a name="Using"></a>
120 * <h3>Using Views</h3>
121 * <p>
122 * All of the views in a window are arranged in a single tree. You can add views
123 * either from code or by specifying a tree of views in one or more XML layout
124 * files. There are many specialized subclasses of views that act as controls or
125 * are capable of displaying text, images, or other content.
126 * </p>
127 * <p>
128 * Once you have created a tree of views, there are typically a few types of
129 * common operations you may wish to perform:
130 * <ul>
131 * <li><strong>Set properties:</strong> for example setting the text of a
132 * {@link android.widget.TextView}. The available properties and the methods
133 * that set them will vary among the different subclasses of views. Note that
134 * properties that are known at build time can be set in the XML layout
135 * files.</li>
136 * <li><strong>Set focus:</strong> The framework will handled moving focus in
137 * response to user input. To force focus to a specific view, call
138 * {@link #requestFocus}.</li>
139 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
140 * that will be notified when something interesting happens to the view. For
141 * example, all views will let you set a listener to be notified when the view
142 * gains or loses focus. You can register such a listener using
143 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
144 * Other view subclasses offer more specialized listeners. For example, a Button
145 * exposes a listener to notify clients when the button is clicked.</li>
146 * <li><strong>Set visibility:</strong> You can hide or show views using
147 * {@link #setVisibility(int)}.</li>
148 * </ul>
149 * </p>
150 * <p><em>
151 * Note: The Android framework is responsible for measuring, laying out and
152 * drawing views. You should not call methods that perform these actions on
153 * views yourself unless you are actually implementing a
154 * {@link android.view.ViewGroup}.
155 * </em></p>
156 *
157 * <a name="Lifecycle"></a>
158 * <h3>Implementing a Custom View</h3>
159 *
160 * <p>
161 * To implement a custom view, you will usually begin by providing overrides for
162 * some of the standard methods that the framework calls on all views. You do
163 * not need to override all of these methods. In fact, you can start by just
164 * overriding {@link #onDraw(android.graphics.Canvas)}.
165 * <table border="2" width="85%" align="center" cellpadding="5">
166 *     <thead>
167 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
168 *     </thead>
169 *
170 *     <tbody>
171 *     <tr>
172 *         <td rowspan="2">Creation</td>
173 *         <td>Constructors</td>
174 *         <td>There is a form of the constructor that are called when the view
175 *         is created from code and a form that is called when the view is
176 *         inflated from a layout file. The second form should parse and apply
177 *         any attributes defined in the layout file.
178 *         </td>
179 *     </tr>
180 *     <tr>
181 *         <td><code>{@link #onFinishInflate()}</code></td>
182 *         <td>Called after a view and all of its children has been inflated
183 *         from XML.</td>
184 *     </tr>
185 *
186 *     <tr>
187 *         <td rowspan="3">Layout</td>
188 *         <td><code>{@link #onMeasure(int, int)}</code></td>
189 *         <td>Called to determine the size requirements for this view and all
190 *         of its children.
191 *         </td>
192 *     </tr>
193 *     <tr>
194 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
195 *         <td>Called when this view should assign a size and position to all
196 *         of its children.
197 *         </td>
198 *     </tr>
199 *     <tr>
200 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
201 *         <td>Called when the size of this view has changed.
202 *         </td>
203 *     </tr>
204 *
205 *     <tr>
206 *         <td>Drawing</td>
207 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
208 *         <td>Called when the view should render its content.
209 *         </td>
210 *     </tr>
211 *
212 *     <tr>
213 *         <td rowspan="4">Event processing</td>
214 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
215 *         <td>Called when a new hardware key event occurs.
216 *         </td>
217 *     </tr>
218 *     <tr>
219 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
220 *         <td>Called when a hardware key up event occurs.
221 *         </td>
222 *     </tr>
223 *     <tr>
224 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
225 *         <td>Called when a trackball motion event occurs.
226 *         </td>
227 *     </tr>
228 *     <tr>
229 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
230 *         <td>Called when a touch screen motion event occurs.
231 *         </td>
232 *     </tr>
233 *
234 *     <tr>
235 *         <td rowspan="2">Focus</td>
236 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
237 *         <td>Called when the view gains or loses focus.
238 *         </td>
239 *     </tr>
240 *
241 *     <tr>
242 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
243 *         <td>Called when the window containing the view gains or loses focus.
244 *         </td>
245 *     </tr>
246 *
247 *     <tr>
248 *         <td rowspan="3">Attaching</td>
249 *         <td><code>{@link #onAttachedToWindow()}</code></td>
250 *         <td>Called when the view is attached to a window.
251 *         </td>
252 *     </tr>
253 *
254 *     <tr>
255 *         <td><code>{@link #onDetachedFromWindow}</code></td>
256 *         <td>Called when the view is detached from its window.
257 *         </td>
258 *     </tr>
259 *
260 *     <tr>
261 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
262 *         <td>Called when the visibility of the window containing the view
263 *         has changed.
264 *         </td>
265 *     </tr>
266 *     </tbody>
267 *
268 * </table>
269 * </p>
270 *
271 * <a name="IDs"></a>
272 * <h3>IDs</h3>
273 * Views may have an integer id associated with them. These ids are typically
274 * assigned in the layout XML files, and are used to find specific views within
275 * the view tree. A common pattern is to:
276 * <ul>
277 * <li>Define a Button in the layout file and assign it a unique ID.
278 * <pre>
279 * &lt;Button
280 *     android:id="@+id/my_button"
281 *     android:layout_width="wrap_content"
282 *     android:layout_height="wrap_content"
283 *     android:text="@string/my_button_text"/&gt;
284 * </pre></li>
285 * <li>From the onCreate method of an Activity, find the Button
286 * <pre class="prettyprint">
287 *      Button myButton = (Button) findViewById(R.id.my_button);
288 * </pre></li>
289 * </ul>
290 * <p>
291 * View IDs need not be unique throughout the tree, but it is good practice to
292 * ensure that they are at least unique within the part of the tree you are
293 * searching.
294 * </p>
295 *
296 * <a name="Position"></a>
297 * <h3>Position</h3>
298 * <p>
299 * The geometry of a view is that of a rectangle. A view has a location,
300 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
301 * two dimensions, expressed as a width and a height. The unit for location
302 * and dimensions is the pixel.
303 * </p>
304 *
305 * <p>
306 * It is possible to retrieve the location of a view by invoking the methods
307 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
308 * coordinate of the rectangle representing the view. The latter returns the
309 * top, or Y, coordinate of the rectangle representing the view. These methods
310 * both return the location of the view relative to its parent. For instance,
311 * when getLeft() returns 20, that means the view is located 20 pixels to the
312 * right of the left edge of its direct parent.
313 * </p>
314 *
315 * <p>
316 * In addition, several convenience methods are offered to avoid unnecessary
317 * computations, namely {@link #getRight()} and {@link #getBottom()}.
318 * These methods return the coordinates of the right and bottom edges of the
319 * rectangle representing the view. For instance, calling {@link #getRight()}
320 * is similar to the following computation: <code>getLeft() + getWidth()</code>
321 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
322 * </p>
323 *
324 * <a name="SizePaddingMargins"></a>
325 * <h3>Size, padding and margins</h3>
326 * <p>
327 * The size of a view is expressed with a width and a height. A view actually
328 * possess two pairs of width and height values.
329 * </p>
330 *
331 * <p>
332 * The first pair is known as <em>measured width</em> and
333 * <em>measured height</em>. These dimensions define how big a view wants to be
334 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
335 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
336 * and {@link #getMeasuredHeight()}.
337 * </p>
338 *
339 * <p>
340 * The second pair is simply known as <em>width</em> and <em>height</em>, or
341 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
342 * dimensions define the actual size of the view on screen, at drawing time and
343 * after layout. These values may, but do not have to, be different from the
344 * measured width and height. The width and height can be obtained by calling
345 * {@link #getWidth()} and {@link #getHeight()}.
346 * </p>
347 *
348 * <p>
349 * To measure its dimensions, a view takes into account its padding. The padding
350 * is expressed in pixels for the left, top, right and bottom parts of the view.
351 * Padding can be used to offset the content of the view by a specific amount of
352 * pixels. For instance, a left padding of 2 will push the view's content by
353 * 2 pixels to the right of the left edge. Padding can be set using the
354 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)}
355 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()},
356 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()},
357 * {@link #getPaddingEnd()}.
358 * </p>
359 *
360 * <p>
361 * Even though a view can define a padding, it does not provide any support for
362 * margins. However, view groups provide such a support. Refer to
363 * {@link android.view.ViewGroup} and
364 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
365 * </p>
366 *
367 * <a name="Layout"></a>
368 * <h3>Layout</h3>
369 * <p>
370 * Layout is a two pass process: a measure pass and a layout pass. The measuring
371 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
372 * of the view tree. Each view pushes dimension specifications down the tree
373 * during the recursion. At the end of the measure pass, every view has stored
374 * its measurements. The second pass happens in
375 * {@link #layout(int,int,int,int)} and is also top-down. During
376 * this pass each parent is responsible for positioning all of its children
377 * using the sizes computed in the measure pass.
378 * </p>
379 *
380 * <p>
381 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
382 * {@link #getMeasuredHeight()} values must be set, along with those for all of
383 * that view's descendants. A view's measured width and measured height values
384 * must respect the constraints imposed by the view's parents. This guarantees
385 * that at the end of the measure pass, all parents accept all of their
386 * children's measurements. A parent view may call measure() more than once on
387 * its children. For example, the parent may measure each child once with
388 * unspecified dimensions to find out how big they want to be, then call
389 * measure() on them again with actual numbers if the sum of all the children's
390 * unconstrained sizes is too big or too small.
391 * </p>
392 *
393 * <p>
394 * The measure pass uses two classes to communicate dimensions. The
395 * {@link MeasureSpec} class is used by views to tell their parents how they
396 * want to be measured and positioned. The base LayoutParams class just
397 * describes how big the view wants to be for both width and height. For each
398 * dimension, it can specify one of:
399 * <ul>
400 * <li> an exact number
401 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
402 * (minus padding)
403 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
404 * enclose its content (plus padding).
405 * </ul>
406 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
407 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
408 * an X and Y value.
409 * </p>
410 *
411 * <p>
412 * MeasureSpecs are used to push requirements down the tree from parent to
413 * child. A MeasureSpec can be in one of three modes:
414 * <ul>
415 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
416 * of a child view. For example, a LinearLayout may call measure() on its child
417 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
418 * tall the child view wants to be given a width of 240 pixels.
419 * <li>EXACTLY: This is used by the parent to impose an exact size on the
420 * child. The child must use this size, and guarantee that all of its
421 * descendants will fit within this size.
422 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
423 * child. The child must gurantee that it and all of its descendants will fit
424 * within this size.
425 * </ul>
426 * </p>
427 *
428 * <p>
429 * To intiate a layout, call {@link #requestLayout}. This method is typically
430 * called by a view on itself when it believes that is can no longer fit within
431 * its current bounds.
432 * </p>
433 *
434 * <a name="Drawing"></a>
435 * <h3>Drawing</h3>
436 * <p>
437 * Drawing is handled by walking the tree and rendering each view that
438 * intersects the invalid region. Because the tree is traversed in-order,
439 * this means that parents will draw before (i.e., behind) their children, with
440 * siblings drawn in the order they appear in the tree.
441 * If you set a background drawable for a View, then the View will draw it for you
442 * before calling back to its <code>onDraw()</code> method.
443 * </p>
444 *
445 * <p>
446 * Note that the framework will not draw views that are not in the invalid region.
447 * </p>
448 *
449 * <p>
450 * To force a view to draw, call {@link #invalidate()}.
451 * </p>
452 *
453 * <a name="EventHandlingThreading"></a>
454 * <h3>Event Handling and Threading</h3>
455 * <p>
456 * The basic cycle of a view is as follows:
457 * <ol>
458 * <li>An event comes in and is dispatched to the appropriate view. The view
459 * handles the event and notifies any listeners.</li>
460 * <li>If in the course of processing the event, the view's bounds may need
461 * to be changed, the view will call {@link #requestLayout()}.</li>
462 * <li>Similarly, if in the course of processing the event the view's appearance
463 * may need to be changed, the view will call {@link #invalidate()}.</li>
464 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
465 * the framework will take care of measuring, laying out, and drawing the tree
466 * as appropriate.</li>
467 * </ol>
468 * </p>
469 *
470 * <p><em>Note: The entire view tree is single threaded. You must always be on
471 * the UI thread when calling any method on any view.</em>
472 * If you are doing work on other threads and want to update the state of a view
473 * from that thread, you should use a {@link Handler}.
474 * </p>
475 *
476 * <a name="FocusHandling"></a>
477 * <h3>Focus Handling</h3>
478 * <p>
479 * The framework will handle routine focus movement in response to user input.
480 * This includes changing the focus as views are removed or hidden, or as new
481 * views become available. Views indicate their willingness to take focus
482 * through the {@link #isFocusable} method. To change whether a view can take
483 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
484 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
485 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
486 * </p>
487 * <p>
488 * Focus movement is based on an algorithm which finds the nearest neighbor in a
489 * given direction. In rare cases, the default algorithm may not match the
490 * intended behavior of the developer. In these situations, you can provide
491 * explicit overrides by using these XML attributes in the layout file:
492 * <pre>
493 * nextFocusDown
494 * nextFocusLeft
495 * nextFocusRight
496 * nextFocusUp
497 * </pre>
498 * </p>
499 *
500 *
501 * <p>
502 * To get a particular view to take focus, call {@link #requestFocus()}.
503 * </p>
504 *
505 * <a name="TouchMode"></a>
506 * <h3>Touch Mode</h3>
507 * <p>
508 * When a user is navigating a user interface via directional keys such as a D-pad, it is
509 * necessary to give focus to actionable items such as buttons so the user can see
510 * what will take input.  If the device has touch capabilities, however, and the user
511 * begins interacting with the interface by touching it, it is no longer necessary to
512 * always highlight, or give focus to, a particular view.  This motivates a mode
513 * for interaction named 'touch mode'.
514 * </p>
515 * <p>
516 * For a touch capable device, once the user touches the screen, the device
517 * will enter touch mode.  From this point onward, only views for which
518 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
519 * Other views that are touchable, like buttons, will not take focus when touched; they will
520 * only fire the on click listeners.
521 * </p>
522 * <p>
523 * Any time a user hits a directional key, such as a D-pad direction, the view device will
524 * exit touch mode, and find a view to take focus, so that the user may resume interacting
525 * with the user interface without touching the screen again.
526 * </p>
527 * <p>
528 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
529 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
530 * </p>
531 *
532 * <a name="Scrolling"></a>
533 * <h3>Scrolling</h3>
534 * <p>
535 * The framework provides basic support for views that wish to internally
536 * scroll their content. This includes keeping track of the X and Y scroll
537 * offset as well as mechanisms for drawing scrollbars. See
538 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
539 * {@link #awakenScrollBars()} for more details.
540 * </p>
541 *
542 * <a name="Tags"></a>
543 * <h3>Tags</h3>
544 * <p>
545 * Unlike IDs, tags are not used to identify views. Tags are essentially an
546 * extra piece of information that can be associated with a view. They are most
547 * often used as a convenience to store data related to views in the views
548 * themselves rather than by putting them in a separate structure.
549 * </p>
550 *
551 * <a name="Properties"></a>
552 * <h3>Properties</h3>
553 * <p>
554 * The View class exposes an {@link #ALPHA} property, as well as several transform-related
555 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are
556 * available both in the {@link Property} form as well as in similarly-named setter/getter
557 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can
558 * be used to set persistent state associated with these rendering-related properties on the view.
559 * The properties and methods can also be used in conjunction with
560 * {@link android.animation.Animator Animator}-based animations, described more in the
561 * <a href="#Animation">Animation</a> section.
562 * </p>
563 *
564 * <a name="Animation"></a>
565 * <h3>Animation</h3>
566 * <p>
567 * Starting with Android 3.0, the preferred way of animating views is to use the
568 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based
569 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and
570 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0
571 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only
572 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class
573 * makes animating these View properties particularly easy and efficient.
574 * </p>
575 * <p>
576 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered.
577 * You can attach an {@link Animation} object to a view using
578 * {@link #setAnimation(Animation)} or
579 * {@link #startAnimation(Animation)}. The animation can alter the scale,
580 * rotation, translation and alpha of a view over time. If the animation is
581 * attached to a view that has children, the animation will affect the entire
582 * subtree rooted by that node. When an animation is started, the framework will
583 * take care of redrawing the appropriate views until the animation completes.
584 * </p>
585 *
586 * <a name="Security"></a>
587 * <h3>Security</h3>
588 * <p>
589 * Sometimes it is essential that an application be able to verify that an action
590 * is being performed with the full knowledge and consent of the user, such as
591 * granting a permission request, making a purchase or clicking on an advertisement.
592 * Unfortunately, a malicious application could try to spoof the user into
593 * performing these actions, unaware, by concealing the intended purpose of the view.
594 * As a remedy, the framework offers a touch filtering mechanism that can be used to
595 * improve the security of views that provide access to sensitive functionality.
596 * </p><p>
597 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
598 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
599 * will discard touches that are received whenever the view's window is obscured by
600 * another visible window.  As a result, the view will not receive touches whenever a
601 * toast, dialog or other window appears above the view's window.
602 * </p><p>
603 * For more fine-grained control over security, consider overriding the
604 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
605 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
606 * </p>
607 *
608 * @attr ref android.R.styleable#View_alpha
609 * @attr ref android.R.styleable#View_background
610 * @attr ref android.R.styleable#View_clickable
611 * @attr ref android.R.styleable#View_contentDescription
612 * @attr ref android.R.styleable#View_drawingCacheQuality
613 * @attr ref android.R.styleable#View_duplicateParentState
614 * @attr ref android.R.styleable#View_id
615 * @attr ref android.R.styleable#View_requiresFadingEdge
616 * @attr ref android.R.styleable#View_fadeScrollbars
617 * @attr ref android.R.styleable#View_fadingEdgeLength
618 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
619 * @attr ref android.R.styleable#View_fitsSystemWindows
620 * @attr ref android.R.styleable#View_isScrollContainer
621 * @attr ref android.R.styleable#View_focusable
622 * @attr ref android.R.styleable#View_focusableInTouchMode
623 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
624 * @attr ref android.R.styleable#View_keepScreenOn
625 * @attr ref android.R.styleable#View_layerType
626 * @attr ref android.R.styleable#View_layoutDirection
627 * @attr ref android.R.styleable#View_longClickable
628 * @attr ref android.R.styleable#View_minHeight
629 * @attr ref android.R.styleable#View_minWidth
630 * @attr ref android.R.styleable#View_nextFocusDown
631 * @attr ref android.R.styleable#View_nextFocusLeft
632 * @attr ref android.R.styleable#View_nextFocusRight
633 * @attr ref android.R.styleable#View_nextFocusUp
634 * @attr ref android.R.styleable#View_onClick
635 * @attr ref android.R.styleable#View_padding
636 * @attr ref android.R.styleable#View_paddingBottom
637 * @attr ref android.R.styleable#View_paddingLeft
638 * @attr ref android.R.styleable#View_paddingRight
639 * @attr ref android.R.styleable#View_paddingTop
640 * @attr ref android.R.styleable#View_paddingStart
641 * @attr ref android.R.styleable#View_paddingEnd
642 * @attr ref android.R.styleable#View_saveEnabled
643 * @attr ref android.R.styleable#View_rotation
644 * @attr ref android.R.styleable#View_rotationX
645 * @attr ref android.R.styleable#View_rotationY
646 * @attr ref android.R.styleable#View_scaleX
647 * @attr ref android.R.styleable#View_scaleY
648 * @attr ref android.R.styleable#View_scrollX
649 * @attr ref android.R.styleable#View_scrollY
650 * @attr ref android.R.styleable#View_scrollbarSize
651 * @attr ref android.R.styleable#View_scrollbarStyle
652 * @attr ref android.R.styleable#View_scrollbars
653 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
654 * @attr ref android.R.styleable#View_scrollbarFadeDuration
655 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
656 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
657 * @attr ref android.R.styleable#View_scrollbarThumbVertical
658 * @attr ref android.R.styleable#View_scrollbarTrackVertical
659 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
660 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
661 * @attr ref android.R.styleable#View_soundEffectsEnabled
662 * @attr ref android.R.styleable#View_tag
663 * @attr ref android.R.styleable#View_textAlignment
664 * @attr ref android.R.styleable#View_textDirection
665 * @attr ref android.R.styleable#View_transformPivotX
666 * @attr ref android.R.styleable#View_transformPivotY
667 * @attr ref android.R.styleable#View_translationX
668 * @attr ref android.R.styleable#View_translationY
669 * @attr ref android.R.styleable#View_visibility
670 *
671 * @see android.view.ViewGroup
672 */
673public class View implements Drawable.Callback, KeyEvent.Callback,
674        AccessibilityEventSource {
675    private static final boolean DBG = false;
676
677    /**
678     * The logging tag used by this class with android.util.Log.
679     */
680    protected static final String VIEW_LOG_TAG = "View";
681
682    /**
683     * When set to true, apps will draw debugging information about their layouts.
684     *
685     * @hide
686     */
687    public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout";
688
689    /**
690     * Used to mark a View that has no ID.
691     */
692    public static final int NO_ID = -1;
693
694    private static boolean sUseBrokenMakeMeasureSpec = false;
695
696    /**
697     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
698     * calling setFlags.
699     */
700    private static final int NOT_FOCUSABLE = 0x00000000;
701
702    /**
703     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
704     * setFlags.
705     */
706    private static final int FOCUSABLE = 0x00000001;
707
708    /**
709     * Mask for use with setFlags indicating bits used for focus.
710     */
711    private static final int FOCUSABLE_MASK = 0x00000001;
712
713    /**
714     * This view will adjust its padding to fit sytem windows (e.g. status bar)
715     */
716    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
717
718    /**
719     * This view is visible.
720     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
721     * android:visibility}.
722     */
723    public static final int VISIBLE = 0x00000000;
724
725    /**
726     * This view is invisible, but it still takes up space for layout purposes.
727     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
728     * android:visibility}.
729     */
730    public static final int INVISIBLE = 0x00000004;
731
732    /**
733     * This view is invisible, and it doesn't take any space for layout
734     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
735     * android:visibility}.
736     */
737    public static final int GONE = 0x00000008;
738
739    /**
740     * Mask for use with setFlags indicating bits used for visibility.
741     * {@hide}
742     */
743    static final int VISIBILITY_MASK = 0x0000000C;
744
745    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
746
747    /**
748     * This view is enabled. Interpretation varies by subclass.
749     * Use with ENABLED_MASK when calling setFlags.
750     * {@hide}
751     */
752    static final int ENABLED = 0x00000000;
753
754    /**
755     * This view is disabled. Interpretation varies by subclass.
756     * Use with ENABLED_MASK when calling setFlags.
757     * {@hide}
758     */
759    static final int DISABLED = 0x00000020;
760
761   /**
762    * Mask for use with setFlags indicating bits used for indicating whether
763    * this view is enabled
764    * {@hide}
765    */
766    static final int ENABLED_MASK = 0x00000020;
767
768    /**
769     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
770     * called and further optimizations will be performed. It is okay to have
771     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
772     * {@hide}
773     */
774    static final int WILL_NOT_DRAW = 0x00000080;
775
776    /**
777     * Mask for use with setFlags indicating bits used for indicating whether
778     * this view is will draw
779     * {@hide}
780     */
781    static final int DRAW_MASK = 0x00000080;
782
783    /**
784     * <p>This view doesn't show scrollbars.</p>
785     * {@hide}
786     */
787    static final int SCROLLBARS_NONE = 0x00000000;
788
789    /**
790     * <p>This view shows horizontal scrollbars.</p>
791     * {@hide}
792     */
793    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
794
795    /**
796     * <p>This view shows vertical scrollbars.</p>
797     * {@hide}
798     */
799    static final int SCROLLBARS_VERTICAL = 0x00000200;
800
801    /**
802     * <p>Mask for use with setFlags indicating bits used for indicating which
803     * scrollbars are enabled.</p>
804     * {@hide}
805     */
806    static final int SCROLLBARS_MASK = 0x00000300;
807
808    /**
809     * Indicates that the view should filter touches when its window is obscured.
810     * Refer to the class comments for more information about this security feature.
811     * {@hide}
812     */
813    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
814
815    /**
816     * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
817     * that they are optional and should be skipped if the window has
818     * requested system UI flags that ignore those insets for layout.
819     */
820    static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
821
822    /**
823     * <p>This view doesn't show fading edges.</p>
824     * {@hide}
825     */
826    static final int FADING_EDGE_NONE = 0x00000000;
827
828    /**
829     * <p>This view shows horizontal fading edges.</p>
830     * {@hide}
831     */
832    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
833
834    /**
835     * <p>This view shows vertical fading edges.</p>
836     * {@hide}
837     */
838    static final int FADING_EDGE_VERTICAL = 0x00002000;
839
840    /**
841     * <p>Mask for use with setFlags indicating bits used for indicating which
842     * fading edges are enabled.</p>
843     * {@hide}
844     */
845    static final int FADING_EDGE_MASK = 0x00003000;
846
847    /**
848     * <p>Indicates this view can be clicked. When clickable, a View reacts
849     * to clicks by notifying the OnClickListener.<p>
850     * {@hide}
851     */
852    static final int CLICKABLE = 0x00004000;
853
854    /**
855     * <p>Indicates this view is caching its drawing into a bitmap.</p>
856     * {@hide}
857     */
858    static final int DRAWING_CACHE_ENABLED = 0x00008000;
859
860    /**
861     * <p>Indicates that no icicle should be saved for this view.<p>
862     * {@hide}
863     */
864    static final int SAVE_DISABLED = 0x000010000;
865
866    /**
867     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
868     * property.</p>
869     * {@hide}
870     */
871    static final int SAVE_DISABLED_MASK = 0x000010000;
872
873    /**
874     * <p>Indicates that no drawing cache should ever be created for this view.<p>
875     * {@hide}
876     */
877    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
878
879    /**
880     * <p>Indicates this view can take / keep focus when int touch mode.</p>
881     * {@hide}
882     */
883    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
884
885    /**
886     * <p>Enables low quality mode for the drawing cache.</p>
887     */
888    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
889
890    /**
891     * <p>Enables high quality mode for the drawing cache.</p>
892     */
893    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
894
895    /**
896     * <p>Enables automatic quality mode for the drawing cache.</p>
897     */
898    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
899
900    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
901            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
902    };
903
904    /**
905     * <p>Mask for use with setFlags indicating bits used for the cache
906     * quality property.</p>
907     * {@hide}
908     */
909    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
910
911    /**
912     * <p>
913     * Indicates this view can be long clicked. When long clickable, a View
914     * reacts to long clicks by notifying the OnLongClickListener or showing a
915     * context menu.
916     * </p>
917     * {@hide}
918     */
919    static final int LONG_CLICKABLE = 0x00200000;
920
921    /**
922     * <p>Indicates that this view gets its drawable states from its direct parent
923     * and ignores its original internal states.</p>
924     *
925     * @hide
926     */
927    static final int DUPLICATE_PARENT_STATE = 0x00400000;
928
929    /**
930     * The scrollbar style to display the scrollbars inside the content area,
931     * without increasing the padding. The scrollbars will be overlaid with
932     * translucency on the view's content.
933     */
934    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
935
936    /**
937     * The scrollbar style to display the scrollbars inside the padded area,
938     * increasing the padding of the view. The scrollbars will not overlap the
939     * content area of the view.
940     */
941    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
942
943    /**
944     * The scrollbar style to display the scrollbars at the edge of the view,
945     * without increasing the padding. The scrollbars will be overlaid with
946     * translucency.
947     */
948    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
949
950    /**
951     * The scrollbar style to display the scrollbars at the edge of the view,
952     * increasing the padding of the view. The scrollbars will only overlap the
953     * background, if any.
954     */
955    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
956
957    /**
958     * Mask to check if the scrollbar style is overlay or inset.
959     * {@hide}
960     */
961    static final int SCROLLBARS_INSET_MASK = 0x01000000;
962
963    /**
964     * Mask to check if the scrollbar style is inside or outside.
965     * {@hide}
966     */
967    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
968
969    /**
970     * Mask for scrollbar style.
971     * {@hide}
972     */
973    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
974
975    /**
976     * View flag indicating that the screen should remain on while the
977     * window containing this view is visible to the user.  This effectively
978     * takes care of automatically setting the WindowManager's
979     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
980     */
981    public static final int KEEP_SCREEN_ON = 0x04000000;
982
983    /**
984     * View flag indicating whether this view should have sound effects enabled
985     * for events such as clicking and touching.
986     */
987    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
988
989    /**
990     * View flag indicating whether this view should have haptic feedback
991     * enabled for events such as long presses.
992     */
993    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
994
995    /**
996     * <p>Indicates that the view hierarchy should stop saving state when
997     * it reaches this view.  If state saving is initiated immediately at
998     * the view, it will be allowed.
999     * {@hide}
1000     */
1001    static final int PARENT_SAVE_DISABLED = 0x20000000;
1002
1003    /**
1004     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
1005     * {@hide}
1006     */
1007    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
1008
1009    /**
1010     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1011     * should add all focusable Views regardless if they are focusable in touch mode.
1012     */
1013    public static final int FOCUSABLES_ALL = 0x00000000;
1014
1015    /**
1016     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1017     * should add only Views focusable in touch mode.
1018     */
1019    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1020
1021    /**
1022     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1023     * item.
1024     */
1025    public static final int FOCUS_BACKWARD = 0x00000001;
1026
1027    /**
1028     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1029     * item.
1030     */
1031    public static final int FOCUS_FORWARD = 0x00000002;
1032
1033    /**
1034     * Use with {@link #focusSearch(int)}. Move focus to the left.
1035     */
1036    public static final int FOCUS_LEFT = 0x00000011;
1037
1038    /**
1039     * Use with {@link #focusSearch(int)}. Move focus up.
1040     */
1041    public static final int FOCUS_UP = 0x00000021;
1042
1043    /**
1044     * Use with {@link #focusSearch(int)}. Move focus to the right.
1045     */
1046    public static final int FOCUS_RIGHT = 0x00000042;
1047
1048    /**
1049     * Use with {@link #focusSearch(int)}. Move focus down.
1050     */
1051    public static final int FOCUS_DOWN = 0x00000082;
1052
1053    /**
1054     * Bits of {@link #getMeasuredWidthAndState()} and
1055     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1056     */
1057    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1058
1059    /**
1060     * Bits of {@link #getMeasuredWidthAndState()} and
1061     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1062     */
1063    public static final int MEASURED_STATE_MASK = 0xff000000;
1064
1065    /**
1066     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1067     * for functions that combine both width and height into a single int,
1068     * such as {@link #getMeasuredState()} and the childState argument of
1069     * {@link #resolveSizeAndState(int, int, int)}.
1070     */
1071    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1072
1073    /**
1074     * Bit of {@link #getMeasuredWidthAndState()} and
1075     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1076     * is smaller that the space the view would like to have.
1077     */
1078    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1079
1080    /**
1081     * Base View state sets
1082     */
1083    // Singles
1084    /**
1085     * Indicates the view has no states set. States are used with
1086     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1087     * view depending on its state.
1088     *
1089     * @see android.graphics.drawable.Drawable
1090     * @see #getDrawableState()
1091     */
1092    protected static final int[] EMPTY_STATE_SET;
1093    /**
1094     * Indicates the view is enabled. States are used with
1095     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1096     * view depending on its state.
1097     *
1098     * @see android.graphics.drawable.Drawable
1099     * @see #getDrawableState()
1100     */
1101    protected static final int[] ENABLED_STATE_SET;
1102    /**
1103     * Indicates the view is focused. States are used with
1104     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1105     * view depending on its state.
1106     *
1107     * @see android.graphics.drawable.Drawable
1108     * @see #getDrawableState()
1109     */
1110    protected static final int[] FOCUSED_STATE_SET;
1111    /**
1112     * Indicates the view is selected. States are used with
1113     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1114     * view depending on its state.
1115     *
1116     * @see android.graphics.drawable.Drawable
1117     * @see #getDrawableState()
1118     */
1119    protected static final int[] SELECTED_STATE_SET;
1120    /**
1121     * Indicates the view is pressed. States are used with
1122     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1123     * view depending on its state.
1124     *
1125     * @see android.graphics.drawable.Drawable
1126     * @see #getDrawableState()
1127     */
1128    protected static final int[] PRESSED_STATE_SET;
1129    /**
1130     * Indicates the view's window has focus. States are used with
1131     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1132     * view depending on its state.
1133     *
1134     * @see android.graphics.drawable.Drawable
1135     * @see #getDrawableState()
1136     */
1137    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1138    // Doubles
1139    /**
1140     * Indicates the view is enabled and has the focus.
1141     *
1142     * @see #ENABLED_STATE_SET
1143     * @see #FOCUSED_STATE_SET
1144     */
1145    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1146    /**
1147     * Indicates the view is enabled and selected.
1148     *
1149     * @see #ENABLED_STATE_SET
1150     * @see #SELECTED_STATE_SET
1151     */
1152    protected static final int[] ENABLED_SELECTED_STATE_SET;
1153    /**
1154     * Indicates the view is enabled and that its window has focus.
1155     *
1156     * @see #ENABLED_STATE_SET
1157     * @see #WINDOW_FOCUSED_STATE_SET
1158     */
1159    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1160    /**
1161     * Indicates the view is focused and selected.
1162     *
1163     * @see #FOCUSED_STATE_SET
1164     * @see #SELECTED_STATE_SET
1165     */
1166    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1167    /**
1168     * Indicates the view has the focus and that its window has the focus.
1169     *
1170     * @see #FOCUSED_STATE_SET
1171     * @see #WINDOW_FOCUSED_STATE_SET
1172     */
1173    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1174    /**
1175     * Indicates the view is selected and that its window has the focus.
1176     *
1177     * @see #SELECTED_STATE_SET
1178     * @see #WINDOW_FOCUSED_STATE_SET
1179     */
1180    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1181    // Triples
1182    /**
1183     * Indicates the view is enabled, focused and selected.
1184     *
1185     * @see #ENABLED_STATE_SET
1186     * @see #FOCUSED_STATE_SET
1187     * @see #SELECTED_STATE_SET
1188     */
1189    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1190    /**
1191     * Indicates the view is enabled, focused and its window has the focus.
1192     *
1193     * @see #ENABLED_STATE_SET
1194     * @see #FOCUSED_STATE_SET
1195     * @see #WINDOW_FOCUSED_STATE_SET
1196     */
1197    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1198    /**
1199     * Indicates the view is enabled, selected and its window has the focus.
1200     *
1201     * @see #ENABLED_STATE_SET
1202     * @see #SELECTED_STATE_SET
1203     * @see #WINDOW_FOCUSED_STATE_SET
1204     */
1205    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1206    /**
1207     * Indicates the view is focused, selected and its window has the focus.
1208     *
1209     * @see #FOCUSED_STATE_SET
1210     * @see #SELECTED_STATE_SET
1211     * @see #WINDOW_FOCUSED_STATE_SET
1212     */
1213    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1214    /**
1215     * Indicates the view is enabled, focused, selected and its window
1216     * has the focus.
1217     *
1218     * @see #ENABLED_STATE_SET
1219     * @see #FOCUSED_STATE_SET
1220     * @see #SELECTED_STATE_SET
1221     * @see #WINDOW_FOCUSED_STATE_SET
1222     */
1223    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1224    /**
1225     * Indicates the view is pressed and its window has the focus.
1226     *
1227     * @see #PRESSED_STATE_SET
1228     * @see #WINDOW_FOCUSED_STATE_SET
1229     */
1230    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1231    /**
1232     * Indicates the view is pressed and selected.
1233     *
1234     * @see #PRESSED_STATE_SET
1235     * @see #SELECTED_STATE_SET
1236     */
1237    protected static final int[] PRESSED_SELECTED_STATE_SET;
1238    /**
1239     * Indicates the view is pressed, selected and its window has the focus.
1240     *
1241     * @see #PRESSED_STATE_SET
1242     * @see #SELECTED_STATE_SET
1243     * @see #WINDOW_FOCUSED_STATE_SET
1244     */
1245    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1246    /**
1247     * Indicates the view is pressed and focused.
1248     *
1249     * @see #PRESSED_STATE_SET
1250     * @see #FOCUSED_STATE_SET
1251     */
1252    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1253    /**
1254     * Indicates the view is pressed, focused and its window has the focus.
1255     *
1256     * @see #PRESSED_STATE_SET
1257     * @see #FOCUSED_STATE_SET
1258     * @see #WINDOW_FOCUSED_STATE_SET
1259     */
1260    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1261    /**
1262     * Indicates the view is pressed, focused and selected.
1263     *
1264     * @see #PRESSED_STATE_SET
1265     * @see #SELECTED_STATE_SET
1266     * @see #FOCUSED_STATE_SET
1267     */
1268    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1269    /**
1270     * Indicates the view is pressed, focused, selected and its window has the focus.
1271     *
1272     * @see #PRESSED_STATE_SET
1273     * @see #FOCUSED_STATE_SET
1274     * @see #SELECTED_STATE_SET
1275     * @see #WINDOW_FOCUSED_STATE_SET
1276     */
1277    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1278    /**
1279     * Indicates the view is pressed and enabled.
1280     *
1281     * @see #PRESSED_STATE_SET
1282     * @see #ENABLED_STATE_SET
1283     */
1284    protected static final int[] PRESSED_ENABLED_STATE_SET;
1285    /**
1286     * Indicates the view is pressed, enabled and its window has the focus.
1287     *
1288     * @see #PRESSED_STATE_SET
1289     * @see #ENABLED_STATE_SET
1290     * @see #WINDOW_FOCUSED_STATE_SET
1291     */
1292    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1293    /**
1294     * Indicates the view is pressed, enabled and selected.
1295     *
1296     * @see #PRESSED_STATE_SET
1297     * @see #ENABLED_STATE_SET
1298     * @see #SELECTED_STATE_SET
1299     */
1300    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1301    /**
1302     * Indicates the view is pressed, enabled, selected and its window has the
1303     * focus.
1304     *
1305     * @see #PRESSED_STATE_SET
1306     * @see #ENABLED_STATE_SET
1307     * @see #SELECTED_STATE_SET
1308     * @see #WINDOW_FOCUSED_STATE_SET
1309     */
1310    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1311    /**
1312     * Indicates the view is pressed, enabled and focused.
1313     *
1314     * @see #PRESSED_STATE_SET
1315     * @see #ENABLED_STATE_SET
1316     * @see #FOCUSED_STATE_SET
1317     */
1318    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1319    /**
1320     * Indicates the view is pressed, enabled, focused and its window has the
1321     * focus.
1322     *
1323     * @see #PRESSED_STATE_SET
1324     * @see #ENABLED_STATE_SET
1325     * @see #FOCUSED_STATE_SET
1326     * @see #WINDOW_FOCUSED_STATE_SET
1327     */
1328    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1329    /**
1330     * Indicates the view is pressed, enabled, focused and selected.
1331     *
1332     * @see #PRESSED_STATE_SET
1333     * @see #ENABLED_STATE_SET
1334     * @see #SELECTED_STATE_SET
1335     * @see #FOCUSED_STATE_SET
1336     */
1337    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1338    /**
1339     * Indicates the view is pressed, enabled, focused, selected and its window
1340     * has the focus.
1341     *
1342     * @see #PRESSED_STATE_SET
1343     * @see #ENABLED_STATE_SET
1344     * @see #SELECTED_STATE_SET
1345     * @see #FOCUSED_STATE_SET
1346     * @see #WINDOW_FOCUSED_STATE_SET
1347     */
1348    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1349
1350    /**
1351     * The order here is very important to {@link #getDrawableState()}
1352     */
1353    private static final int[][] VIEW_STATE_SETS;
1354
1355    static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1356    static final int VIEW_STATE_SELECTED = 1 << 1;
1357    static final int VIEW_STATE_FOCUSED = 1 << 2;
1358    static final int VIEW_STATE_ENABLED = 1 << 3;
1359    static final int VIEW_STATE_PRESSED = 1 << 4;
1360    static final int VIEW_STATE_ACTIVATED = 1 << 5;
1361    static final int VIEW_STATE_ACCELERATED = 1 << 6;
1362    static final int VIEW_STATE_HOVERED = 1 << 7;
1363    static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8;
1364    static final int VIEW_STATE_DRAG_HOVERED = 1 << 9;
1365
1366    static final int[] VIEW_STATE_IDS = new int[] {
1367        R.attr.state_window_focused,    VIEW_STATE_WINDOW_FOCUSED,
1368        R.attr.state_selected,          VIEW_STATE_SELECTED,
1369        R.attr.state_focused,           VIEW_STATE_FOCUSED,
1370        R.attr.state_enabled,           VIEW_STATE_ENABLED,
1371        R.attr.state_pressed,           VIEW_STATE_PRESSED,
1372        R.attr.state_activated,         VIEW_STATE_ACTIVATED,
1373        R.attr.state_accelerated,       VIEW_STATE_ACCELERATED,
1374        R.attr.state_hovered,           VIEW_STATE_HOVERED,
1375        R.attr.state_drag_can_accept,   VIEW_STATE_DRAG_CAN_ACCEPT,
1376        R.attr.state_drag_hovered,      VIEW_STATE_DRAG_HOVERED
1377    };
1378
1379    static {
1380        if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1381            throw new IllegalStateException(
1382                    "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1383        }
1384        int[] orderedIds = new int[VIEW_STATE_IDS.length];
1385        for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
1386            int viewState = R.styleable.ViewDrawableStates[i];
1387            for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
1388                if (VIEW_STATE_IDS[j] == viewState) {
1389                    orderedIds[i * 2] = viewState;
1390                    orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
1391                }
1392            }
1393        }
1394        final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1395        VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1396        for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
1397            int numBits = Integer.bitCount(i);
1398            int[] set = new int[numBits];
1399            int pos = 0;
1400            for (int j = 0; j < orderedIds.length; j += 2) {
1401                if ((i & orderedIds[j+1]) != 0) {
1402                    set[pos++] = orderedIds[j];
1403                }
1404            }
1405            VIEW_STATE_SETS[i] = set;
1406        }
1407
1408        EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1409        WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1410        SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1411        SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1412                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1413        FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1414        FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1415                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1416        FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1417                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1418        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1419                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1420                | VIEW_STATE_FOCUSED];
1421        ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1422        ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1423                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1424        ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1425                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1426        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1427                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1428                | VIEW_STATE_ENABLED];
1429        ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1430                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1431        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1432                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1433                | VIEW_STATE_ENABLED];
1434        ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1435                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1436                | VIEW_STATE_ENABLED];
1437        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1438                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1439                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1440
1441        PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1442        PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1443                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1444        PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1445                VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1446        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1447                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1448                | VIEW_STATE_PRESSED];
1449        PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1450                VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1451        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1452                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1453                | VIEW_STATE_PRESSED];
1454        PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1455                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1456                | VIEW_STATE_PRESSED];
1457        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1458                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1459                | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1460        PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1461                VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1462        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1463                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1464                | VIEW_STATE_PRESSED];
1465        PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1466                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1467                | VIEW_STATE_PRESSED];
1468        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1469                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1470                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1471        PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1472                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1473                | VIEW_STATE_PRESSED];
1474        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1475                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1476                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1477        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1478                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1479                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1480        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1481                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1482                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1483                | VIEW_STATE_PRESSED];
1484    }
1485
1486    /**
1487     * Accessibility event types that are dispatched for text population.
1488     */
1489    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1490            AccessibilityEvent.TYPE_VIEW_CLICKED
1491            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1492            | AccessibilityEvent.TYPE_VIEW_SELECTED
1493            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1494            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1495            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1496            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1497            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1498            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
1499            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
1500            | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY;
1501
1502    /**
1503     * Temporary Rect currently for use in setBackground().  This will probably
1504     * be extended in the future to hold our own class with more than just
1505     * a Rect. :)
1506     */
1507    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1508
1509    /**
1510     * Map used to store views' tags.
1511     */
1512    private SparseArray<Object> mKeyedTags;
1513
1514    /**
1515     * The next available accessibility id.
1516     */
1517    private static int sNextAccessibilityViewId;
1518
1519    /**
1520     * The animation currently associated with this view.
1521     * @hide
1522     */
1523    protected Animation mCurrentAnimation = null;
1524
1525    /**
1526     * Width as measured during measure pass.
1527     * {@hide}
1528     */
1529    @ViewDebug.ExportedProperty(category = "measurement")
1530    int mMeasuredWidth;
1531
1532    /**
1533     * Height as measured during measure pass.
1534     * {@hide}
1535     */
1536    @ViewDebug.ExportedProperty(category = "measurement")
1537    int mMeasuredHeight;
1538
1539    /**
1540     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1541     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1542     * its display list. This flag, used only when hw accelerated, allows us to clear the
1543     * flag while retaining this information until it's needed (at getDisplayList() time and
1544     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1545     *
1546     * {@hide}
1547     */
1548    boolean mRecreateDisplayList = false;
1549
1550    /**
1551     * The view's identifier.
1552     * {@hide}
1553     *
1554     * @see #setId(int)
1555     * @see #getId()
1556     */
1557    @ViewDebug.ExportedProperty(resolveId = true)
1558    int mID = NO_ID;
1559
1560    /**
1561     * The stable ID of this view for accessibility purposes.
1562     */
1563    int mAccessibilityViewId = NO_ID;
1564
1565    private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
1566
1567    SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent;
1568
1569    /**
1570     * The view's tag.
1571     * {@hide}
1572     *
1573     * @see #setTag(Object)
1574     * @see #getTag()
1575     */
1576    protected Object mTag;
1577
1578    private Scene mCurrentScene = null;
1579
1580    // for mPrivateFlags:
1581    /** {@hide} */
1582    static final int PFLAG_WANTS_FOCUS                 = 0x00000001;
1583    /** {@hide} */
1584    static final int PFLAG_FOCUSED                     = 0x00000002;
1585    /** {@hide} */
1586    static final int PFLAG_SELECTED                    = 0x00000004;
1587    /** {@hide} */
1588    static final int PFLAG_IS_ROOT_NAMESPACE           = 0x00000008;
1589    /** {@hide} */
1590    static final int PFLAG_HAS_BOUNDS                  = 0x00000010;
1591    /** {@hide} */
1592    static final int PFLAG_DRAWN                       = 0x00000020;
1593    /**
1594     * When this flag is set, this view is running an animation on behalf of its
1595     * children and should therefore not cancel invalidate requests, even if they
1596     * lie outside of this view's bounds.
1597     *
1598     * {@hide}
1599     */
1600    static final int PFLAG_DRAW_ANIMATION              = 0x00000040;
1601    /** {@hide} */
1602    static final int PFLAG_SKIP_DRAW                   = 0x00000080;
1603    /** {@hide} */
1604    static final int PFLAG_ONLY_DRAWS_BACKGROUND       = 0x00000100;
1605    /** {@hide} */
1606    static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1607    /** {@hide} */
1608    static final int PFLAG_DRAWABLE_STATE_DIRTY        = 0x00000400;
1609    /** {@hide} */
1610    static final int PFLAG_MEASURED_DIMENSION_SET      = 0x00000800;
1611    /** {@hide} */
1612    static final int PFLAG_FORCE_LAYOUT                = 0x00001000;
1613    /** {@hide} */
1614    static final int PFLAG_LAYOUT_REQUIRED             = 0x00002000;
1615
1616    private static final int PFLAG_PRESSED             = 0x00004000;
1617
1618    /** {@hide} */
1619    static final int PFLAG_DRAWING_CACHE_VALID         = 0x00008000;
1620    /**
1621     * Flag used to indicate that this view should be drawn once more (and only once
1622     * more) after its animation has completed.
1623     * {@hide}
1624     */
1625    static final int PFLAG_ANIMATION_STARTED           = 0x00010000;
1626
1627    private static final int PFLAG_SAVE_STATE_CALLED   = 0x00020000;
1628
1629    /**
1630     * Indicates that the View returned true when onSetAlpha() was called and that
1631     * the alpha must be restored.
1632     * {@hide}
1633     */
1634    static final int PFLAG_ALPHA_SET                   = 0x00040000;
1635
1636    /**
1637     * Set by {@link #setScrollContainer(boolean)}.
1638     */
1639    static final int PFLAG_SCROLL_CONTAINER            = 0x00080000;
1640
1641    /**
1642     * Set by {@link #setScrollContainer(boolean)}.
1643     */
1644    static final int PFLAG_SCROLL_CONTAINER_ADDED      = 0x00100000;
1645
1646    /**
1647     * View flag indicating whether this view was invalidated (fully or partially.)
1648     *
1649     * @hide
1650     */
1651    static final int PFLAG_DIRTY                       = 0x00200000;
1652
1653    /**
1654     * View flag indicating whether this view was invalidated by an opaque
1655     * invalidate request.
1656     *
1657     * @hide
1658     */
1659    static final int PFLAG_DIRTY_OPAQUE                = 0x00400000;
1660
1661    /**
1662     * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}.
1663     *
1664     * @hide
1665     */
1666    static final int PFLAG_DIRTY_MASK                  = 0x00600000;
1667
1668    /**
1669     * Indicates whether the background is opaque.
1670     *
1671     * @hide
1672     */
1673    static final int PFLAG_OPAQUE_BACKGROUND           = 0x00800000;
1674
1675    /**
1676     * Indicates whether the scrollbars are opaque.
1677     *
1678     * @hide
1679     */
1680    static final int PFLAG_OPAQUE_SCROLLBARS           = 0x01000000;
1681
1682    /**
1683     * Indicates whether the view is opaque.
1684     *
1685     * @hide
1686     */
1687    static final int PFLAG_OPAQUE_MASK                 = 0x01800000;
1688
1689    /**
1690     * Indicates a prepressed state;
1691     * the short time between ACTION_DOWN and recognizing
1692     * a 'real' press. Prepressed is used to recognize quick taps
1693     * even when they are shorter than ViewConfiguration.getTapTimeout().
1694     *
1695     * @hide
1696     */
1697    private static final int PFLAG_PREPRESSED          = 0x02000000;
1698
1699    /**
1700     * Indicates whether the view is temporarily detached.
1701     *
1702     * @hide
1703     */
1704    static final int PFLAG_CANCEL_NEXT_UP_EVENT        = 0x04000000;
1705
1706    /**
1707     * Indicates that we should awaken scroll bars once attached
1708     *
1709     * @hide
1710     */
1711    private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1712
1713    /**
1714     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1715     * @hide
1716     */
1717    private static final int PFLAG_HOVERED             = 0x10000000;
1718
1719    /**
1720     * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1721     * for transform operations
1722     *
1723     * @hide
1724     */
1725    private static final int PFLAG_PIVOT_EXPLICITLY_SET = 0x20000000;
1726
1727    /** {@hide} */
1728    static final int PFLAG_ACTIVATED                   = 0x40000000;
1729
1730    /**
1731     * Indicates that this view was specifically invalidated, not just dirtied because some
1732     * child view was invalidated. The flag is used to determine when we need to recreate
1733     * a view's display list (as opposed to just returning a reference to its existing
1734     * display list).
1735     *
1736     * @hide
1737     */
1738    static final int PFLAG_INVALIDATED                 = 0x80000000;
1739
1740    /**
1741     * Masks for mPrivateFlags2, as generated by dumpFlags():
1742     *
1743     * -------|-------|-------|-------|
1744     *                                  PFLAG2_TEXT_ALIGNMENT_FLAGS[0]
1745     *                                  PFLAG2_TEXT_DIRECTION_FLAGS[0]
1746     *                                1 PFLAG2_DRAG_CAN_ACCEPT
1747     *                               1  PFLAG2_DRAG_HOVERED
1748     *                               1  PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT
1749     *                              11  PFLAG2_TEXT_DIRECTION_MASK_SHIFT
1750     *                             1 1  PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT
1751     *                             11   PFLAG2_LAYOUT_DIRECTION_MASK
1752     *                             11 1 PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
1753     *                            1     PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL
1754     *                            1   1 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT
1755     *                            1 1   PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT
1756     *                           1      PFLAG2_LAYOUT_DIRECTION_RESOLVED
1757     *                           11     PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK
1758     *                          1       PFLAG2_TEXT_DIRECTION_FLAGS[1]
1759     *                         1        PFLAG2_TEXT_DIRECTION_FLAGS[2]
1760     *                         11       PFLAG2_TEXT_DIRECTION_FLAGS[3]
1761     *                        1         PFLAG2_TEXT_DIRECTION_FLAGS[4]
1762     *                        1 1       PFLAG2_TEXT_DIRECTION_FLAGS[5]
1763     *                        111       PFLAG2_TEXT_DIRECTION_MASK
1764     *                       1          PFLAG2_TEXT_DIRECTION_RESOLVED
1765     *                      1           PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT
1766     *                    111           PFLAG2_TEXT_DIRECTION_RESOLVED_MASK
1767     *                   1              PFLAG2_TEXT_ALIGNMENT_FLAGS[1]
1768     *                  1               PFLAG2_TEXT_ALIGNMENT_FLAGS[2]
1769     *                  11              PFLAG2_TEXT_ALIGNMENT_FLAGS[3]
1770     *                 1                PFLAG2_TEXT_ALIGNMENT_FLAGS[4]
1771     *                 1 1              PFLAG2_TEXT_ALIGNMENT_FLAGS[5]
1772     *                 11               PFLAG2_TEXT_ALIGNMENT_FLAGS[6]
1773     *                 111              PFLAG2_TEXT_ALIGNMENT_MASK
1774     *                1                 PFLAG2_TEXT_ALIGNMENT_RESOLVED
1775     *               1                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT
1776     *             111                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK
1777     *           11                     PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK
1778     *          1                       PFLAG2_HAS_TRANSIENT_STATE
1779     *      1                           PFLAG2_ACCESSIBILITY_FOCUSED
1780     *     1                            PFLAG2_ACCESSIBILITY_STATE_CHANGED
1781     *    1                             PFLAG2_VIEW_QUICK_REJECTED
1782     *   1                              PFLAG2_PADDING_RESOLVED
1783     * -------|-------|-------|-------|
1784     */
1785
1786    /**
1787     * Indicates that this view has reported that it can accept the current drag's content.
1788     * Cleared when the drag operation concludes.
1789     * @hide
1790     */
1791    static final int PFLAG2_DRAG_CAN_ACCEPT            = 0x00000001;
1792
1793    /**
1794     * Indicates that this view is currently directly under the drag location in a
1795     * drag-and-drop operation involving content that it can accept.  Cleared when
1796     * the drag exits the view, or when the drag operation concludes.
1797     * @hide
1798     */
1799    static final int PFLAG2_DRAG_HOVERED               = 0x00000002;
1800
1801    /**
1802     * Horizontal layout direction of this view is from Left to Right.
1803     * Use with {@link #setLayoutDirection}.
1804     */
1805    public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR;
1806
1807    /**
1808     * Horizontal layout direction of this view is from Right to Left.
1809     * Use with {@link #setLayoutDirection}.
1810     */
1811    public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL;
1812
1813    /**
1814     * Horizontal layout direction of this view is inherited from its parent.
1815     * Use with {@link #setLayoutDirection}.
1816     */
1817    public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT;
1818
1819    /**
1820     * Horizontal layout direction of this view is from deduced from the default language
1821     * script for the locale. Use with {@link #setLayoutDirection}.
1822     */
1823    public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE;
1824
1825    /**
1826     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1827     * @hide
1828     */
1829    static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2;
1830
1831    /**
1832     * Mask for use with private flags indicating bits used for horizontal layout direction.
1833     * @hide
1834     */
1835    static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1836
1837    /**
1838     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
1839     * right-to-left direction.
1840     * @hide
1841     */
1842    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1843
1844    /**
1845     * Indicates whether the view horizontal layout direction has been resolved.
1846     * @hide
1847     */
1848    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1849
1850    /**
1851     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
1852     * @hide
1853     */
1854    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C
1855            << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1856
1857    /*
1858     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
1859     * flag value.
1860     * @hide
1861     */
1862    private static final int[] LAYOUT_DIRECTION_FLAGS = {
1863            LAYOUT_DIRECTION_LTR,
1864            LAYOUT_DIRECTION_RTL,
1865            LAYOUT_DIRECTION_INHERIT,
1866            LAYOUT_DIRECTION_LOCALE
1867    };
1868
1869    /**
1870     * Default horizontal layout direction.
1871     */
1872    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
1873
1874    /**
1875     * Default horizontal layout direction.
1876     * @hide
1877     */
1878    static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR;
1879
1880    /**
1881     * Indicates that the view is tracking some sort of transient state
1882     * that the app should not need to be aware of, but that the framework
1883     * should take special care to preserve.
1884     *
1885     * @hide
1886     */
1887    static final int PFLAG2_HAS_TRANSIENT_STATE = 0x1 << 22;
1888
1889    /**
1890     * Text direction is inherited thru {@link ViewGroup}
1891     */
1892    public static final int TEXT_DIRECTION_INHERIT = 0;
1893
1894    /**
1895     * Text direction is using "first strong algorithm". The first strong directional character
1896     * determines the paragraph direction. If there is no strong directional character, the
1897     * paragraph direction is the view's resolved layout direction.
1898     */
1899    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
1900
1901    /**
1902     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
1903     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
1904     * If there are neither, the paragraph direction is the view's resolved layout direction.
1905     */
1906    public static final int TEXT_DIRECTION_ANY_RTL = 2;
1907
1908    /**
1909     * Text direction is forced to LTR.
1910     */
1911    public static final int TEXT_DIRECTION_LTR = 3;
1912
1913    /**
1914     * Text direction is forced to RTL.
1915     */
1916    public static final int TEXT_DIRECTION_RTL = 4;
1917
1918    /**
1919     * Text direction is coming from the system Locale.
1920     */
1921    public static final int TEXT_DIRECTION_LOCALE = 5;
1922
1923    /**
1924     * Default text direction is inherited
1925     */
1926    private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
1927
1928    /**
1929     * Default resolved text direction
1930     * @hide
1931     */
1932    static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG;
1933
1934    /**
1935     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
1936     * @hide
1937     */
1938    static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6;
1939
1940    /**
1941     * Mask for use with private flags indicating bits used for text direction.
1942     * @hide
1943     */
1944    static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007
1945            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
1946
1947    /**
1948     * Array of text direction flags for mapping attribute "textDirection" to correct
1949     * flag value.
1950     * @hide
1951     */
1952    private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = {
1953            TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1954            TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1955            TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1956            TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1957            TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1958            TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT
1959    };
1960
1961    /**
1962     * Indicates whether the view text direction has been resolved.
1963     * @hide
1964     */
1965    static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008
1966            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
1967
1968    /**
1969     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1970     * @hide
1971     */
1972    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
1973
1974    /**
1975     * Mask for use with private flags indicating bits used for resolved text direction.
1976     * @hide
1977     */
1978    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007
1979            << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
1980
1981    /**
1982     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
1983     * @hide
1984     */
1985    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT =
1986            TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
1987
1988    /*
1989     * Default text alignment. The text alignment of this View is inherited from its parent.
1990     * Use with {@link #setTextAlignment(int)}
1991     */
1992    public static final int TEXT_ALIGNMENT_INHERIT = 0;
1993
1994    /**
1995     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
1996     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
1997     *
1998     * Use with {@link #setTextAlignment(int)}
1999     */
2000    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
2001
2002    /**
2003     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
2004     *
2005     * Use with {@link #setTextAlignment(int)}
2006     */
2007    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
2008
2009    /**
2010     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
2011     *
2012     * Use with {@link #setTextAlignment(int)}
2013     */
2014    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
2015
2016    /**
2017     * Center the paragraph, e.g. ALIGN_CENTER.
2018     *
2019     * Use with {@link #setTextAlignment(int)}
2020     */
2021    public static final int TEXT_ALIGNMENT_CENTER = 4;
2022
2023    /**
2024     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
2025     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
2026     *
2027     * Use with {@link #setTextAlignment(int)}
2028     */
2029    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
2030
2031    /**
2032     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
2033     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
2034     *
2035     * Use with {@link #setTextAlignment(int)}
2036     */
2037    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
2038
2039    /**
2040     * Default text alignment is inherited
2041     */
2042    private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2043
2044    /**
2045     * Default resolved text alignment
2046     * @hide
2047     */
2048    static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2049
2050    /**
2051      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2052      * @hide
2053      */
2054    static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13;
2055
2056    /**
2057      * Mask for use with private flags indicating bits used for text alignment.
2058      * @hide
2059      */
2060    static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2061
2062    /**
2063     * Array of text direction flags for mapping attribute "textAlignment" to correct
2064     * flag value.
2065     * @hide
2066     */
2067    private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = {
2068            TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2069            TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2070            TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2071            TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2072            TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2073            TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2074            TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
2075    };
2076
2077    /**
2078     * Indicates whether the view text alignment has been resolved.
2079     * @hide
2080     */
2081    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2082
2083    /**
2084     * Bit shift to get the resolved text alignment.
2085     * @hide
2086     */
2087    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2088
2089    /**
2090     * Mask for use with private flags indicating bits used for text alignment.
2091     * @hide
2092     */
2093    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007
2094            << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2095
2096    /**
2097     * Indicates whether if the view text alignment has been resolved to gravity
2098     */
2099    private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2100            TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2101
2102    // Accessiblity constants for mPrivateFlags2
2103
2104    /**
2105     * Shift for the bits in {@link #mPrivateFlags2} related to the
2106     * "importantForAccessibility" attribute.
2107     */
2108    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2109
2110    /**
2111     * Automatically determine whether a view is important for accessibility.
2112     */
2113    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2114
2115    /**
2116     * The view is important for accessibility.
2117     */
2118    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2119
2120    /**
2121     * The view is not important for accessibility.
2122     */
2123    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2124
2125    /**
2126     * The default whether the view is important for accessibility.
2127     */
2128    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2129
2130    /**
2131     * Mask for obtainig the bits which specify how to determine
2132     * whether a view is important for accessibility.
2133     */
2134    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2135        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO)
2136        << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2137
2138    /**
2139     * Flag indicating whether a view has accessibility focus.
2140     */
2141    static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000;
2142
2143    /**
2144     * Flag whether the accessibility state of the subtree rooted at this view changed.
2145     */
2146    static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000;
2147
2148    /**
2149     * Flag indicating whether a view failed the quickReject() check in draw(). This condition
2150     * is used to check whether later changes to the view's transform should invalidate the
2151     * view to force the quickReject test to run again.
2152     */
2153    static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000;
2154
2155    /**
2156     * Flag indicating that start/end padding has been resolved into left/right padding
2157     * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()}
2158     * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved
2159     * during measurement. In some special cases this is required such as when an adapter-based
2160     * view measures prospective children without attaching them to a window.
2161     */
2162    static final int PFLAG2_PADDING_RESOLVED = 0x20000000;
2163
2164    /**
2165     * Flag indicating that the start/end drawables has been resolved into left/right ones.
2166     */
2167    static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000;
2168
2169    /**
2170     * Group of bits indicating that RTL properties resolution is done.
2171     */
2172    static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED |
2173            PFLAG2_TEXT_DIRECTION_RESOLVED |
2174            PFLAG2_TEXT_ALIGNMENT_RESOLVED |
2175            PFLAG2_PADDING_RESOLVED |
2176            PFLAG2_DRAWABLE_RESOLVED;
2177
2178    // There are a couple of flags left in mPrivateFlags2
2179
2180    /* End of masks for mPrivateFlags2 */
2181
2182    /* Masks for mPrivateFlags3 */
2183
2184    /**
2185     * Flag indicating that view has a transform animation set on it. This is used to track whether
2186     * an animation is cleared between successive frames, in order to tell the associated
2187     * DisplayList to clear its animation matrix.
2188     */
2189    static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1;
2190
2191    /**
2192     * Flag indicating that view has an alpha animation set on it. This is used to track whether an
2193     * animation is cleared between successive frames, in order to tell the associated
2194     * DisplayList to restore its alpha value.
2195     */
2196    static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2;
2197
2198    /**
2199     * Flag indicating that the view has been through at least one layout since it
2200     * was last attached to a window.
2201     */
2202    static final int PFLAG3_IS_LAID_OUT = 0x4;
2203
2204    /**
2205     * Flag indicating that a call to measure() was skipped and should be done
2206     * instead when layout() is invoked.
2207     */
2208    static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8;
2209
2210
2211    /* End of masks for mPrivateFlags3 */
2212
2213    static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED;
2214
2215    /**
2216     * Always allow a user to over-scroll this view, provided it is a
2217     * view that can scroll.
2218     *
2219     * @see #getOverScrollMode()
2220     * @see #setOverScrollMode(int)
2221     */
2222    public static final int OVER_SCROLL_ALWAYS = 0;
2223
2224    /**
2225     * Allow a user to over-scroll this view only if the content is large
2226     * enough to meaningfully scroll, provided it is a view that can scroll.
2227     *
2228     * @see #getOverScrollMode()
2229     * @see #setOverScrollMode(int)
2230     */
2231    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2232
2233    /**
2234     * Never allow a user to over-scroll this view.
2235     *
2236     * @see #getOverScrollMode()
2237     * @see #setOverScrollMode(int)
2238     */
2239    public static final int OVER_SCROLL_NEVER = 2;
2240
2241    /**
2242     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2243     * requested the system UI (status bar) to be visible (the default).
2244     *
2245     * @see #setSystemUiVisibility(int)
2246     */
2247    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2248
2249    /**
2250     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2251     * system UI to enter an unobtrusive "low profile" mode.
2252     *
2253     * <p>This is for use in games, book readers, video players, or any other
2254     * "immersive" application where the usual system chrome is deemed too distracting.
2255     *
2256     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2257     *
2258     * @see #setSystemUiVisibility(int)
2259     */
2260    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2261
2262    /**
2263     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2264     * system navigation be temporarily hidden.
2265     *
2266     * <p>This is an even less obtrusive state than that called for by
2267     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2268     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2269     * those to disappear. This is useful (in conjunction with the
2270     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2271     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2272     * window flags) for displaying content using every last pixel on the display.
2273     *
2274     * <p>There is a limitation: because navigation controls are so important, the least user
2275     * interaction will cause them to reappear immediately.  When this happens, both
2276     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2277     * so that both elements reappear at the same time.
2278     *
2279     * @see #setSystemUiVisibility(int)
2280     */
2281    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2282
2283    /**
2284     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2285     * into the normal fullscreen mode so that its content can take over the screen
2286     * while still allowing the user to interact with the application.
2287     *
2288     * <p>This has the same visual effect as
2289     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2290     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2291     * meaning that non-critical screen decorations (such as the status bar) will be
2292     * hidden while the user is in the View's window, focusing the experience on
2293     * that content.  Unlike the window flag, if you are using ActionBar in
2294     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2295     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2296     * hide the action bar.
2297     *
2298     * <p>This approach to going fullscreen is best used over the window flag when
2299     * it is a transient state -- that is, the application does this at certain
2300     * points in its user interaction where it wants to allow the user to focus
2301     * on content, but not as a continuous state.  For situations where the application
2302     * would like to simply stay full screen the entire time (such as a game that
2303     * wants to take over the screen), the
2304     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2305     * is usually a better approach.  The state set here will be removed by the system
2306     * in various situations (such as the user moving to another application) like
2307     * the other system UI states.
2308     *
2309     * <p>When using this flag, the application should provide some easy facility
2310     * for the user to go out of it.  A common example would be in an e-book
2311     * reader, where tapping on the screen brings back whatever screen and UI
2312     * decorations that had been hidden while the user was immersed in reading
2313     * the book.
2314     *
2315     * @see #setSystemUiVisibility(int)
2316     */
2317    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2318
2319    /**
2320     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2321     * flags, we would like a stable view of the content insets given to
2322     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2323     * will always represent the worst case that the application can expect
2324     * as a continuous state.  In the stock Android UI this is the space for
2325     * the system bar, nav bar, and status bar, but not more transient elements
2326     * such as an input method.
2327     *
2328     * The stable layout your UI sees is based on the system UI modes you can
2329     * switch to.  That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
2330     * then you will get a stable layout for changes of the
2331     * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
2332     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
2333     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
2334     * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
2335     * with a stable layout.  (Note that you should avoid using
2336     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
2337     *
2338     * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN}
2339     * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
2340     * then a hidden status bar will be considered a "stable" state for purposes
2341     * here.  This allows your UI to continually hide the status bar, while still
2342     * using the system UI flags to hide the action bar while still retaining
2343     * a stable layout.  Note that changing the window fullscreen flag will never
2344     * provide a stable layout for a clean transition.
2345     *
2346     * <p>If you are using ActionBar in
2347     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2348     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2349     * insets it adds to those given to the application.
2350     */
2351    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2352
2353    /**
2354     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2355     * to be layed out as if it has requested
2356     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2357     * allows it to avoid artifacts when switching in and out of that mode, at
2358     * the expense that some of its user interface may be covered by screen
2359     * decorations when they are shown.  You can perform layout of your inner
2360     * UI elements to account for the navigation system UI through the
2361     * {@link #fitSystemWindows(Rect)} method.
2362     */
2363    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2364
2365    /**
2366     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2367     * to be layed out as if it has requested
2368     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2369     * allows it to avoid artifacts when switching in and out of that mode, at
2370     * the expense that some of its user interface may be covered by screen
2371     * decorations when they are shown.  You can perform layout of your inner
2372     * UI elements to account for non-fullscreen system UI through the
2373     * {@link #fitSystemWindows(Rect)} method.
2374     */
2375    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2376
2377    /**
2378     * Flag for {@link #setSystemUiVisibility(int)}: View would like to receive touch events
2379     * when hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the
2380     * navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} instead of having the system
2381     * clear these flags upon interaction.  The system may compensate by temporarily overlaying
2382     * transparent system bars while also delivering the event.
2383     */
2384    public static final int SYSTEM_UI_FLAG_ALLOW_TRANSIENT = 0x00000800;
2385
2386    /**
2387     * Flag for {@link #setSystemUiVisibility(int)}: View would like the status bar to have
2388     * transparency.
2389     *
2390     * <p>The transparency request may be denied if the bar is in another mode with a specific
2391     * style, like {@link #SYSTEM_UI_FLAG_ALLOW_TRANSIENT transient mode}.
2392     */
2393    public static final int SYSTEM_UI_FLAG_TRANSPARENT_STATUS = 0x00001000;
2394
2395    /**
2396     * Flag for {@link #setSystemUiVisibility(int)}: View would like the navigation bar to have
2397     * transparency.
2398     *
2399     * <p>The transparency request may be denied if the bar is in another mode with a specific
2400     * style, like {@link #SYSTEM_UI_FLAG_ALLOW_TRANSIENT transient mode}.
2401     */
2402    public static final int SYSTEM_UI_FLAG_TRANSPARENT_NAVIGATION = 0x00002000;
2403
2404    /**
2405     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2406     */
2407    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2408
2409    /**
2410     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2411     */
2412    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2413
2414    /**
2415     * @hide
2416     *
2417     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2418     * out of the public fields to keep the undefined bits out of the developer's way.
2419     *
2420     * Flag to make the status bar not expandable.  Unless you also
2421     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
2422     */
2423    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
2424
2425    /**
2426     * @hide
2427     *
2428     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2429     * out of the public fields to keep the undefined bits out of the developer's way.
2430     *
2431     * Flag to hide notification icons and scrolling ticker text.
2432     */
2433    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
2434
2435    /**
2436     * @hide
2437     *
2438     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2439     * out of the public fields to keep the undefined bits out of the developer's way.
2440     *
2441     * Flag to disable incoming notification alerts.  This will not block
2442     * icons, but it will block sound, vibrating and other visual or aural notifications.
2443     */
2444    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
2445
2446    /**
2447     * @hide
2448     *
2449     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2450     * out of the public fields to keep the undefined bits out of the developer's way.
2451     *
2452     * Flag to hide only the scrolling ticker.  Note that
2453     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
2454     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
2455     */
2456    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
2457
2458    /**
2459     * @hide
2460     *
2461     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2462     * out of the public fields to keep the undefined bits out of the developer's way.
2463     *
2464     * Flag to hide the center system info area.
2465     */
2466    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
2467
2468    /**
2469     * @hide
2470     *
2471     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2472     * out of the public fields to keep the undefined bits out of the developer's way.
2473     *
2474     * Flag to hide only the home button.  Don't use this
2475     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2476     */
2477    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
2478
2479    /**
2480     * @hide
2481     *
2482     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2483     * out of the public fields to keep the undefined bits out of the developer's way.
2484     *
2485     * Flag to hide only the back button. Don't use this
2486     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2487     */
2488    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
2489
2490    /**
2491     * @hide
2492     *
2493     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2494     * out of the public fields to keep the undefined bits out of the developer's way.
2495     *
2496     * Flag to hide only the clock.  You might use this if your activity has
2497     * its own clock making the status bar's clock redundant.
2498     */
2499    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
2500
2501    /**
2502     * @hide
2503     *
2504     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2505     * out of the public fields to keep the undefined bits out of the developer's way.
2506     *
2507     * Flag to hide only the recent apps button. Don't use this
2508     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2509     */
2510    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
2511
2512    /**
2513     * @hide
2514     *
2515     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2516     * out of the public fields to keep the undefined bits out of the developer's way.
2517     *
2518     * Flag to disable the global search gesture. Don't use this
2519     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2520     */
2521    public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000;
2522
2523    /**
2524     * @hide
2525     *
2526     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2527     * out of the public fields to keep the undefined bits out of the developer's way.
2528     *
2529     * Flag to specify that the status bar is displayed in transient mode.
2530     */
2531    public static final int STATUS_BAR_TRANSIENT = 0x04000000;
2532
2533    /**
2534     * @hide
2535     *
2536     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2537     * out of the public fields to keep the undefined bits out of the developer's way.
2538     *
2539     * Flag to specify that the navigation bar is displayed in transient mode.
2540     */
2541    public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000;
2542
2543    /**
2544     * @hide
2545     */
2546    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF;
2547
2548    /**
2549     * These are the system UI flags that can be cleared by events outside
2550     * of an application.  Currently this is just the ability to tap on the
2551     * screen while hiding the navigation bar to have it return.
2552     * @hide
2553     */
2554    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
2555            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
2556            | SYSTEM_UI_FLAG_FULLSCREEN;
2557
2558    /**
2559     * Flags that can impact the layout in relation to system UI.
2560     */
2561    public static final int SYSTEM_UI_LAYOUT_FLAGS =
2562            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
2563            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
2564
2565    /**
2566     * Find views that render the specified text.
2567     *
2568     * @see #findViewsWithText(ArrayList, CharSequence, int)
2569     */
2570    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
2571
2572    /**
2573     * Find find views that contain the specified content description.
2574     *
2575     * @see #findViewsWithText(ArrayList, CharSequence, int)
2576     */
2577    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
2578
2579    /**
2580     * Find views that contain {@link AccessibilityNodeProvider}. Such
2581     * a View is a root of virtual view hierarchy and may contain the searched
2582     * text. If this flag is set Views with providers are automatically
2583     * added and it is a responsibility of the client to call the APIs of
2584     * the provider to determine whether the virtual tree rooted at this View
2585     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
2586     * represeting the virtual views with this text.
2587     *
2588     * @see #findViewsWithText(ArrayList, CharSequence, int)
2589     *
2590     * @hide
2591     */
2592    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
2593
2594    /**
2595     * The undefined cursor position.
2596     *
2597     * @hide
2598     */
2599    public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1;
2600
2601    /**
2602     * Indicates that the screen has changed state and is now off.
2603     *
2604     * @see #onScreenStateChanged(int)
2605     */
2606    public static final int SCREEN_STATE_OFF = 0x0;
2607
2608    /**
2609     * Indicates that the screen has changed state and is now on.
2610     *
2611     * @see #onScreenStateChanged(int)
2612     */
2613    public static final int SCREEN_STATE_ON = 0x1;
2614
2615    /**
2616     * Controls the over-scroll mode for this view.
2617     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
2618     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
2619     * and {@link #OVER_SCROLL_NEVER}.
2620     */
2621    private int mOverScrollMode;
2622
2623    /**
2624     * The parent this view is attached to.
2625     * {@hide}
2626     *
2627     * @see #getParent()
2628     */
2629    protected ViewParent mParent;
2630
2631    /**
2632     * {@hide}
2633     */
2634    AttachInfo mAttachInfo;
2635
2636    /**
2637     * {@hide}
2638     */
2639    @ViewDebug.ExportedProperty(flagMapping = {
2640        @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT,
2641                name = "FORCE_LAYOUT"),
2642        @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED,
2643                name = "LAYOUT_REQUIRED"),
2644        @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID,
2645            name = "DRAWING_CACHE_INVALID", outputIf = false),
2646        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true),
2647        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false),
2648        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
2649        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY")
2650    })
2651    int mPrivateFlags;
2652    int mPrivateFlags2;
2653    int mPrivateFlags3;
2654
2655    /**
2656     * This view's request for the visibility of the status bar.
2657     * @hide
2658     */
2659    @ViewDebug.ExportedProperty(flagMapping = {
2660        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
2661                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
2662                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
2663        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2664                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2665                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
2666        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
2667                                equals = SYSTEM_UI_FLAG_VISIBLE,
2668                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
2669    })
2670    int mSystemUiVisibility;
2671
2672    /**
2673     * Reference count for transient state.
2674     * @see #setHasTransientState(boolean)
2675     */
2676    int mTransientStateCount = 0;
2677
2678    /**
2679     * Count of how many windows this view has been attached to.
2680     */
2681    int mWindowAttachCount;
2682
2683    /**
2684     * The layout parameters associated with this view and used by the parent
2685     * {@link android.view.ViewGroup} to determine how this view should be
2686     * laid out.
2687     * {@hide}
2688     */
2689    protected ViewGroup.LayoutParams mLayoutParams;
2690
2691    /**
2692     * The view flags hold various views states.
2693     * {@hide}
2694     */
2695    @ViewDebug.ExportedProperty
2696    int mViewFlags;
2697
2698    static class TransformationInfo {
2699        /**
2700         * The transform matrix for the View. This transform is calculated internally
2701         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2702         * is used by default. Do *not* use this variable directly; instead call
2703         * getMatrix(), which will automatically recalculate the matrix if necessary
2704         * to get the correct matrix based on the latest rotation and scale properties.
2705         */
2706        private final Matrix mMatrix = new Matrix();
2707
2708        /**
2709         * The transform matrix for the View. This transform is calculated internally
2710         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2711         * is used by default. Do *not* use this variable directly; instead call
2712         * getInverseMatrix(), which will automatically recalculate the matrix if necessary
2713         * to get the correct matrix based on the latest rotation and scale properties.
2714         */
2715        private Matrix mInverseMatrix;
2716
2717        /**
2718         * An internal variable that tracks whether we need to recalculate the
2719         * transform matrix, based on whether the rotation or scaleX/Y properties
2720         * have changed since the matrix was last calculated.
2721         */
2722        boolean mMatrixDirty = false;
2723
2724        /**
2725         * An internal variable that tracks whether we need to recalculate the
2726         * transform matrix, based on whether the rotation or scaleX/Y properties
2727         * have changed since the matrix was last calculated.
2728         */
2729        private boolean mInverseMatrixDirty = true;
2730
2731        /**
2732         * A variable that tracks whether we need to recalculate the
2733         * transform matrix, based on whether the rotation or scaleX/Y properties
2734         * have changed since the matrix was last calculated. This variable
2735         * is only valid after a call to updateMatrix() or to a function that
2736         * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
2737         */
2738        private boolean mMatrixIsIdentity = true;
2739
2740        /**
2741         * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
2742         */
2743        private Camera mCamera = null;
2744
2745        /**
2746         * This matrix is used when computing the matrix for 3D rotations.
2747         */
2748        private Matrix matrix3D = null;
2749
2750        /**
2751         * These prev values are used to recalculate a centered pivot point when necessary. The
2752         * pivot point is only used in matrix operations (when rotation, scale, or translation are
2753         * set), so thes values are only used then as well.
2754         */
2755        private int mPrevWidth = -1;
2756        private int mPrevHeight = -1;
2757
2758        /**
2759         * The degrees rotation around the vertical axis through the pivot point.
2760         */
2761        @ViewDebug.ExportedProperty
2762        float mRotationY = 0f;
2763
2764        /**
2765         * The degrees rotation around the horizontal axis through the pivot point.
2766         */
2767        @ViewDebug.ExportedProperty
2768        float mRotationX = 0f;
2769
2770        /**
2771         * The degrees rotation around the pivot point.
2772         */
2773        @ViewDebug.ExportedProperty
2774        float mRotation = 0f;
2775
2776        /**
2777         * The amount of translation of the object away from its left property (post-layout).
2778         */
2779        @ViewDebug.ExportedProperty
2780        float mTranslationX = 0f;
2781
2782        /**
2783         * The amount of translation of the object away from its top property (post-layout).
2784         */
2785        @ViewDebug.ExportedProperty
2786        float mTranslationY = 0f;
2787
2788        /**
2789         * The amount of scale in the x direction around the pivot point. A
2790         * value of 1 means no scaling is applied.
2791         */
2792        @ViewDebug.ExportedProperty
2793        float mScaleX = 1f;
2794
2795        /**
2796         * The amount of scale in the y direction around the pivot point. A
2797         * value of 1 means no scaling is applied.
2798         */
2799        @ViewDebug.ExportedProperty
2800        float mScaleY = 1f;
2801
2802        /**
2803         * The x location of the point around which the view is rotated and scaled.
2804         */
2805        @ViewDebug.ExportedProperty
2806        float mPivotX = 0f;
2807
2808        /**
2809         * The y location of the point around which the view is rotated and scaled.
2810         */
2811        @ViewDebug.ExportedProperty
2812        float mPivotY = 0f;
2813
2814        /**
2815         * The opacity of the View. This is a value from 0 to 1, where 0 means
2816         * completely transparent and 1 means completely opaque.
2817         */
2818        @ViewDebug.ExportedProperty
2819        float mAlpha = 1f;
2820    }
2821
2822    TransformationInfo mTransformationInfo;
2823
2824    /**
2825     * Current clip bounds. to which all drawing of this view are constrained.
2826     */
2827    private Rect mClipBounds = null;
2828
2829    private boolean mLastIsOpaque;
2830
2831    /**
2832     * Convenience value to check for float values that are close enough to zero to be considered
2833     * zero.
2834     */
2835    private static final float NONZERO_EPSILON = .001f;
2836
2837    /**
2838     * The distance in pixels from the left edge of this view's parent
2839     * to the left edge of this view.
2840     * {@hide}
2841     */
2842    @ViewDebug.ExportedProperty(category = "layout")
2843    protected int mLeft;
2844    /**
2845     * The distance in pixels from the left edge of this view's parent
2846     * to the right edge of this view.
2847     * {@hide}
2848     */
2849    @ViewDebug.ExportedProperty(category = "layout")
2850    protected int mRight;
2851    /**
2852     * The distance in pixels from the top edge of this view's parent
2853     * to the top edge of this view.
2854     * {@hide}
2855     */
2856    @ViewDebug.ExportedProperty(category = "layout")
2857    protected int mTop;
2858    /**
2859     * The distance in pixels from the top edge of this view's parent
2860     * to the bottom edge of this view.
2861     * {@hide}
2862     */
2863    @ViewDebug.ExportedProperty(category = "layout")
2864    protected int mBottom;
2865
2866    /**
2867     * The offset, in pixels, by which the content of this view is scrolled
2868     * horizontally.
2869     * {@hide}
2870     */
2871    @ViewDebug.ExportedProperty(category = "scrolling")
2872    protected int mScrollX;
2873    /**
2874     * The offset, in pixels, by which the content of this view is scrolled
2875     * vertically.
2876     * {@hide}
2877     */
2878    @ViewDebug.ExportedProperty(category = "scrolling")
2879    protected int mScrollY;
2880
2881    /**
2882     * The left padding in pixels, that is the distance in pixels between the
2883     * left edge of this view and the left edge of its content.
2884     * {@hide}
2885     */
2886    @ViewDebug.ExportedProperty(category = "padding")
2887    protected int mPaddingLeft = 0;
2888    /**
2889     * The right padding in pixels, that is the distance in pixels between the
2890     * right edge of this view and the right edge of its content.
2891     * {@hide}
2892     */
2893    @ViewDebug.ExportedProperty(category = "padding")
2894    protected int mPaddingRight = 0;
2895    /**
2896     * The top padding in pixels, that is the distance in pixels between the
2897     * top edge of this view and the top edge of its content.
2898     * {@hide}
2899     */
2900    @ViewDebug.ExportedProperty(category = "padding")
2901    protected int mPaddingTop;
2902    /**
2903     * The bottom padding in pixels, that is the distance in pixels between the
2904     * bottom edge of this view and the bottom edge of its content.
2905     * {@hide}
2906     */
2907    @ViewDebug.ExportedProperty(category = "padding")
2908    protected int mPaddingBottom;
2909
2910    /**
2911     * The layout insets in pixels, that is the distance in pixels between the
2912     * visible edges of this view its bounds.
2913     */
2914    private Insets mLayoutInsets;
2915
2916    /**
2917     * Briefly describes the view and is primarily used for accessibility support.
2918     */
2919    private CharSequence mContentDescription;
2920
2921    /**
2922     * Specifies the id of a view for which this view serves as a label for
2923     * accessibility purposes.
2924     */
2925    private int mLabelForId = View.NO_ID;
2926
2927    /**
2928     * Predicate for matching labeled view id with its label for
2929     * accessibility purposes.
2930     */
2931    private MatchLabelForPredicate mMatchLabelForPredicate;
2932
2933    /**
2934     * Predicate for matching a view by its id.
2935     */
2936    private MatchIdPredicate mMatchIdPredicate;
2937
2938    /**
2939     * Cache the paddingRight set by the user to append to the scrollbar's size.
2940     *
2941     * @hide
2942     */
2943    @ViewDebug.ExportedProperty(category = "padding")
2944    protected int mUserPaddingRight;
2945
2946    /**
2947     * Cache the paddingBottom set by the user to append to the scrollbar's size.
2948     *
2949     * @hide
2950     */
2951    @ViewDebug.ExportedProperty(category = "padding")
2952    protected int mUserPaddingBottom;
2953
2954    /**
2955     * Cache the paddingLeft set by the user to append to the scrollbar's size.
2956     *
2957     * @hide
2958     */
2959    @ViewDebug.ExportedProperty(category = "padding")
2960    protected int mUserPaddingLeft;
2961
2962    /**
2963     * Cache the paddingStart set by the user to append to the scrollbar's size.
2964     *
2965     */
2966    @ViewDebug.ExportedProperty(category = "padding")
2967    int mUserPaddingStart;
2968
2969    /**
2970     * Cache the paddingEnd set by the user to append to the scrollbar's size.
2971     *
2972     */
2973    @ViewDebug.ExportedProperty(category = "padding")
2974    int mUserPaddingEnd;
2975
2976    /**
2977     * Cache initial left padding.
2978     *
2979     * @hide
2980     */
2981    int mUserPaddingLeftInitial;
2982
2983    /**
2984     * Cache initial right padding.
2985     *
2986     * @hide
2987     */
2988    int mUserPaddingRightInitial;
2989
2990    /**
2991     * Default undefined padding
2992     */
2993    private static final int UNDEFINED_PADDING = Integer.MIN_VALUE;
2994
2995    /**
2996     * @hide
2997     */
2998    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
2999    /**
3000     * @hide
3001     */
3002    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
3003
3004    private LongSparseLongArray mMeasureCache;
3005
3006    @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_")
3007    private Drawable mBackground;
3008
3009    private int mBackgroundResource;
3010    private boolean mBackgroundSizeChanged;
3011
3012    static class ListenerInfo {
3013        /**
3014         * Listener used to dispatch focus change events.
3015         * This field should be made private, so it is hidden from the SDK.
3016         * {@hide}
3017         */
3018        protected OnFocusChangeListener mOnFocusChangeListener;
3019
3020        /**
3021         * Listeners for layout change events.
3022         */
3023        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
3024
3025        /**
3026         * Listeners for attach events.
3027         */
3028        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
3029
3030        /**
3031         * Listener used to dispatch click events.
3032         * This field should be made private, so it is hidden from the SDK.
3033         * {@hide}
3034         */
3035        public OnClickListener mOnClickListener;
3036
3037        /**
3038         * Listener used to dispatch long click events.
3039         * This field should be made private, so it is hidden from the SDK.
3040         * {@hide}
3041         */
3042        protected OnLongClickListener mOnLongClickListener;
3043
3044        /**
3045         * Listener used to build the context menu.
3046         * This field should be made private, so it is hidden from the SDK.
3047         * {@hide}
3048         */
3049        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
3050
3051        private OnKeyListener mOnKeyListener;
3052
3053        private OnTouchListener mOnTouchListener;
3054
3055        private OnHoverListener mOnHoverListener;
3056
3057        private OnGenericMotionListener mOnGenericMotionListener;
3058
3059        private OnDragListener mOnDragListener;
3060
3061        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
3062    }
3063
3064    ListenerInfo mListenerInfo;
3065
3066    /**
3067     * The application environment this view lives in.
3068     * This field should be made private, so it is hidden from the SDK.
3069     * {@hide}
3070     */
3071    protected Context mContext;
3072
3073    private final Resources mResources;
3074
3075    private ScrollabilityCache mScrollCache;
3076
3077    private int[] mDrawableState = null;
3078
3079    /**
3080     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
3081     * the user may specify which view to go to next.
3082     */
3083    private int mNextFocusLeftId = View.NO_ID;
3084
3085    /**
3086     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
3087     * the user may specify which view to go to next.
3088     */
3089    private int mNextFocusRightId = View.NO_ID;
3090
3091    /**
3092     * When this view has focus and the next focus is {@link #FOCUS_UP},
3093     * the user may specify which view to go to next.
3094     */
3095    private int mNextFocusUpId = View.NO_ID;
3096
3097    /**
3098     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
3099     * the user may specify which view to go to next.
3100     */
3101    private int mNextFocusDownId = View.NO_ID;
3102
3103    /**
3104     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
3105     * the user may specify which view to go to next.
3106     */
3107    int mNextFocusForwardId = View.NO_ID;
3108
3109    private CheckForLongPress mPendingCheckForLongPress;
3110    private CheckForTap mPendingCheckForTap = null;
3111    private PerformClick mPerformClick;
3112    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
3113
3114    private UnsetPressedState mUnsetPressedState;
3115
3116    /**
3117     * Whether the long press's action has been invoked.  The tap's action is invoked on the
3118     * up event while a long press is invoked as soon as the long press duration is reached, so
3119     * a long press could be performed before the tap is checked, in which case the tap's action
3120     * should not be invoked.
3121     */
3122    private boolean mHasPerformedLongPress;
3123
3124    /**
3125     * The minimum height of the view. We'll try our best to have the height
3126     * of this view to at least this amount.
3127     */
3128    @ViewDebug.ExportedProperty(category = "measurement")
3129    private int mMinHeight;
3130
3131    /**
3132     * The minimum width of the view. We'll try our best to have the width
3133     * of this view to at least this amount.
3134     */
3135    @ViewDebug.ExportedProperty(category = "measurement")
3136    private int mMinWidth;
3137
3138    /**
3139     * The delegate to handle touch events that are physically in this view
3140     * but should be handled by another view.
3141     */
3142    private TouchDelegate mTouchDelegate = null;
3143
3144    /**
3145     * Solid color to use as a background when creating the drawing cache. Enables
3146     * the cache to use 16 bit bitmaps instead of 32 bit.
3147     */
3148    private int mDrawingCacheBackgroundColor = 0;
3149
3150    /**
3151     * Special tree observer used when mAttachInfo is null.
3152     */
3153    private ViewTreeObserver mFloatingTreeObserver;
3154
3155    /**
3156     * Cache the touch slop from the context that created the view.
3157     */
3158    private int mTouchSlop;
3159
3160    /**
3161     * Object that handles automatic animation of view properties.
3162     */
3163    private ViewPropertyAnimator mAnimator = null;
3164
3165    /**
3166     * Flag indicating that a drag can cross window boundaries.  When
3167     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
3168     * with this flag set, all visible applications will be able to participate
3169     * in the drag operation and receive the dragged content.
3170     *
3171     * @hide
3172     */
3173    public static final int DRAG_FLAG_GLOBAL = 1;
3174
3175    /**
3176     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
3177     */
3178    private float mVerticalScrollFactor;
3179
3180    /**
3181     * Position of the vertical scroll bar.
3182     */
3183    private int mVerticalScrollbarPosition;
3184
3185    /**
3186     * Position the scroll bar at the default position as determined by the system.
3187     */
3188    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
3189
3190    /**
3191     * Position the scroll bar along the left edge.
3192     */
3193    public static final int SCROLLBAR_POSITION_LEFT = 1;
3194
3195    /**
3196     * Position the scroll bar along the right edge.
3197     */
3198    public static final int SCROLLBAR_POSITION_RIGHT = 2;
3199
3200    /**
3201     * Indicates that the view does not have a layer.
3202     *
3203     * @see #getLayerType()
3204     * @see #setLayerType(int, android.graphics.Paint)
3205     * @see #LAYER_TYPE_SOFTWARE
3206     * @see #LAYER_TYPE_HARDWARE
3207     */
3208    public static final int LAYER_TYPE_NONE = 0;
3209
3210    /**
3211     * <p>Indicates that the view has a software layer. A software layer is backed
3212     * by a bitmap and causes the view to be rendered using Android's software
3213     * rendering pipeline, even if hardware acceleration is enabled.</p>
3214     *
3215     * <p>Software layers have various usages:</p>
3216     * <p>When the application is not using hardware acceleration, a software layer
3217     * is useful to apply a specific color filter and/or blending mode and/or
3218     * translucency to a view and all its children.</p>
3219     * <p>When the application is using hardware acceleration, a software layer
3220     * is useful to render drawing primitives not supported by the hardware
3221     * accelerated pipeline. It can also be used to cache a complex view tree
3222     * into a texture and reduce the complexity of drawing operations. For instance,
3223     * when animating a complex view tree with a translation, a software layer can
3224     * be used to render the view tree only once.</p>
3225     * <p>Software layers should be avoided when the affected view tree updates
3226     * often. Every update will require to re-render the software layer, which can
3227     * potentially be slow (particularly when hardware acceleration is turned on
3228     * since the layer will have to be uploaded into a hardware texture after every
3229     * update.)</p>
3230     *
3231     * @see #getLayerType()
3232     * @see #setLayerType(int, android.graphics.Paint)
3233     * @see #LAYER_TYPE_NONE
3234     * @see #LAYER_TYPE_HARDWARE
3235     */
3236    public static final int LAYER_TYPE_SOFTWARE = 1;
3237
3238    /**
3239     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3240     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3241     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3242     * rendering pipeline, but only if hardware acceleration is turned on for the
3243     * view hierarchy. When hardware acceleration is turned off, hardware layers
3244     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3245     *
3246     * <p>A hardware layer is useful to apply a specific color filter and/or
3247     * blending mode and/or translucency to a view and all its children.</p>
3248     * <p>A hardware layer can be used to cache a complex view tree into a
3249     * texture and reduce the complexity of drawing operations. For instance,
3250     * when animating a complex view tree with a translation, a hardware layer can
3251     * be used to render the view tree only once.</p>
3252     * <p>A hardware layer can also be used to increase the rendering quality when
3253     * rotation transformations are applied on a view. It can also be used to
3254     * prevent potential clipping issues when applying 3D transforms on a view.</p>
3255     *
3256     * @see #getLayerType()
3257     * @see #setLayerType(int, android.graphics.Paint)
3258     * @see #LAYER_TYPE_NONE
3259     * @see #LAYER_TYPE_SOFTWARE
3260     */
3261    public static final int LAYER_TYPE_HARDWARE = 2;
3262
3263    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3264            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
3265            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
3266            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
3267    })
3268    int mLayerType = LAYER_TYPE_NONE;
3269    Paint mLayerPaint;
3270    Rect mLocalDirtyRect;
3271    private HardwareLayer mHardwareLayer;
3272
3273    /**
3274     * Set to true when drawing cache is enabled and cannot be created.
3275     *
3276     * @hide
3277     */
3278    public boolean mCachingFailed;
3279    private Bitmap mDrawingCache;
3280    private Bitmap mUnscaledDrawingCache;
3281
3282    DisplayList mDisplayList;
3283
3284    /**
3285     * Set to true when the view is sending hover accessibility events because it
3286     * is the innermost hovered view.
3287     */
3288    private boolean mSendingHoverAccessibilityEvents;
3289
3290    /**
3291     * Delegate for injecting accessibility functionality.
3292     */
3293    AccessibilityDelegate mAccessibilityDelegate;
3294
3295    /**
3296     * The view's overlay layer. Developers get a reference to the overlay via getOverlay()
3297     * and add/remove objects to/from the overlay directly through the Overlay methods.
3298     */
3299    ViewOverlay mOverlay;
3300
3301    /**
3302     * Consistency verifier for debugging purposes.
3303     * @hide
3304     */
3305    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
3306            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
3307                    new InputEventConsistencyVerifier(this, 0) : null;
3308
3309    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
3310
3311    /**
3312     * Simple constructor to use when creating a view from code.
3313     *
3314     * @param context The Context the view is running in, through which it can
3315     *        access the current theme, resources, etc.
3316     */
3317    public View(Context context) {
3318        mContext = context;
3319        mResources = context != null ? context.getResources() : null;
3320        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
3321        // Set some flags defaults
3322        mPrivateFlags2 =
3323                (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) |
3324                (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) |
3325                (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) |
3326                (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) |
3327                (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) |
3328                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
3329        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
3330        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
3331        mUserPaddingStart = UNDEFINED_PADDING;
3332        mUserPaddingEnd = UNDEFINED_PADDING;
3333
3334        if (!sUseBrokenMakeMeasureSpec && context != null &&
3335                context.getApplicationInfo().targetSdkVersion <= JELLY_BEAN_MR1) {
3336            // Older apps may need this compatibility hack for measurement.
3337            sUseBrokenMakeMeasureSpec = true;
3338        }
3339    }
3340
3341    /**
3342     * Constructor that is called when inflating a view from XML. This is called
3343     * when a view is being constructed from an XML file, supplying attributes
3344     * that were specified in the XML file. This version uses a default style of
3345     * 0, so the only attribute values applied are those in the Context's Theme
3346     * and the given AttributeSet.
3347     *
3348     * <p>
3349     * The method onFinishInflate() will be called after all children have been
3350     * added.
3351     *
3352     * @param context The Context the view is running in, through which it can
3353     *        access the current theme, resources, etc.
3354     * @param attrs The attributes of the XML tag that is inflating the view.
3355     * @see #View(Context, AttributeSet, int)
3356     */
3357    public View(Context context, AttributeSet attrs) {
3358        this(context, attrs, 0);
3359    }
3360
3361    /**
3362     * Perform inflation from XML and apply a class-specific base style. This
3363     * constructor of View allows subclasses to use their own base style when
3364     * they are inflating. For example, a Button class's constructor would call
3365     * this version of the super class constructor and supply
3366     * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
3367     * the theme's button style to modify all of the base view attributes (in
3368     * particular its background) as well as the Button class's attributes.
3369     *
3370     * @param context The Context the view is running in, through which it can
3371     *        access the current theme, resources, etc.
3372     * @param attrs The attributes of the XML tag that is inflating the view.
3373     * @param defStyle The default style to apply to this view. If 0, no style
3374     *        will be applied (beyond what is included in the theme). This may
3375     *        either be an attribute resource, whose value will be retrieved
3376     *        from the current theme, or an explicit style resource.
3377     * @see #View(Context, AttributeSet)
3378     */
3379    public View(Context context, AttributeSet attrs, int defStyle) {
3380        this(context);
3381
3382        TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
3383                defStyle, 0);
3384
3385        Drawable background = null;
3386
3387        int leftPadding = -1;
3388        int topPadding = -1;
3389        int rightPadding = -1;
3390        int bottomPadding = -1;
3391        int startPadding = UNDEFINED_PADDING;
3392        int endPadding = UNDEFINED_PADDING;
3393
3394        int padding = -1;
3395
3396        int viewFlagValues = 0;
3397        int viewFlagMasks = 0;
3398
3399        boolean setScrollContainer = false;
3400
3401        int x = 0;
3402        int y = 0;
3403
3404        float tx = 0;
3405        float ty = 0;
3406        float rotation = 0;
3407        float rotationX = 0;
3408        float rotationY = 0;
3409        float sx = 1f;
3410        float sy = 1f;
3411        boolean transformSet = false;
3412
3413        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
3414        int overScrollMode = mOverScrollMode;
3415        boolean initializeScrollbars = false;
3416
3417        boolean leftPaddingDefined = false;
3418        boolean rightPaddingDefined = false;
3419        boolean startPaddingDefined = false;
3420        boolean endPaddingDefined = false;
3421
3422        final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3423
3424        final int N = a.getIndexCount();
3425        for (int i = 0; i < N; i++) {
3426            int attr = a.getIndex(i);
3427            switch (attr) {
3428                case com.android.internal.R.styleable.View_background:
3429                    background = a.getDrawable(attr);
3430                    break;
3431                case com.android.internal.R.styleable.View_padding:
3432                    padding = a.getDimensionPixelSize(attr, -1);
3433                    mUserPaddingLeftInitial = padding;
3434                    mUserPaddingRightInitial = padding;
3435                    leftPaddingDefined = true;
3436                    rightPaddingDefined = true;
3437                    break;
3438                 case com.android.internal.R.styleable.View_paddingLeft:
3439                    leftPadding = a.getDimensionPixelSize(attr, -1);
3440                    mUserPaddingLeftInitial = leftPadding;
3441                    leftPaddingDefined = true;
3442                    break;
3443                case com.android.internal.R.styleable.View_paddingTop:
3444                    topPadding = a.getDimensionPixelSize(attr, -1);
3445                    break;
3446                case com.android.internal.R.styleable.View_paddingRight:
3447                    rightPadding = a.getDimensionPixelSize(attr, -1);
3448                    mUserPaddingRightInitial = rightPadding;
3449                    rightPaddingDefined = true;
3450                    break;
3451                case com.android.internal.R.styleable.View_paddingBottom:
3452                    bottomPadding = a.getDimensionPixelSize(attr, -1);
3453                    break;
3454                case com.android.internal.R.styleable.View_paddingStart:
3455                    startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3456                    startPaddingDefined = (startPadding != UNDEFINED_PADDING);
3457                    break;
3458                case com.android.internal.R.styleable.View_paddingEnd:
3459                    endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3460                    endPaddingDefined = (endPadding != UNDEFINED_PADDING);
3461                    break;
3462                case com.android.internal.R.styleable.View_scrollX:
3463                    x = a.getDimensionPixelOffset(attr, 0);
3464                    break;
3465                case com.android.internal.R.styleable.View_scrollY:
3466                    y = a.getDimensionPixelOffset(attr, 0);
3467                    break;
3468                case com.android.internal.R.styleable.View_alpha:
3469                    setAlpha(a.getFloat(attr, 1f));
3470                    break;
3471                case com.android.internal.R.styleable.View_transformPivotX:
3472                    setPivotX(a.getDimensionPixelOffset(attr, 0));
3473                    break;
3474                case com.android.internal.R.styleable.View_transformPivotY:
3475                    setPivotY(a.getDimensionPixelOffset(attr, 0));
3476                    break;
3477                case com.android.internal.R.styleable.View_translationX:
3478                    tx = a.getDimensionPixelOffset(attr, 0);
3479                    transformSet = true;
3480                    break;
3481                case com.android.internal.R.styleable.View_translationY:
3482                    ty = a.getDimensionPixelOffset(attr, 0);
3483                    transformSet = true;
3484                    break;
3485                case com.android.internal.R.styleable.View_rotation:
3486                    rotation = a.getFloat(attr, 0);
3487                    transformSet = true;
3488                    break;
3489                case com.android.internal.R.styleable.View_rotationX:
3490                    rotationX = a.getFloat(attr, 0);
3491                    transformSet = true;
3492                    break;
3493                case com.android.internal.R.styleable.View_rotationY:
3494                    rotationY = a.getFloat(attr, 0);
3495                    transformSet = true;
3496                    break;
3497                case com.android.internal.R.styleable.View_scaleX:
3498                    sx = a.getFloat(attr, 1f);
3499                    transformSet = true;
3500                    break;
3501                case com.android.internal.R.styleable.View_scaleY:
3502                    sy = a.getFloat(attr, 1f);
3503                    transformSet = true;
3504                    break;
3505                case com.android.internal.R.styleable.View_id:
3506                    mID = a.getResourceId(attr, NO_ID);
3507                    break;
3508                case com.android.internal.R.styleable.View_tag:
3509                    mTag = a.getText(attr);
3510                    break;
3511                case com.android.internal.R.styleable.View_fitsSystemWindows:
3512                    if (a.getBoolean(attr, false)) {
3513                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
3514                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
3515                    }
3516                    break;
3517                case com.android.internal.R.styleable.View_focusable:
3518                    if (a.getBoolean(attr, false)) {
3519                        viewFlagValues |= FOCUSABLE;
3520                        viewFlagMasks |= FOCUSABLE_MASK;
3521                    }
3522                    break;
3523                case com.android.internal.R.styleable.View_focusableInTouchMode:
3524                    if (a.getBoolean(attr, false)) {
3525                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
3526                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
3527                    }
3528                    break;
3529                case com.android.internal.R.styleable.View_clickable:
3530                    if (a.getBoolean(attr, false)) {
3531                        viewFlagValues |= CLICKABLE;
3532                        viewFlagMasks |= CLICKABLE;
3533                    }
3534                    break;
3535                case com.android.internal.R.styleable.View_longClickable:
3536                    if (a.getBoolean(attr, false)) {
3537                        viewFlagValues |= LONG_CLICKABLE;
3538                        viewFlagMasks |= LONG_CLICKABLE;
3539                    }
3540                    break;
3541                case com.android.internal.R.styleable.View_saveEnabled:
3542                    if (!a.getBoolean(attr, true)) {
3543                        viewFlagValues |= SAVE_DISABLED;
3544                        viewFlagMasks |= SAVE_DISABLED_MASK;
3545                    }
3546                    break;
3547                case com.android.internal.R.styleable.View_duplicateParentState:
3548                    if (a.getBoolean(attr, false)) {
3549                        viewFlagValues |= DUPLICATE_PARENT_STATE;
3550                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
3551                    }
3552                    break;
3553                case com.android.internal.R.styleable.View_visibility:
3554                    final int visibility = a.getInt(attr, 0);
3555                    if (visibility != 0) {
3556                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
3557                        viewFlagMasks |= VISIBILITY_MASK;
3558                    }
3559                    break;
3560                case com.android.internal.R.styleable.View_layoutDirection:
3561                    // Clear any layout direction flags (included resolved bits) already set
3562                    mPrivateFlags2 &=
3563                            ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK);
3564                    // Set the layout direction flags depending on the value of the attribute
3565                    final int layoutDirection = a.getInt(attr, -1);
3566                    final int value = (layoutDirection != -1) ?
3567                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
3568                    mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT);
3569                    break;
3570                case com.android.internal.R.styleable.View_drawingCacheQuality:
3571                    final int cacheQuality = a.getInt(attr, 0);
3572                    if (cacheQuality != 0) {
3573                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
3574                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
3575                    }
3576                    break;
3577                case com.android.internal.R.styleable.View_contentDescription:
3578                    setContentDescription(a.getString(attr));
3579                    break;
3580                case com.android.internal.R.styleable.View_labelFor:
3581                    setLabelFor(a.getResourceId(attr, NO_ID));
3582                    break;
3583                case com.android.internal.R.styleable.View_soundEffectsEnabled:
3584                    if (!a.getBoolean(attr, true)) {
3585                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
3586                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
3587                    }
3588                    break;
3589                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
3590                    if (!a.getBoolean(attr, true)) {
3591                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
3592                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
3593                    }
3594                    break;
3595                case R.styleable.View_scrollbars:
3596                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
3597                    if (scrollbars != SCROLLBARS_NONE) {
3598                        viewFlagValues |= scrollbars;
3599                        viewFlagMasks |= SCROLLBARS_MASK;
3600                        initializeScrollbars = true;
3601                    }
3602                    break;
3603                //noinspection deprecation
3604                case R.styleable.View_fadingEdge:
3605                    if (targetSdkVersion >= ICE_CREAM_SANDWICH) {
3606                        // Ignore the attribute starting with ICS
3607                        break;
3608                    }
3609                    // With builds < ICS, fall through and apply fading edges
3610                case R.styleable.View_requiresFadingEdge:
3611                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
3612                    if (fadingEdge != FADING_EDGE_NONE) {
3613                        viewFlagValues |= fadingEdge;
3614                        viewFlagMasks |= FADING_EDGE_MASK;
3615                        initializeFadingEdge(a);
3616                    }
3617                    break;
3618                case R.styleable.View_scrollbarStyle:
3619                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
3620                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3621                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
3622                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
3623                    }
3624                    break;
3625                case R.styleable.View_isScrollContainer:
3626                    setScrollContainer = true;
3627                    if (a.getBoolean(attr, false)) {
3628                        setScrollContainer(true);
3629                    }
3630                    break;
3631                case com.android.internal.R.styleable.View_keepScreenOn:
3632                    if (a.getBoolean(attr, false)) {
3633                        viewFlagValues |= KEEP_SCREEN_ON;
3634                        viewFlagMasks |= KEEP_SCREEN_ON;
3635                    }
3636                    break;
3637                case R.styleable.View_filterTouchesWhenObscured:
3638                    if (a.getBoolean(attr, false)) {
3639                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
3640                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
3641                    }
3642                    break;
3643                case R.styleable.View_nextFocusLeft:
3644                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
3645                    break;
3646                case R.styleable.View_nextFocusRight:
3647                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
3648                    break;
3649                case R.styleable.View_nextFocusUp:
3650                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
3651                    break;
3652                case R.styleable.View_nextFocusDown:
3653                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
3654                    break;
3655                case R.styleable.View_nextFocusForward:
3656                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
3657                    break;
3658                case R.styleable.View_minWidth:
3659                    mMinWidth = a.getDimensionPixelSize(attr, 0);
3660                    break;
3661                case R.styleable.View_minHeight:
3662                    mMinHeight = a.getDimensionPixelSize(attr, 0);
3663                    break;
3664                case R.styleable.View_onClick:
3665                    if (context.isRestricted()) {
3666                        throw new IllegalStateException("The android:onClick attribute cannot "
3667                                + "be used within a restricted context");
3668                    }
3669
3670                    final String handlerName = a.getString(attr);
3671                    if (handlerName != null) {
3672                        setOnClickListener(new OnClickListener() {
3673                            private Method mHandler;
3674
3675                            public void onClick(View v) {
3676                                if (mHandler == null) {
3677                                    try {
3678                                        mHandler = getContext().getClass().getMethod(handlerName,
3679                                                View.class);
3680                                    } catch (NoSuchMethodException e) {
3681                                        int id = getId();
3682                                        String idText = id == NO_ID ? "" : " with id '"
3683                                                + getContext().getResources().getResourceEntryName(
3684                                                    id) + "'";
3685                                        throw new IllegalStateException("Could not find a method " +
3686                                                handlerName + "(View) in the activity "
3687                                                + getContext().getClass() + " for onClick handler"
3688                                                + " on view " + View.this.getClass() + idText, e);
3689                                    }
3690                                }
3691
3692                                try {
3693                                    mHandler.invoke(getContext(), View.this);
3694                                } catch (IllegalAccessException e) {
3695                                    throw new IllegalStateException("Could not execute non "
3696                                            + "public method of the activity", e);
3697                                } catch (InvocationTargetException e) {
3698                                    throw new IllegalStateException("Could not execute "
3699                                            + "method of the activity", e);
3700                                }
3701                            }
3702                        });
3703                    }
3704                    break;
3705                case R.styleable.View_overScrollMode:
3706                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
3707                    break;
3708                case R.styleable.View_verticalScrollbarPosition:
3709                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
3710                    break;
3711                case R.styleable.View_layerType:
3712                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
3713                    break;
3714                case R.styleable.View_textDirection:
3715                    // Clear any text direction flag already set
3716                    mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
3717                    // Set the text direction flags depending on the value of the attribute
3718                    final int textDirection = a.getInt(attr, -1);
3719                    if (textDirection != -1) {
3720                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection];
3721                    }
3722                    break;
3723                case R.styleable.View_textAlignment:
3724                    // Clear any text alignment flag already set
3725                    mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
3726                    // Set the text alignment flag depending on the value of the attribute
3727                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
3728                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment];
3729                    break;
3730                case R.styleable.View_importantForAccessibility:
3731                    setImportantForAccessibility(a.getInt(attr,
3732                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
3733                    break;
3734            }
3735        }
3736
3737        setOverScrollMode(overScrollMode);
3738
3739        // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet
3740        // the resolved layout direction). Those cached values will be used later during padding
3741        // resolution.
3742        mUserPaddingStart = startPadding;
3743        mUserPaddingEnd = endPadding;
3744
3745        if (background != null) {
3746            setBackground(background);
3747        }
3748
3749        if (padding >= 0) {
3750            leftPadding = padding;
3751            topPadding = padding;
3752            rightPadding = padding;
3753            bottomPadding = padding;
3754            mUserPaddingLeftInitial = padding;
3755            mUserPaddingRightInitial = padding;
3756        }
3757
3758        if (isRtlCompatibilityMode()) {
3759            // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case.
3760            // left / right padding are used if defined (meaning here nothing to do). If they are not
3761            // defined and start / end padding are defined (e.g. in Frameworks resources), then we use
3762            // start / end and resolve them as left / right (layout direction is not taken into account).
3763            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
3764            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
3765            // defined.
3766            if (!leftPaddingDefined && startPaddingDefined) {
3767                leftPadding = startPadding;
3768            }
3769            mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial;
3770            if (!rightPaddingDefined && endPaddingDefined) {
3771                rightPadding = endPadding;
3772            }
3773            mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial;
3774        } else {
3775            // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right
3776            // values defined. Otherwise, left /right values are used.
3777            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
3778            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
3779            // defined.
3780            final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined;
3781
3782            if (leftPaddingDefined && !hasRelativePadding) {
3783                mUserPaddingLeftInitial = leftPadding;
3784            }
3785            if (rightPaddingDefined && !hasRelativePadding) {
3786                mUserPaddingRightInitial = rightPadding;
3787            }
3788        }
3789
3790        internalSetPadding(
3791                mUserPaddingLeftInitial,
3792                topPadding >= 0 ? topPadding : mPaddingTop,
3793                mUserPaddingRightInitial,
3794                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
3795
3796        if (viewFlagMasks != 0) {
3797            setFlags(viewFlagValues, viewFlagMasks);
3798        }
3799
3800        if (initializeScrollbars) {
3801            initializeScrollbars(a);
3802        }
3803
3804        a.recycle();
3805
3806        // Needs to be called after mViewFlags is set
3807        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3808            recomputePadding();
3809        }
3810
3811        if (x != 0 || y != 0) {
3812            scrollTo(x, y);
3813        }
3814
3815        if (transformSet) {
3816            setTranslationX(tx);
3817            setTranslationY(ty);
3818            setRotation(rotation);
3819            setRotationX(rotationX);
3820            setRotationY(rotationY);
3821            setScaleX(sx);
3822            setScaleY(sy);
3823        }
3824
3825        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
3826            setScrollContainer(true);
3827        }
3828
3829        computeOpaqueFlags();
3830    }
3831
3832    /**
3833     * Non-public constructor for use in testing
3834     */
3835    View() {
3836        mResources = null;
3837    }
3838
3839    public String toString() {
3840        StringBuilder out = new StringBuilder(128);
3841        out.append(getClass().getName());
3842        out.append('{');
3843        out.append(Integer.toHexString(System.identityHashCode(this)));
3844        out.append(' ');
3845        switch (mViewFlags&VISIBILITY_MASK) {
3846            case VISIBLE: out.append('V'); break;
3847            case INVISIBLE: out.append('I'); break;
3848            case GONE: out.append('G'); break;
3849            default: out.append('.'); break;
3850        }
3851        out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.');
3852        out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.');
3853        out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D');
3854        out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.');
3855        out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.');
3856        out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.');
3857        out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.');
3858        out.append(' ');
3859        out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.');
3860        out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.');
3861        out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.');
3862        if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) {
3863            out.append('p');
3864        } else {
3865            out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.');
3866        }
3867        out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.');
3868        out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.');
3869        out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.');
3870        out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.');
3871        out.append(' ');
3872        out.append(mLeft);
3873        out.append(',');
3874        out.append(mTop);
3875        out.append('-');
3876        out.append(mRight);
3877        out.append(',');
3878        out.append(mBottom);
3879        final int id = getId();
3880        if (id != NO_ID) {
3881            out.append(" #");
3882            out.append(Integer.toHexString(id));
3883            final Resources r = mResources;
3884            if (id != 0 && r != null) {
3885                try {
3886                    String pkgname;
3887                    switch (id&0xff000000) {
3888                        case 0x7f000000:
3889                            pkgname="app";
3890                            break;
3891                        case 0x01000000:
3892                            pkgname="android";
3893                            break;
3894                        default:
3895                            pkgname = r.getResourcePackageName(id);
3896                            break;
3897                    }
3898                    String typename = r.getResourceTypeName(id);
3899                    String entryname = r.getResourceEntryName(id);
3900                    out.append(" ");
3901                    out.append(pkgname);
3902                    out.append(":");
3903                    out.append(typename);
3904                    out.append("/");
3905                    out.append(entryname);
3906                } catch (Resources.NotFoundException e) {
3907                }
3908            }
3909        }
3910        out.append("}");
3911        return out.toString();
3912    }
3913
3914    /**
3915     * <p>
3916     * Initializes the fading edges from a given set of styled attributes. This
3917     * method should be called by subclasses that need fading edges and when an
3918     * instance of these subclasses is created programmatically rather than
3919     * being inflated from XML. This method is automatically called when the XML
3920     * is inflated.
3921     * </p>
3922     *
3923     * @param a the styled attributes set to initialize the fading edges from
3924     */
3925    protected void initializeFadingEdge(TypedArray a) {
3926        initScrollCache();
3927
3928        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
3929                R.styleable.View_fadingEdgeLength,
3930                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
3931    }
3932
3933    /**
3934     * Returns the size of the vertical faded edges used to indicate that more
3935     * content in this view is visible.
3936     *
3937     * @return The size in pixels of the vertical faded edge or 0 if vertical
3938     *         faded edges are not enabled for this view.
3939     * @attr ref android.R.styleable#View_fadingEdgeLength
3940     */
3941    public int getVerticalFadingEdgeLength() {
3942        if (isVerticalFadingEdgeEnabled()) {
3943            ScrollabilityCache cache = mScrollCache;
3944            if (cache != null) {
3945                return cache.fadingEdgeLength;
3946            }
3947        }
3948        return 0;
3949    }
3950
3951    /**
3952     * Set the size of the faded edge used to indicate that more content in this
3953     * view is available.  Will not change whether the fading edge is enabled; use
3954     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
3955     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
3956     * for the vertical or horizontal fading edges.
3957     *
3958     * @param length The size in pixels of the faded edge used to indicate that more
3959     *        content in this view is visible.
3960     */
3961    public void setFadingEdgeLength(int length) {
3962        initScrollCache();
3963        mScrollCache.fadingEdgeLength = length;
3964    }
3965
3966    /**
3967     * Returns the size of the horizontal faded edges used to indicate that more
3968     * content in this view is visible.
3969     *
3970     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
3971     *         faded edges are not enabled for this view.
3972     * @attr ref android.R.styleable#View_fadingEdgeLength
3973     */
3974    public int getHorizontalFadingEdgeLength() {
3975        if (isHorizontalFadingEdgeEnabled()) {
3976            ScrollabilityCache cache = mScrollCache;
3977            if (cache != null) {
3978                return cache.fadingEdgeLength;
3979            }
3980        }
3981        return 0;
3982    }
3983
3984    /**
3985     * Returns the width of the vertical scrollbar.
3986     *
3987     * @return The width in pixels of the vertical scrollbar or 0 if there
3988     *         is no vertical scrollbar.
3989     */
3990    public int getVerticalScrollbarWidth() {
3991        ScrollabilityCache cache = mScrollCache;
3992        if (cache != null) {
3993            ScrollBarDrawable scrollBar = cache.scrollBar;
3994            if (scrollBar != null) {
3995                int size = scrollBar.getSize(true);
3996                if (size <= 0) {
3997                    size = cache.scrollBarSize;
3998                }
3999                return size;
4000            }
4001            return 0;
4002        }
4003        return 0;
4004    }
4005
4006    /**
4007     * Returns the height of the horizontal scrollbar.
4008     *
4009     * @return The height in pixels of the horizontal scrollbar or 0 if
4010     *         there is no horizontal scrollbar.
4011     */
4012    protected int getHorizontalScrollbarHeight() {
4013        ScrollabilityCache cache = mScrollCache;
4014        if (cache != null) {
4015            ScrollBarDrawable scrollBar = cache.scrollBar;
4016            if (scrollBar != null) {
4017                int size = scrollBar.getSize(false);
4018                if (size <= 0) {
4019                    size = cache.scrollBarSize;
4020                }
4021                return size;
4022            }
4023            return 0;
4024        }
4025        return 0;
4026    }
4027
4028    /**
4029     * <p>
4030     * Initializes the scrollbars from a given set of styled attributes. This
4031     * method should be called by subclasses that need scrollbars and when an
4032     * instance of these subclasses is created programmatically rather than
4033     * being inflated from XML. This method is automatically called when the XML
4034     * is inflated.
4035     * </p>
4036     *
4037     * @param a the styled attributes set to initialize the scrollbars from
4038     */
4039    protected void initializeScrollbars(TypedArray a) {
4040        initScrollCache();
4041
4042        final ScrollabilityCache scrollabilityCache = mScrollCache;
4043
4044        if (scrollabilityCache.scrollBar == null) {
4045            scrollabilityCache.scrollBar = new ScrollBarDrawable();
4046        }
4047
4048        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
4049
4050        if (!fadeScrollbars) {
4051            scrollabilityCache.state = ScrollabilityCache.ON;
4052        }
4053        scrollabilityCache.fadeScrollBars = fadeScrollbars;
4054
4055
4056        scrollabilityCache.scrollBarFadeDuration = a.getInt(
4057                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
4058                        .getScrollBarFadeDuration());
4059        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
4060                R.styleable.View_scrollbarDefaultDelayBeforeFade,
4061                ViewConfiguration.getScrollDefaultDelay());
4062
4063
4064        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
4065                com.android.internal.R.styleable.View_scrollbarSize,
4066                ViewConfiguration.get(mContext).getScaledScrollBarSize());
4067
4068        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
4069        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
4070
4071        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
4072        if (thumb != null) {
4073            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
4074        }
4075
4076        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
4077                false);
4078        if (alwaysDraw) {
4079            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
4080        }
4081
4082        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
4083        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
4084
4085        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
4086        if (thumb != null) {
4087            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
4088        }
4089
4090        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
4091                false);
4092        if (alwaysDraw) {
4093            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
4094        }
4095
4096        // Apply layout direction to the new Drawables if needed
4097        final int layoutDirection = getLayoutDirection();
4098        if (track != null) {
4099            track.setLayoutDirection(layoutDirection);
4100        }
4101        if (thumb != null) {
4102            thumb.setLayoutDirection(layoutDirection);
4103        }
4104
4105        // Re-apply user/background padding so that scrollbar(s) get added
4106        resolvePadding();
4107    }
4108
4109    /**
4110     * <p>
4111     * Initalizes the scrollability cache if necessary.
4112     * </p>
4113     */
4114    private void initScrollCache() {
4115        if (mScrollCache == null) {
4116            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
4117        }
4118    }
4119
4120    private ScrollabilityCache getScrollCache() {
4121        initScrollCache();
4122        return mScrollCache;
4123    }
4124
4125    /**
4126     * Set the position of the vertical scroll bar. Should be one of
4127     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
4128     * {@link #SCROLLBAR_POSITION_RIGHT}.
4129     *
4130     * @param position Where the vertical scroll bar should be positioned.
4131     */
4132    public void setVerticalScrollbarPosition(int position) {
4133        if (mVerticalScrollbarPosition != position) {
4134            mVerticalScrollbarPosition = position;
4135            computeOpaqueFlags();
4136            resolvePadding();
4137        }
4138    }
4139
4140    /**
4141     * @return The position where the vertical scroll bar will show, if applicable.
4142     * @see #setVerticalScrollbarPosition(int)
4143     */
4144    public int getVerticalScrollbarPosition() {
4145        return mVerticalScrollbarPosition;
4146    }
4147
4148    ListenerInfo getListenerInfo() {
4149        if (mListenerInfo != null) {
4150            return mListenerInfo;
4151        }
4152        mListenerInfo = new ListenerInfo();
4153        return mListenerInfo;
4154    }
4155
4156    /**
4157     * Register a callback to be invoked when focus of this view changed.
4158     *
4159     * @param l The callback that will run.
4160     */
4161    public void setOnFocusChangeListener(OnFocusChangeListener l) {
4162        getListenerInfo().mOnFocusChangeListener = l;
4163    }
4164
4165    /**
4166     * Add a listener that will be called when the bounds of the view change due to
4167     * layout processing.
4168     *
4169     * @param listener The listener that will be called when layout bounds change.
4170     */
4171    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
4172        ListenerInfo li = getListenerInfo();
4173        if (li.mOnLayoutChangeListeners == null) {
4174            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
4175        }
4176        if (!li.mOnLayoutChangeListeners.contains(listener)) {
4177            li.mOnLayoutChangeListeners.add(listener);
4178        }
4179    }
4180
4181    /**
4182     * Remove a listener for layout changes.
4183     *
4184     * @param listener The listener for layout bounds change.
4185     */
4186    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
4187        ListenerInfo li = mListenerInfo;
4188        if (li == null || li.mOnLayoutChangeListeners == null) {
4189            return;
4190        }
4191        li.mOnLayoutChangeListeners.remove(listener);
4192    }
4193
4194    /**
4195     * Add a listener for attach state changes.
4196     *
4197     * This listener will be called whenever this view is attached or detached
4198     * from a window. Remove the listener using
4199     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
4200     *
4201     * @param listener Listener to attach
4202     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
4203     */
4204    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4205        ListenerInfo li = getListenerInfo();
4206        if (li.mOnAttachStateChangeListeners == null) {
4207            li.mOnAttachStateChangeListeners
4208                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
4209        }
4210        li.mOnAttachStateChangeListeners.add(listener);
4211    }
4212
4213    /**
4214     * Remove a listener for attach state changes. The listener will receive no further
4215     * notification of window attach/detach events.
4216     *
4217     * @param listener Listener to remove
4218     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
4219     */
4220    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4221        ListenerInfo li = mListenerInfo;
4222        if (li == null || li.mOnAttachStateChangeListeners == null) {
4223            return;
4224        }
4225        li.mOnAttachStateChangeListeners.remove(listener);
4226    }
4227
4228    /**
4229     * Returns the focus-change callback registered for this view.
4230     *
4231     * @return The callback, or null if one is not registered.
4232     */
4233    public OnFocusChangeListener getOnFocusChangeListener() {
4234        ListenerInfo li = mListenerInfo;
4235        return li != null ? li.mOnFocusChangeListener : null;
4236    }
4237
4238    /**
4239     * Register a callback to be invoked when this view is clicked. If this view is not
4240     * clickable, it becomes clickable.
4241     *
4242     * @param l The callback that will run
4243     *
4244     * @see #setClickable(boolean)
4245     */
4246    public void setOnClickListener(OnClickListener l) {
4247        if (!isClickable()) {
4248            setClickable(true);
4249        }
4250        getListenerInfo().mOnClickListener = l;
4251    }
4252
4253    /**
4254     * Return whether this view has an attached OnClickListener.  Returns
4255     * true if there is a listener, false if there is none.
4256     */
4257    public boolean hasOnClickListeners() {
4258        ListenerInfo li = mListenerInfo;
4259        return (li != null && li.mOnClickListener != null);
4260    }
4261
4262    /**
4263     * Register a callback to be invoked when this view is clicked and held. If this view is not
4264     * long clickable, it becomes long clickable.
4265     *
4266     * @param l The callback that will run
4267     *
4268     * @see #setLongClickable(boolean)
4269     */
4270    public void setOnLongClickListener(OnLongClickListener l) {
4271        if (!isLongClickable()) {
4272            setLongClickable(true);
4273        }
4274        getListenerInfo().mOnLongClickListener = l;
4275    }
4276
4277    /**
4278     * Register a callback to be invoked when the context menu for this view is
4279     * being built. If this view is not long clickable, it becomes long clickable.
4280     *
4281     * @param l The callback that will run
4282     *
4283     */
4284    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
4285        if (!isLongClickable()) {
4286            setLongClickable(true);
4287        }
4288        getListenerInfo().mOnCreateContextMenuListener = l;
4289    }
4290
4291    /**
4292     * Call this view's OnClickListener, if it is defined.  Performs all normal
4293     * actions associated with clicking: reporting accessibility event, playing
4294     * a sound, etc.
4295     *
4296     * @return True there was an assigned OnClickListener that was called, false
4297     *         otherwise is returned.
4298     */
4299    public boolean performClick() {
4300        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
4301
4302        ListenerInfo li = mListenerInfo;
4303        if (li != null && li.mOnClickListener != null) {
4304            playSoundEffect(SoundEffectConstants.CLICK);
4305            li.mOnClickListener.onClick(this);
4306            return true;
4307        }
4308
4309        return false;
4310    }
4311
4312    /**
4313     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
4314     * this only calls the listener, and does not do any associated clicking
4315     * actions like reporting an accessibility event.
4316     *
4317     * @return True there was an assigned OnClickListener that was called, false
4318     *         otherwise is returned.
4319     */
4320    public boolean callOnClick() {
4321        ListenerInfo li = mListenerInfo;
4322        if (li != null && li.mOnClickListener != null) {
4323            li.mOnClickListener.onClick(this);
4324            return true;
4325        }
4326        return false;
4327    }
4328
4329    /**
4330     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
4331     * OnLongClickListener did not consume the event.
4332     *
4333     * @return True if one of the above receivers consumed the event, false otherwise.
4334     */
4335    public boolean performLongClick() {
4336        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
4337
4338        boolean handled = false;
4339        ListenerInfo li = mListenerInfo;
4340        if (li != null && li.mOnLongClickListener != null) {
4341            handled = li.mOnLongClickListener.onLongClick(View.this);
4342        }
4343        if (!handled) {
4344            handled = showContextMenu();
4345        }
4346        if (handled) {
4347            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
4348        }
4349        return handled;
4350    }
4351
4352    /**
4353     * Performs button-related actions during a touch down event.
4354     *
4355     * @param event The event.
4356     * @return True if the down was consumed.
4357     *
4358     * @hide
4359     */
4360    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
4361        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
4362            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
4363                return true;
4364            }
4365        }
4366        return false;
4367    }
4368
4369    /**
4370     * Bring up the context menu for this view.
4371     *
4372     * @return Whether a context menu was displayed.
4373     */
4374    public boolean showContextMenu() {
4375        return getParent().showContextMenuForChild(this);
4376    }
4377
4378    /**
4379     * Bring up the context menu for this view, referring to the item under the specified point.
4380     *
4381     * @param x The referenced x coordinate.
4382     * @param y The referenced y coordinate.
4383     * @param metaState The keyboard modifiers that were pressed.
4384     * @return Whether a context menu was displayed.
4385     *
4386     * @hide
4387     */
4388    public boolean showContextMenu(float x, float y, int metaState) {
4389        return showContextMenu();
4390    }
4391
4392    /**
4393     * Start an action mode.
4394     *
4395     * @param callback Callback that will control the lifecycle of the action mode
4396     * @return The new action mode if it is started, null otherwise
4397     *
4398     * @see ActionMode
4399     */
4400    public ActionMode startActionMode(ActionMode.Callback callback) {
4401        ViewParent parent = getParent();
4402        if (parent == null) return null;
4403        return parent.startActionModeForChild(this, callback);
4404    }
4405
4406    /**
4407     * Register a callback to be invoked when a hardware key is pressed in this view.
4408     * Key presses in software input methods will generally not trigger the methods of
4409     * this listener.
4410     * @param l the key listener to attach to this view
4411     */
4412    public void setOnKeyListener(OnKeyListener l) {
4413        getListenerInfo().mOnKeyListener = l;
4414    }
4415
4416    /**
4417     * Register a callback to be invoked when a touch event is sent to this view.
4418     * @param l the touch listener to attach to this view
4419     */
4420    public void setOnTouchListener(OnTouchListener l) {
4421        getListenerInfo().mOnTouchListener = l;
4422    }
4423
4424    /**
4425     * Register a callback to be invoked when a generic motion event is sent to this view.
4426     * @param l the generic motion listener to attach to this view
4427     */
4428    public void setOnGenericMotionListener(OnGenericMotionListener l) {
4429        getListenerInfo().mOnGenericMotionListener = l;
4430    }
4431
4432    /**
4433     * Register a callback to be invoked when a hover event is sent to this view.
4434     * @param l the hover listener to attach to this view
4435     */
4436    public void setOnHoverListener(OnHoverListener l) {
4437        getListenerInfo().mOnHoverListener = l;
4438    }
4439
4440    /**
4441     * Register a drag event listener callback object for this View. The parameter is
4442     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
4443     * View, the system calls the
4444     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
4445     * @param l An implementation of {@link android.view.View.OnDragListener}.
4446     */
4447    public void setOnDragListener(OnDragListener l) {
4448        getListenerInfo().mOnDragListener = l;
4449    }
4450
4451    /**
4452     * Give this view focus. This will cause
4453     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
4454     *
4455     * Note: this does not check whether this {@link View} should get focus, it just
4456     * gives it focus no matter what.  It should only be called internally by framework
4457     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
4458     *
4459     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
4460     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
4461     *        focus moved when requestFocus() is called. It may not always
4462     *        apply, in which case use the default View.FOCUS_DOWN.
4463     * @param previouslyFocusedRect The rectangle of the view that had focus
4464     *        prior in this View's coordinate system.
4465     */
4466    void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
4467        if (DBG) {
4468            System.out.println(this + " requestFocus()");
4469        }
4470
4471        if ((mPrivateFlags & PFLAG_FOCUSED) == 0) {
4472            mPrivateFlags |= PFLAG_FOCUSED;
4473
4474            View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null;
4475
4476            if (mParent != null) {
4477                mParent.requestChildFocus(this, this);
4478            }
4479
4480            if (mAttachInfo != null) {
4481                mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this);
4482            }
4483
4484            onFocusChanged(true, direction, previouslyFocusedRect);
4485            refreshDrawableState();
4486        }
4487    }
4488
4489    /**
4490     * Request that a rectangle of this view be visible on the screen,
4491     * scrolling if necessary just enough.
4492     *
4493     * <p>A View should call this if it maintains some notion of which part
4494     * of its content is interesting.  For example, a text editing view
4495     * should call this when its cursor moves.
4496     *
4497     * @param rectangle The rectangle.
4498     * @return Whether any parent scrolled.
4499     */
4500    public boolean requestRectangleOnScreen(Rect rectangle) {
4501        return requestRectangleOnScreen(rectangle, false);
4502    }
4503
4504    /**
4505     * Request that a rectangle of this view be visible on the screen,
4506     * scrolling if necessary just enough.
4507     *
4508     * <p>A View should call this if it maintains some notion of which part
4509     * of its content is interesting.  For example, a text editing view
4510     * should call this when its cursor moves.
4511     *
4512     * <p>When <code>immediate</code> is set to true, scrolling will not be
4513     * animated.
4514     *
4515     * @param rectangle The rectangle.
4516     * @param immediate True to forbid animated scrolling, false otherwise
4517     * @return Whether any parent scrolled.
4518     */
4519    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
4520        if (mParent == null) {
4521            return false;
4522        }
4523
4524        View child = this;
4525
4526        RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF();
4527        position.set(rectangle);
4528
4529        ViewParent parent = mParent;
4530        boolean scrolled = false;
4531        while (parent != null) {
4532            rectangle.set((int) position.left, (int) position.top,
4533                    (int) position.right, (int) position.bottom);
4534
4535            scrolled |= parent.requestChildRectangleOnScreen(child,
4536                    rectangle, immediate);
4537
4538            if (!child.hasIdentityMatrix()) {
4539                child.getMatrix().mapRect(position);
4540            }
4541
4542            position.offset(child.mLeft, child.mTop);
4543
4544            if (!(parent instanceof View)) {
4545                break;
4546            }
4547
4548            View parentView = (View) parent;
4549
4550            position.offset(-parentView.getScrollX(), -parentView.getScrollY());
4551
4552            child = parentView;
4553            parent = child.getParent();
4554        }
4555
4556        return scrolled;
4557    }
4558
4559    /**
4560     * Called when this view wants to give up focus. If focus is cleared
4561     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
4562     * <p>
4563     * <strong>Note:</strong> When a View clears focus the framework is trying
4564     * to give focus to the first focusable View from the top. Hence, if this
4565     * View is the first from the top that can take focus, then all callbacks
4566     * related to clearing focus will be invoked after wich the framework will
4567     * give focus to this view.
4568     * </p>
4569     */
4570    public void clearFocus() {
4571        if (DBG) {
4572            System.out.println(this + " clearFocus()");
4573        }
4574
4575        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
4576            mPrivateFlags &= ~PFLAG_FOCUSED;
4577
4578            if (mParent != null) {
4579                mParent.clearChildFocus(this);
4580            }
4581
4582            onFocusChanged(false, 0, null);
4583
4584            refreshDrawableState();
4585
4586            if (!rootViewRequestFocus()) {
4587                notifyGlobalFocusCleared(this);
4588            }
4589        }
4590    }
4591
4592    void notifyGlobalFocusCleared(View oldFocus) {
4593        if (oldFocus != null && mAttachInfo != null) {
4594            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
4595        }
4596    }
4597
4598    boolean rootViewRequestFocus() {
4599        final View root = getRootView();
4600        return root != null && root.requestFocus();
4601    }
4602
4603    /**
4604     * Called internally by the view system when a new view is getting focus.
4605     * This is what clears the old focus.
4606     * <p>
4607     * <b>NOTE:</b> The parent view's focused child must be updated manually
4608     * after calling this method. Otherwise, the view hierarchy may be left in
4609     * an inconstent state.
4610     */
4611    void unFocus() {
4612        if (DBG) {
4613            System.out.println(this + " unFocus()");
4614        }
4615
4616        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
4617            mPrivateFlags &= ~PFLAG_FOCUSED;
4618
4619            onFocusChanged(false, 0, null);
4620            refreshDrawableState();
4621        }
4622    }
4623
4624    /**
4625     * Returns true if this view has focus iteself, or is the ancestor of the
4626     * view that has focus.
4627     *
4628     * @return True if this view has or contains focus, false otherwise.
4629     */
4630    @ViewDebug.ExportedProperty(category = "focus")
4631    public boolean hasFocus() {
4632        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
4633    }
4634
4635    /**
4636     * Returns true if this view is focusable or if it contains a reachable View
4637     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
4638     * is a View whose parents do not block descendants focus.
4639     *
4640     * Only {@link #VISIBLE} views are considered focusable.
4641     *
4642     * @return True if the view is focusable or if the view contains a focusable
4643     *         View, false otherwise.
4644     *
4645     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
4646     */
4647    public boolean hasFocusable() {
4648        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
4649    }
4650
4651    /**
4652     * Called by the view system when the focus state of this view changes.
4653     * When the focus change event is caused by directional navigation, direction
4654     * and previouslyFocusedRect provide insight into where the focus is coming from.
4655     * When overriding, be sure to call up through to the super class so that
4656     * the standard focus handling will occur.
4657     *
4658     * @param gainFocus True if the View has focus; false otherwise.
4659     * @param direction The direction focus has moved when requestFocus()
4660     *                  is called to give this view focus. Values are
4661     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
4662     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
4663     *                  It may not always apply, in which case use the default.
4664     * @param previouslyFocusedRect The rectangle, in this view's coordinate
4665     *        system, of the previously focused view.  If applicable, this will be
4666     *        passed in as finer grained information about where the focus is coming
4667     *        from (in addition to direction).  Will be <code>null</code> otherwise.
4668     */
4669    protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
4670        if (gainFocus) {
4671            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
4672        } else {
4673            notifyViewAccessibilityStateChangedIfNeeded();
4674        }
4675
4676        InputMethodManager imm = InputMethodManager.peekInstance();
4677        if (!gainFocus) {
4678            if (isPressed()) {
4679                setPressed(false);
4680            }
4681            if (imm != null && mAttachInfo != null
4682                    && mAttachInfo.mHasWindowFocus) {
4683                imm.focusOut(this);
4684            }
4685            onFocusLost();
4686        } else if (imm != null && mAttachInfo != null
4687                && mAttachInfo.mHasWindowFocus) {
4688            imm.focusIn(this);
4689        }
4690
4691        invalidate(true);
4692        ListenerInfo li = mListenerInfo;
4693        if (li != null && li.mOnFocusChangeListener != null) {
4694            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
4695        }
4696
4697        if (mAttachInfo != null) {
4698            mAttachInfo.mKeyDispatchState.reset(this);
4699        }
4700    }
4701
4702    /**
4703     * Sends an accessibility event of the given type. If accessibility is
4704     * not enabled this method has no effect. The default implementation calls
4705     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
4706     * to populate information about the event source (this View), then calls
4707     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
4708     * populate the text content of the event source including its descendants,
4709     * and last calls
4710     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
4711     * on its parent to resuest sending of the event to interested parties.
4712     * <p>
4713     * If an {@link AccessibilityDelegate} has been specified via calling
4714     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4715     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
4716     * responsible for handling this call.
4717     * </p>
4718     *
4719     * @param eventType The type of the event to send, as defined by several types from
4720     * {@link android.view.accessibility.AccessibilityEvent}, such as
4721     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
4722     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
4723     *
4724     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4725     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4726     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
4727     * @see AccessibilityDelegate
4728     */
4729    public void sendAccessibilityEvent(int eventType) {
4730        // Excluded views do not send accessibility events.
4731        if (!includeForAccessibility()) {
4732            return;
4733        }
4734        if (mAccessibilityDelegate != null) {
4735            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
4736        } else {
4737            sendAccessibilityEventInternal(eventType);
4738        }
4739    }
4740
4741    /**
4742     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
4743     * {@link AccessibilityEvent} to make an announcement which is related to some
4744     * sort of a context change for which none of the events representing UI transitions
4745     * is a good fit. For example, announcing a new page in a book. If accessibility
4746     * is not enabled this method does nothing.
4747     *
4748     * @param text The announcement text.
4749     */
4750    public void announceForAccessibility(CharSequence text) {
4751        if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) {
4752            AccessibilityEvent event = AccessibilityEvent.obtain(
4753                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
4754            onInitializeAccessibilityEvent(event);
4755            event.getText().add(text);
4756            event.setContentDescription(null);
4757            mParent.requestSendAccessibilityEvent(this, event);
4758        }
4759    }
4760
4761    /**
4762     * @see #sendAccessibilityEvent(int)
4763     *
4764     * Note: Called from the default {@link AccessibilityDelegate}.
4765     */
4766    void sendAccessibilityEventInternal(int eventType) {
4767        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4768            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
4769        }
4770    }
4771
4772    /**
4773     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
4774     * takes as an argument an empty {@link AccessibilityEvent} and does not
4775     * perform a check whether accessibility is enabled.
4776     * <p>
4777     * If an {@link AccessibilityDelegate} has been specified via calling
4778     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4779     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
4780     * is responsible for handling this call.
4781     * </p>
4782     *
4783     * @param event The event to send.
4784     *
4785     * @see #sendAccessibilityEvent(int)
4786     */
4787    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
4788        if (mAccessibilityDelegate != null) {
4789            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
4790        } else {
4791            sendAccessibilityEventUncheckedInternal(event);
4792        }
4793    }
4794
4795    /**
4796     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
4797     *
4798     * Note: Called from the default {@link AccessibilityDelegate}.
4799     */
4800    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
4801        if (!isShown()) {
4802            return;
4803        }
4804        onInitializeAccessibilityEvent(event);
4805        // Only a subset of accessibility events populates text content.
4806        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
4807            dispatchPopulateAccessibilityEvent(event);
4808        }
4809        // In the beginning we called #isShown(), so we know that getParent() is not null.
4810        getParent().requestSendAccessibilityEvent(this, event);
4811    }
4812
4813    /**
4814     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
4815     * to its children for adding their text content to the event. Note that the
4816     * event text is populated in a separate dispatch path since we add to the
4817     * event not only the text of the source but also the text of all its descendants.
4818     * A typical implementation will call
4819     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
4820     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4821     * on each child. Override this method if custom population of the event text
4822     * content is required.
4823     * <p>
4824     * If an {@link AccessibilityDelegate} has been specified via calling
4825     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4826     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
4827     * is responsible for handling this call.
4828     * </p>
4829     * <p>
4830     * <em>Note:</em> Accessibility events of certain types are not dispatched for
4831     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
4832     * </p>
4833     *
4834     * @param event The event.
4835     *
4836     * @return True if the event population was completed.
4837     */
4838    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
4839        if (mAccessibilityDelegate != null) {
4840            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
4841        } else {
4842            return dispatchPopulateAccessibilityEventInternal(event);
4843        }
4844    }
4845
4846    /**
4847     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4848     *
4849     * Note: Called from the default {@link AccessibilityDelegate}.
4850     */
4851    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4852        onPopulateAccessibilityEvent(event);
4853        return false;
4854    }
4855
4856    /**
4857     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4858     * giving a chance to this View to populate the accessibility event with its
4859     * text content. While this method is free to modify event
4860     * attributes other than text content, doing so should normally be performed in
4861     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
4862     * <p>
4863     * Example: Adding formatted date string to an accessibility event in addition
4864     *          to the text added by the super implementation:
4865     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4866     *     super.onPopulateAccessibilityEvent(event);
4867     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
4868     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
4869     *         mCurrentDate.getTimeInMillis(), flags);
4870     *     event.getText().add(selectedDateUtterance);
4871     * }</pre>
4872     * <p>
4873     * If an {@link AccessibilityDelegate} has been specified via calling
4874     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4875     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
4876     * is responsible for handling this call.
4877     * </p>
4878     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4879     * information to the event, in case the default implementation has basic information to add.
4880     * </p>
4881     *
4882     * @param event The accessibility event which to populate.
4883     *
4884     * @see #sendAccessibilityEvent(int)
4885     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4886     */
4887    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4888        if (mAccessibilityDelegate != null) {
4889            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
4890        } else {
4891            onPopulateAccessibilityEventInternal(event);
4892        }
4893    }
4894
4895    /**
4896     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
4897     *
4898     * Note: Called from the default {@link AccessibilityDelegate}.
4899     */
4900    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4901    }
4902
4903    /**
4904     * Initializes an {@link AccessibilityEvent} with information about
4905     * this View which is the event source. In other words, the source of
4906     * an accessibility event is the view whose state change triggered firing
4907     * the event.
4908     * <p>
4909     * Example: Setting the password property of an event in addition
4910     *          to properties set by the super implementation:
4911     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4912     *     super.onInitializeAccessibilityEvent(event);
4913     *     event.setPassword(true);
4914     * }</pre>
4915     * <p>
4916     * If an {@link AccessibilityDelegate} has been specified via calling
4917     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4918     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
4919     * is responsible for handling this call.
4920     * </p>
4921     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4922     * information to the event, in case the default implementation has basic information to add.
4923     * </p>
4924     * @param event The event to initialize.
4925     *
4926     * @see #sendAccessibilityEvent(int)
4927     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4928     */
4929    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4930        if (mAccessibilityDelegate != null) {
4931            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
4932        } else {
4933            onInitializeAccessibilityEventInternal(event);
4934        }
4935    }
4936
4937    /**
4938     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4939     *
4940     * Note: Called from the default {@link AccessibilityDelegate}.
4941     */
4942    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
4943        event.setSource(this);
4944        event.setClassName(View.class.getName());
4945        event.setPackageName(getContext().getPackageName());
4946        event.setEnabled(isEnabled());
4947        event.setContentDescription(mContentDescription);
4948
4949        switch (event.getEventType()) {
4950            case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
4951                ArrayList<View> focusablesTempList = (mAttachInfo != null)
4952                        ? mAttachInfo.mTempArrayList : new ArrayList<View>();
4953                getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
4954                event.setItemCount(focusablesTempList.size());
4955                event.setCurrentItemIndex(focusablesTempList.indexOf(this));
4956                if (mAttachInfo != null) {
4957                    focusablesTempList.clear();
4958                }
4959            } break;
4960            case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: {
4961                CharSequence text = getIterableTextForAccessibility();
4962                if (text != null && text.length() > 0) {
4963                    event.setFromIndex(getAccessibilitySelectionStart());
4964                    event.setToIndex(getAccessibilitySelectionEnd());
4965                    event.setItemCount(text.length());
4966                }
4967            } break;
4968        }
4969    }
4970
4971    /**
4972     * Returns an {@link AccessibilityNodeInfo} representing this view from the
4973     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
4974     * This method is responsible for obtaining an accessibility node info from a
4975     * pool of reusable instances and calling
4976     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
4977     * initialize the former.
4978     * <p>
4979     * Note: The client is responsible for recycling the obtained instance by calling
4980     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
4981     * </p>
4982     *
4983     * @return A populated {@link AccessibilityNodeInfo}.
4984     *
4985     * @see AccessibilityNodeInfo
4986     */
4987    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
4988        if (mAccessibilityDelegate != null) {
4989            return mAccessibilityDelegate.createAccessibilityNodeInfo(this);
4990        } else {
4991            return createAccessibilityNodeInfoInternal();
4992        }
4993    }
4994
4995    /**
4996     * @see #createAccessibilityNodeInfo()
4997     */
4998    AccessibilityNodeInfo createAccessibilityNodeInfoInternal() {
4999        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
5000        if (provider != null) {
5001            return provider.createAccessibilityNodeInfo(View.NO_ID);
5002        } else {
5003            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
5004            onInitializeAccessibilityNodeInfo(info);
5005            return info;
5006        }
5007    }
5008
5009    /**
5010     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
5011     * The base implementation sets:
5012     * <ul>
5013     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
5014     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
5015     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
5016     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
5017     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
5018     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
5019     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
5020     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
5021     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
5022     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
5023     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
5024     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
5025     * </ul>
5026     * <p>
5027     * Subclasses should override this method, call the super implementation,
5028     * and set additional attributes.
5029     * </p>
5030     * <p>
5031     * If an {@link AccessibilityDelegate} has been specified via calling
5032     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5033     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
5034     * is responsible for handling this call.
5035     * </p>
5036     *
5037     * @param info The instance to initialize.
5038     */
5039    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
5040        if (mAccessibilityDelegate != null) {
5041            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
5042        } else {
5043            onInitializeAccessibilityNodeInfoInternal(info);
5044        }
5045    }
5046
5047    /**
5048     * Gets the location of this view in screen coordintates.
5049     *
5050     * @param outRect The output location
5051     */
5052    void getBoundsOnScreen(Rect outRect) {
5053        if (mAttachInfo == null) {
5054            return;
5055        }
5056
5057        RectF position = mAttachInfo.mTmpTransformRect;
5058        position.set(0, 0, mRight - mLeft, mBottom - mTop);
5059
5060        if (!hasIdentityMatrix()) {
5061            getMatrix().mapRect(position);
5062        }
5063
5064        position.offset(mLeft, mTop);
5065
5066        ViewParent parent = mParent;
5067        while (parent instanceof View) {
5068            View parentView = (View) parent;
5069
5070            position.offset(-parentView.mScrollX, -parentView.mScrollY);
5071
5072            if (!parentView.hasIdentityMatrix()) {
5073                parentView.getMatrix().mapRect(position);
5074            }
5075
5076            position.offset(parentView.mLeft, parentView.mTop);
5077
5078            parent = parentView.mParent;
5079        }
5080
5081        if (parent instanceof ViewRootImpl) {
5082            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
5083            position.offset(0, -viewRootImpl.mCurScrollY);
5084        }
5085
5086        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
5087
5088        outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f),
5089                (int) (position.right + 0.5f), (int) (position.bottom + 0.5f));
5090    }
5091
5092    /**
5093     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
5094     *
5095     * Note: Called from the default {@link AccessibilityDelegate}.
5096     */
5097    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
5098        Rect bounds = mAttachInfo.mTmpInvalRect;
5099
5100        getDrawingRect(bounds);
5101        info.setBoundsInParent(bounds);
5102
5103        getBoundsOnScreen(bounds);
5104        info.setBoundsInScreen(bounds);
5105
5106        ViewParent parent = getParentForAccessibility();
5107        if (parent instanceof View) {
5108            info.setParent((View) parent);
5109        }
5110
5111        if (mID != View.NO_ID) {
5112            View rootView = getRootView();
5113            if (rootView == null) {
5114                rootView = this;
5115            }
5116            View label = rootView.findLabelForView(this, mID);
5117            if (label != null) {
5118                info.setLabeledBy(label);
5119            }
5120
5121            if ((mAttachInfo.mAccessibilityFetchFlags
5122                    & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0
5123                    && Resources.resourceHasPackage(mID)) {
5124                try {
5125                    String viewId = getResources().getResourceName(mID);
5126                    info.setViewIdResourceName(viewId);
5127                } catch (Resources.NotFoundException nfe) {
5128                    /* ignore */
5129                }
5130            }
5131        }
5132
5133        if (mLabelForId != View.NO_ID) {
5134            View rootView = getRootView();
5135            if (rootView == null) {
5136                rootView = this;
5137            }
5138            View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId);
5139            if (labeled != null) {
5140                info.setLabelFor(labeled);
5141            }
5142        }
5143
5144        info.setVisibleToUser(isVisibleToUser());
5145
5146        info.setPackageName(mContext.getPackageName());
5147        info.setClassName(View.class.getName());
5148        info.setContentDescription(getContentDescription());
5149
5150        info.setEnabled(isEnabled());
5151        info.setClickable(isClickable());
5152        info.setFocusable(isFocusable());
5153        info.setFocused(isFocused());
5154        info.setAccessibilityFocused(isAccessibilityFocused());
5155        info.setSelected(isSelected());
5156        info.setLongClickable(isLongClickable());
5157
5158        // TODO: These make sense only if we are in an AdapterView but all
5159        // views can be selected. Maybe from accessibility perspective
5160        // we should report as selectable view in an AdapterView.
5161        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
5162        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
5163
5164        if (isFocusable()) {
5165            if (isFocused()) {
5166                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
5167            } else {
5168                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
5169            }
5170        }
5171
5172        if (!isAccessibilityFocused()) {
5173            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
5174        } else {
5175            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
5176        }
5177
5178        if (isClickable() && isEnabled()) {
5179            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
5180        }
5181
5182        if (isLongClickable() && isEnabled()) {
5183            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
5184        }
5185
5186        CharSequence text = getIterableTextForAccessibility();
5187        if (text != null && text.length() > 0) {
5188            info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd());
5189
5190            info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION);
5191            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
5192            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
5193            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
5194                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
5195                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
5196        }
5197    }
5198
5199    private View findLabelForView(View view, int labeledId) {
5200        if (mMatchLabelForPredicate == null) {
5201            mMatchLabelForPredicate = new MatchLabelForPredicate();
5202        }
5203        mMatchLabelForPredicate.mLabeledId = labeledId;
5204        return findViewByPredicateInsideOut(view, mMatchLabelForPredicate);
5205    }
5206
5207    /**
5208     * Computes whether this view is visible to the user. Such a view is
5209     * attached, visible, all its predecessors are visible, it is not clipped
5210     * entirely by its predecessors, and has an alpha greater than zero.
5211     *
5212     * @return Whether the view is visible on the screen.
5213     *
5214     * @hide
5215     */
5216    protected boolean isVisibleToUser() {
5217        return isVisibleToUser(null);
5218    }
5219
5220    /**
5221     * Computes whether the given portion of this view is visible to the user.
5222     * Such a view is attached, visible, all its predecessors are visible,
5223     * has an alpha greater than zero, and the specified portion is not
5224     * clipped entirely by its predecessors.
5225     *
5226     * @param boundInView the portion of the view to test; coordinates should be relative; may be
5227     *                    <code>null</code>, and the entire view will be tested in this case.
5228     *                    When <code>true</code> is returned by the function, the actual visible
5229     *                    region will be stored in this parameter; that is, if boundInView is fully
5230     *                    contained within the view, no modification will be made, otherwise regions
5231     *                    outside of the visible area of the view will be clipped.
5232     *
5233     * @return Whether the specified portion of the view is visible on the screen.
5234     *
5235     * @hide
5236     */
5237    protected boolean isVisibleToUser(Rect boundInView) {
5238        if (mAttachInfo != null) {
5239            // Attached to invisible window means this view is not visible.
5240            if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
5241                return false;
5242            }
5243            // An invisible predecessor or one with alpha zero means
5244            // that this view is not visible to the user.
5245            Object current = this;
5246            while (current instanceof View) {
5247                View view = (View) current;
5248                // We have attach info so this view is attached and there is no
5249                // need to check whether we reach to ViewRootImpl on the way up.
5250                if (view.getAlpha() <= 0 || view.getVisibility() != VISIBLE) {
5251                    return false;
5252                }
5253                current = view.mParent;
5254            }
5255            // Check if the view is entirely covered by its predecessors.
5256            Rect visibleRect = mAttachInfo.mTmpInvalRect;
5257            Point offset = mAttachInfo.mPoint;
5258            if (!getGlobalVisibleRect(visibleRect, offset)) {
5259                return false;
5260            }
5261            // Check if the visible portion intersects the rectangle of interest.
5262            if (boundInView != null) {
5263                visibleRect.offset(-offset.x, -offset.y);
5264                return boundInView.intersect(visibleRect);
5265            }
5266            return true;
5267        }
5268        return false;
5269    }
5270
5271    /**
5272     * Returns the delegate for implementing accessibility support via
5273     * composition. For more details see {@link AccessibilityDelegate}.
5274     *
5275     * @return The delegate, or null if none set.
5276     *
5277     * @hide
5278     */
5279    public AccessibilityDelegate getAccessibilityDelegate() {
5280        return mAccessibilityDelegate;
5281    }
5282
5283    /**
5284     * Sets a delegate for implementing accessibility support via composition as
5285     * opposed to inheritance. The delegate's primary use is for implementing
5286     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
5287     *
5288     * @param delegate The delegate instance.
5289     *
5290     * @see AccessibilityDelegate
5291     */
5292    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
5293        mAccessibilityDelegate = delegate;
5294    }
5295
5296    /**
5297     * Gets the provider for managing a virtual view hierarchy rooted at this View
5298     * and reported to {@link android.accessibilityservice.AccessibilityService}s
5299     * that explore the window content.
5300     * <p>
5301     * If this method returns an instance, this instance is responsible for managing
5302     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
5303     * View including the one representing the View itself. Similarly the returned
5304     * instance is responsible for performing accessibility actions on any virtual
5305     * view or the root view itself.
5306     * </p>
5307     * <p>
5308     * If an {@link AccessibilityDelegate} has been specified via calling
5309     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5310     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
5311     * is responsible for handling this call.
5312     * </p>
5313     *
5314     * @return The provider.
5315     *
5316     * @see AccessibilityNodeProvider
5317     */
5318    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
5319        if (mAccessibilityDelegate != null) {
5320            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
5321        } else {
5322            return null;
5323        }
5324    }
5325
5326    /**
5327     * Gets the unique identifier of this view on the screen for accessibility purposes.
5328     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
5329     *
5330     * @return The view accessibility id.
5331     *
5332     * @hide
5333     */
5334    public int getAccessibilityViewId() {
5335        if (mAccessibilityViewId == NO_ID) {
5336            mAccessibilityViewId = sNextAccessibilityViewId++;
5337        }
5338        return mAccessibilityViewId;
5339    }
5340
5341    /**
5342     * Gets the unique identifier of the window in which this View reseides.
5343     *
5344     * @return The window accessibility id.
5345     *
5346     * @hide
5347     */
5348    public int getAccessibilityWindowId() {
5349        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID;
5350    }
5351
5352    /**
5353     * Gets the {@link View} description. It briefly describes the view and is
5354     * primarily used for accessibility support. Set this property to enable
5355     * better accessibility support for your application. This is especially
5356     * true for views that do not have textual representation (For example,
5357     * ImageButton).
5358     *
5359     * @return The content description.
5360     *
5361     * @attr ref android.R.styleable#View_contentDescription
5362     */
5363    @ViewDebug.ExportedProperty(category = "accessibility")
5364    public CharSequence getContentDescription() {
5365        return mContentDescription;
5366    }
5367
5368    /**
5369     * Sets the {@link View} description. It briefly describes the view and is
5370     * primarily used for accessibility support. Set this property to enable
5371     * better accessibility support for your application. This is especially
5372     * true for views that do not have textual representation (For example,
5373     * ImageButton).
5374     *
5375     * @param contentDescription The content description.
5376     *
5377     * @attr ref android.R.styleable#View_contentDescription
5378     */
5379    @RemotableViewMethod
5380    public void setContentDescription(CharSequence contentDescription) {
5381        if (mContentDescription == null) {
5382            if (contentDescription == null) {
5383                return;
5384            }
5385        } else if (mContentDescription.equals(contentDescription)) {
5386            return;
5387        }
5388        mContentDescription = contentDescription;
5389        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
5390        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
5391            setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
5392            notifySubtreeAccessibilityStateChangedIfNeeded();
5393        } else {
5394            notifyViewAccessibilityStateChangedIfNeeded();
5395        }
5396    }
5397
5398    /**
5399     * Gets the id of a view for which this view serves as a label for
5400     * accessibility purposes.
5401     *
5402     * @return The labeled view id.
5403     */
5404    @ViewDebug.ExportedProperty(category = "accessibility")
5405    public int getLabelFor() {
5406        return mLabelForId;
5407    }
5408
5409    /**
5410     * Sets the id of a view for which this view serves as a label for
5411     * accessibility purposes.
5412     *
5413     * @param id The labeled view id.
5414     */
5415    @RemotableViewMethod
5416    public void setLabelFor(int id) {
5417        mLabelForId = id;
5418        if (mLabelForId != View.NO_ID
5419                && mID == View.NO_ID) {
5420            mID = generateViewId();
5421        }
5422    }
5423
5424    /**
5425     * Invoked whenever this view loses focus, either by losing window focus or by losing
5426     * focus within its window. This method can be used to clear any state tied to the
5427     * focus. For instance, if a button is held pressed with the trackball and the window
5428     * loses focus, this method can be used to cancel the press.
5429     *
5430     * Subclasses of View overriding this method should always call super.onFocusLost().
5431     *
5432     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
5433     * @see #onWindowFocusChanged(boolean)
5434     *
5435     * @hide pending API council approval
5436     */
5437    protected void onFocusLost() {
5438        resetPressedState();
5439    }
5440
5441    private void resetPressedState() {
5442        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
5443            return;
5444        }
5445
5446        if (isPressed()) {
5447            setPressed(false);
5448
5449            if (!mHasPerformedLongPress) {
5450                removeLongPressCallback();
5451            }
5452        }
5453    }
5454
5455    /**
5456     * Returns true if this view has focus
5457     *
5458     * @return True if this view has focus, false otherwise.
5459     */
5460    @ViewDebug.ExportedProperty(category = "focus")
5461    public boolean isFocused() {
5462        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
5463    }
5464
5465    /**
5466     * Find the view in the hierarchy rooted at this view that currently has
5467     * focus.
5468     *
5469     * @return The view that currently has focus, or null if no focused view can
5470     *         be found.
5471     */
5472    public View findFocus() {
5473        return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
5474    }
5475
5476    /**
5477     * Indicates whether this view is one of the set of scrollable containers in
5478     * its window.
5479     *
5480     * @return whether this view is one of the set of scrollable containers in
5481     * its window
5482     *
5483     * @attr ref android.R.styleable#View_isScrollContainer
5484     */
5485    public boolean isScrollContainer() {
5486        return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0;
5487    }
5488
5489    /**
5490     * Change whether this view is one of the set of scrollable containers in
5491     * its window.  This will be used to determine whether the window can
5492     * resize or must pan when a soft input area is open -- scrollable
5493     * containers allow the window to use resize mode since the container
5494     * will appropriately shrink.
5495     *
5496     * @attr ref android.R.styleable#View_isScrollContainer
5497     */
5498    public void setScrollContainer(boolean isScrollContainer) {
5499        if (isScrollContainer) {
5500            if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) {
5501                mAttachInfo.mScrollContainers.add(this);
5502                mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
5503            }
5504            mPrivateFlags |= PFLAG_SCROLL_CONTAINER;
5505        } else {
5506            if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
5507                mAttachInfo.mScrollContainers.remove(this);
5508            }
5509            mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED);
5510        }
5511    }
5512
5513    /**
5514     * Returns the quality of the drawing cache.
5515     *
5516     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5517     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5518     *
5519     * @see #setDrawingCacheQuality(int)
5520     * @see #setDrawingCacheEnabled(boolean)
5521     * @see #isDrawingCacheEnabled()
5522     *
5523     * @attr ref android.R.styleable#View_drawingCacheQuality
5524     */
5525    public int getDrawingCacheQuality() {
5526        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
5527    }
5528
5529    /**
5530     * Set the drawing cache quality of this view. This value is used only when the
5531     * drawing cache is enabled
5532     *
5533     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5534     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5535     *
5536     * @see #getDrawingCacheQuality()
5537     * @see #setDrawingCacheEnabled(boolean)
5538     * @see #isDrawingCacheEnabled()
5539     *
5540     * @attr ref android.R.styleable#View_drawingCacheQuality
5541     */
5542    public void setDrawingCacheQuality(int quality) {
5543        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
5544    }
5545
5546    /**
5547     * Returns whether the screen should remain on, corresponding to the current
5548     * value of {@link #KEEP_SCREEN_ON}.
5549     *
5550     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
5551     *
5552     * @see #setKeepScreenOn(boolean)
5553     *
5554     * @attr ref android.R.styleable#View_keepScreenOn
5555     */
5556    public boolean getKeepScreenOn() {
5557        return (mViewFlags & KEEP_SCREEN_ON) != 0;
5558    }
5559
5560    /**
5561     * Controls whether the screen should remain on, modifying the
5562     * value of {@link #KEEP_SCREEN_ON}.
5563     *
5564     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
5565     *
5566     * @see #getKeepScreenOn()
5567     *
5568     * @attr ref android.R.styleable#View_keepScreenOn
5569     */
5570    public void setKeepScreenOn(boolean keepScreenOn) {
5571        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
5572    }
5573
5574    /**
5575     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5576     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5577     *
5578     * @attr ref android.R.styleable#View_nextFocusLeft
5579     */
5580    public int getNextFocusLeftId() {
5581        return mNextFocusLeftId;
5582    }
5583
5584    /**
5585     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5586     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
5587     * decide automatically.
5588     *
5589     * @attr ref android.R.styleable#View_nextFocusLeft
5590     */
5591    public void setNextFocusLeftId(int nextFocusLeftId) {
5592        mNextFocusLeftId = nextFocusLeftId;
5593    }
5594
5595    /**
5596     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5597     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5598     *
5599     * @attr ref android.R.styleable#View_nextFocusRight
5600     */
5601    public int getNextFocusRightId() {
5602        return mNextFocusRightId;
5603    }
5604
5605    /**
5606     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5607     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
5608     * decide automatically.
5609     *
5610     * @attr ref android.R.styleable#View_nextFocusRight
5611     */
5612    public void setNextFocusRightId(int nextFocusRightId) {
5613        mNextFocusRightId = nextFocusRightId;
5614    }
5615
5616    /**
5617     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5618     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5619     *
5620     * @attr ref android.R.styleable#View_nextFocusUp
5621     */
5622    public int getNextFocusUpId() {
5623        return mNextFocusUpId;
5624    }
5625
5626    /**
5627     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5628     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
5629     * decide automatically.
5630     *
5631     * @attr ref android.R.styleable#View_nextFocusUp
5632     */
5633    public void setNextFocusUpId(int nextFocusUpId) {
5634        mNextFocusUpId = nextFocusUpId;
5635    }
5636
5637    /**
5638     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5639     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5640     *
5641     * @attr ref android.R.styleable#View_nextFocusDown
5642     */
5643    public int getNextFocusDownId() {
5644        return mNextFocusDownId;
5645    }
5646
5647    /**
5648     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5649     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
5650     * decide automatically.
5651     *
5652     * @attr ref android.R.styleable#View_nextFocusDown
5653     */
5654    public void setNextFocusDownId(int nextFocusDownId) {
5655        mNextFocusDownId = nextFocusDownId;
5656    }
5657
5658    /**
5659     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5660     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5661     *
5662     * @attr ref android.R.styleable#View_nextFocusForward
5663     */
5664    public int getNextFocusForwardId() {
5665        return mNextFocusForwardId;
5666    }
5667
5668    /**
5669     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5670     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
5671     * decide automatically.
5672     *
5673     * @attr ref android.R.styleable#View_nextFocusForward
5674     */
5675    public void setNextFocusForwardId(int nextFocusForwardId) {
5676        mNextFocusForwardId = nextFocusForwardId;
5677    }
5678
5679    /**
5680     * Returns the visibility of this view and all of its ancestors
5681     *
5682     * @return True if this view and all of its ancestors are {@link #VISIBLE}
5683     */
5684    public boolean isShown() {
5685        View current = this;
5686        //noinspection ConstantConditions
5687        do {
5688            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
5689                return false;
5690            }
5691            ViewParent parent = current.mParent;
5692            if (parent == null) {
5693                return false; // We are not attached to the view root
5694            }
5695            if (!(parent instanceof View)) {
5696                return true;
5697            }
5698            current = (View) parent;
5699        } while (current != null);
5700
5701        return false;
5702    }
5703
5704    /**
5705     * Called by the view hierarchy when the content insets for a window have
5706     * changed, to allow it to adjust its content to fit within those windows.
5707     * The content insets tell you the space that the status bar, input method,
5708     * and other system windows infringe on the application's window.
5709     *
5710     * <p>You do not normally need to deal with this function, since the default
5711     * window decoration given to applications takes care of applying it to the
5712     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
5713     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
5714     * and your content can be placed under those system elements.  You can then
5715     * use this method within your view hierarchy if you have parts of your UI
5716     * which you would like to ensure are not being covered.
5717     *
5718     * <p>The default implementation of this method simply applies the content
5719     * insets to the view's padding, consuming that content (modifying the
5720     * insets to be 0), and returning true.  This behavior is off by default, but can
5721     * be enabled through {@link #setFitsSystemWindows(boolean)}.
5722     *
5723     * <p>This function's traversal down the hierarchy is depth-first.  The same content
5724     * insets object is propagated down the hierarchy, so any changes made to it will
5725     * be seen by all following views (including potentially ones above in
5726     * the hierarchy since this is a depth-first traversal).  The first view
5727     * that returns true will abort the entire traversal.
5728     *
5729     * <p>The default implementation works well for a situation where it is
5730     * used with a container that covers the entire window, allowing it to
5731     * apply the appropriate insets to its content on all edges.  If you need
5732     * a more complicated layout (such as two different views fitting system
5733     * windows, one on the top of the window, and one on the bottom),
5734     * you can override the method and handle the insets however you would like.
5735     * Note that the insets provided by the framework are always relative to the
5736     * far edges of the window, not accounting for the location of the called view
5737     * within that window.  (In fact when this method is called you do not yet know
5738     * where the layout will place the view, as it is done before layout happens.)
5739     *
5740     * <p>Note: unlike many View methods, there is no dispatch phase to this
5741     * call.  If you are overriding it in a ViewGroup and want to allow the
5742     * call to continue to your children, you must be sure to call the super
5743     * implementation.
5744     *
5745     * <p>Here is a sample layout that makes use of fitting system windows
5746     * to have controls for a video view placed inside of the window decorations
5747     * that it hides and shows.  This can be used with code like the second
5748     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
5749     *
5750     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
5751     *
5752     * @param insets Current content insets of the window.  Prior to
5753     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
5754     * the insets or else you and Android will be unhappy.
5755     *
5756     * @return {@code true} if this view applied the insets and it should not
5757     * continue propagating further down the hierarchy, {@code false} otherwise.
5758     * @see #getFitsSystemWindows()
5759     * @see #setFitsSystemWindows(boolean)
5760     * @see #setSystemUiVisibility(int)
5761     */
5762    protected boolean fitSystemWindows(Rect insets) {
5763        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
5764            mUserPaddingStart = UNDEFINED_PADDING;
5765            mUserPaddingEnd = UNDEFINED_PADDING;
5766            Rect localInsets = sThreadLocal.get();
5767            if (localInsets == null) {
5768                localInsets = new Rect();
5769                sThreadLocal.set(localInsets);
5770            }
5771            boolean res = computeFitSystemWindows(insets, localInsets);
5772            internalSetPadding(localInsets.left, localInsets.top,
5773                    localInsets.right, localInsets.bottom);
5774            return res;
5775        }
5776        return false;
5777    }
5778
5779    /**
5780     * @hide Compute the insets that should be consumed by this view and the ones
5781     * that should propagate to those under it.
5782     */
5783    protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) {
5784        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
5785                || mAttachInfo == null
5786                || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0
5787                        && !mAttachInfo.mOverscanRequested)) {
5788            outLocalInsets.set(inoutInsets);
5789            inoutInsets.set(0, 0, 0, 0);
5790            return true;
5791        } else {
5792            // The application wants to take care of fitting system window for
5793            // the content...  however we still need to take care of any overscan here.
5794            final Rect overscan = mAttachInfo.mOverscanInsets;
5795            outLocalInsets.set(overscan);
5796            inoutInsets.left -= overscan.left;
5797            inoutInsets.top -= overscan.top;
5798            inoutInsets.right -= overscan.right;
5799            inoutInsets.bottom -= overscan.bottom;
5800            return false;
5801        }
5802    }
5803
5804    /**
5805     * Sets whether or not this view should account for system screen decorations
5806     * such as the status bar and inset its content; that is, controlling whether
5807     * the default implementation of {@link #fitSystemWindows(Rect)} will be
5808     * executed.  See that method for more details.
5809     *
5810     * <p>Note that if you are providing your own implementation of
5811     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
5812     * flag to true -- your implementation will be overriding the default
5813     * implementation that checks this flag.
5814     *
5815     * @param fitSystemWindows If true, then the default implementation of
5816     * {@link #fitSystemWindows(Rect)} will be executed.
5817     *
5818     * @attr ref android.R.styleable#View_fitsSystemWindows
5819     * @see #getFitsSystemWindows()
5820     * @see #fitSystemWindows(Rect)
5821     * @see #setSystemUiVisibility(int)
5822     */
5823    public void setFitsSystemWindows(boolean fitSystemWindows) {
5824        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
5825    }
5826
5827    /**
5828     * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method
5829     * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)}
5830     * will be executed.
5831     *
5832     * @return {@code true} if the default implementation of
5833     * {@link #fitSystemWindows(Rect)} will be executed.
5834     *
5835     * @attr ref android.R.styleable#View_fitsSystemWindows
5836     * @see #setFitsSystemWindows(boolean)
5837     * @see #fitSystemWindows(Rect)
5838     * @see #setSystemUiVisibility(int)
5839     */
5840    public boolean getFitsSystemWindows() {
5841        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
5842    }
5843
5844    /** @hide */
5845    public boolean fitsSystemWindows() {
5846        return getFitsSystemWindows();
5847    }
5848
5849    /**
5850     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
5851     */
5852    public void requestFitSystemWindows() {
5853        if (mParent != null) {
5854            mParent.requestFitSystemWindows();
5855        }
5856    }
5857
5858    /**
5859     * For use by PhoneWindow to make its own system window fitting optional.
5860     * @hide
5861     */
5862    public void makeOptionalFitsSystemWindows() {
5863        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
5864    }
5865
5866    /**
5867     * Returns the visibility status for this view.
5868     *
5869     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5870     * @attr ref android.R.styleable#View_visibility
5871     */
5872    @ViewDebug.ExportedProperty(mapping = {
5873        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
5874        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
5875        @ViewDebug.IntToString(from = GONE,      to = "GONE")
5876    })
5877    public int getVisibility() {
5878        return mViewFlags & VISIBILITY_MASK;
5879    }
5880
5881    /**
5882     * Set the enabled state of this view.
5883     *
5884     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5885     * @attr ref android.R.styleable#View_visibility
5886     */
5887    @RemotableViewMethod
5888    public void setVisibility(int visibility) {
5889        setFlags(visibility, VISIBILITY_MASK);
5890        if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false);
5891    }
5892
5893    /**
5894     * Returns the enabled status for this view. The interpretation of the
5895     * enabled state varies by subclass.
5896     *
5897     * @return True if this view is enabled, false otherwise.
5898     */
5899    @ViewDebug.ExportedProperty
5900    public boolean isEnabled() {
5901        return (mViewFlags & ENABLED_MASK) == ENABLED;
5902    }
5903
5904    /**
5905     * Set the enabled state of this view. The interpretation of the enabled
5906     * state varies by subclass.
5907     *
5908     * @param enabled True if this view is enabled, false otherwise.
5909     */
5910    @RemotableViewMethod
5911    public void setEnabled(boolean enabled) {
5912        if (enabled == isEnabled()) return;
5913
5914        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
5915
5916        /*
5917         * The View most likely has to change its appearance, so refresh
5918         * the drawable state.
5919         */
5920        refreshDrawableState();
5921
5922        // Invalidate too, since the default behavior for views is to be
5923        // be drawn at 50% alpha rather than to change the drawable.
5924        invalidate(true);
5925    }
5926
5927    /**
5928     * Set whether this view can receive the focus.
5929     *
5930     * Setting this to false will also ensure that this view is not focusable
5931     * in touch mode.
5932     *
5933     * @param focusable If true, this view can receive the focus.
5934     *
5935     * @see #setFocusableInTouchMode(boolean)
5936     * @attr ref android.R.styleable#View_focusable
5937     */
5938    public void setFocusable(boolean focusable) {
5939        if (!focusable) {
5940            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
5941        }
5942        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
5943    }
5944
5945    /**
5946     * Set whether this view can receive focus while in touch mode.
5947     *
5948     * Setting this to true will also ensure that this view is focusable.
5949     *
5950     * @param focusableInTouchMode If true, this view can receive the focus while
5951     *   in touch mode.
5952     *
5953     * @see #setFocusable(boolean)
5954     * @attr ref android.R.styleable#View_focusableInTouchMode
5955     */
5956    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
5957        // Focusable in touch mode should always be set before the focusable flag
5958        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
5959        // which, in touch mode, will not successfully request focus on this view
5960        // because the focusable in touch mode flag is not set
5961        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
5962        if (focusableInTouchMode) {
5963            setFlags(FOCUSABLE, FOCUSABLE_MASK);
5964        }
5965    }
5966
5967    /**
5968     * Set whether this view should have sound effects enabled for events such as
5969     * clicking and touching.
5970     *
5971     * <p>You may wish to disable sound effects for a view if you already play sounds,
5972     * for instance, a dial key that plays dtmf tones.
5973     *
5974     * @param soundEffectsEnabled whether sound effects are enabled for this view.
5975     * @see #isSoundEffectsEnabled()
5976     * @see #playSoundEffect(int)
5977     * @attr ref android.R.styleable#View_soundEffectsEnabled
5978     */
5979    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
5980        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
5981    }
5982
5983    /**
5984     * @return whether this view should have sound effects enabled for events such as
5985     *     clicking and touching.
5986     *
5987     * @see #setSoundEffectsEnabled(boolean)
5988     * @see #playSoundEffect(int)
5989     * @attr ref android.R.styleable#View_soundEffectsEnabled
5990     */
5991    @ViewDebug.ExportedProperty
5992    public boolean isSoundEffectsEnabled() {
5993        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
5994    }
5995
5996    /**
5997     * Set whether this view should have haptic feedback for events such as
5998     * long presses.
5999     *
6000     * <p>You may wish to disable haptic feedback if your view already controls
6001     * its own haptic feedback.
6002     *
6003     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
6004     * @see #isHapticFeedbackEnabled()
6005     * @see #performHapticFeedback(int)
6006     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
6007     */
6008    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
6009        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
6010    }
6011
6012    /**
6013     * @return whether this view should have haptic feedback enabled for events
6014     * long presses.
6015     *
6016     * @see #setHapticFeedbackEnabled(boolean)
6017     * @see #performHapticFeedback(int)
6018     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
6019     */
6020    @ViewDebug.ExportedProperty
6021    public boolean isHapticFeedbackEnabled() {
6022        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
6023    }
6024
6025    /**
6026     * Returns the layout direction for this view.
6027     *
6028     * @return One of {@link #LAYOUT_DIRECTION_LTR},
6029     *   {@link #LAYOUT_DIRECTION_RTL},
6030     *   {@link #LAYOUT_DIRECTION_INHERIT} or
6031     *   {@link #LAYOUT_DIRECTION_LOCALE}.
6032     *
6033     * @attr ref android.R.styleable#View_layoutDirection
6034     *
6035     * @hide
6036     */
6037    @ViewDebug.ExportedProperty(category = "layout", mapping = {
6038        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
6039        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
6040        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
6041        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
6042    })
6043    public int getRawLayoutDirection() {
6044        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
6045    }
6046
6047    /**
6048     * Set the layout direction for this view. This will propagate a reset of layout direction
6049     * resolution to the view's children and resolve layout direction for this view.
6050     *
6051     * @param layoutDirection the layout direction to set. Should be one of:
6052     *
6053     * {@link #LAYOUT_DIRECTION_LTR},
6054     * {@link #LAYOUT_DIRECTION_RTL},
6055     * {@link #LAYOUT_DIRECTION_INHERIT},
6056     * {@link #LAYOUT_DIRECTION_LOCALE}.
6057     *
6058     * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution
6059     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
6060     * will return the default {@link #LAYOUT_DIRECTION_LTR}.
6061     *
6062     * @attr ref android.R.styleable#View_layoutDirection
6063     */
6064    @RemotableViewMethod
6065    public void setLayoutDirection(int layoutDirection) {
6066        if (getRawLayoutDirection() != layoutDirection) {
6067            // Reset the current layout direction and the resolved one
6068            mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK;
6069            resetRtlProperties();
6070            // Set the new layout direction (filtered)
6071            mPrivateFlags2 |=
6072                    ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK);
6073            // We need to resolve all RTL properties as they all depend on layout direction
6074            resolveRtlPropertiesIfNeeded();
6075            requestLayout();
6076            invalidate(true);
6077        }
6078    }
6079
6080    /**
6081     * Returns the resolved layout direction for this view.
6082     *
6083     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
6084     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
6085     *
6086     * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version
6087     * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}.
6088     *
6089     * @attr ref android.R.styleable#View_layoutDirection
6090     */
6091    @ViewDebug.ExportedProperty(category = "layout", mapping = {
6092        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
6093        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
6094    })
6095    public int getLayoutDirection() {
6096        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
6097        if (targetSdkVersion < JELLY_BEAN_MR1) {
6098            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
6099            return LAYOUT_DIRECTION_RESOLVED_DEFAULT;
6100        }
6101        return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ==
6102                PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
6103    }
6104
6105    /**
6106     * Indicates whether or not this view's layout is right-to-left. This is resolved from
6107     * layout attribute and/or the inherited value from the parent
6108     *
6109     * @return true if the layout is right-to-left.
6110     *
6111     * @hide
6112     */
6113    @ViewDebug.ExportedProperty(category = "layout")
6114    public boolean isLayoutRtl() {
6115        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
6116    }
6117
6118    /**
6119     * Indicates whether the view is currently tracking transient state that the
6120     * app should not need to concern itself with saving and restoring, but that
6121     * the framework should take special note to preserve when possible.
6122     *
6123     * <p>A view with transient state cannot be trivially rebound from an external
6124     * data source, such as an adapter binding item views in a list. This may be
6125     * because the view is performing an animation, tracking user selection
6126     * of content, or similar.</p>
6127     *
6128     * @return true if the view has transient state
6129     */
6130    @ViewDebug.ExportedProperty(category = "layout")
6131    public boolean hasTransientState() {
6132        return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE;
6133    }
6134
6135    /**
6136     * Set whether this view is currently tracking transient state that the
6137     * framework should attempt to preserve when possible. This flag is reference counted,
6138     * so every call to setHasTransientState(true) should be paired with a later call
6139     * to setHasTransientState(false).
6140     *
6141     * <p>A view with transient state cannot be trivially rebound from an external
6142     * data source, such as an adapter binding item views in a list. This may be
6143     * because the view is performing an animation, tracking user selection
6144     * of content, or similar.</p>
6145     *
6146     * @param hasTransientState true if this view has transient state
6147     */
6148    public void setHasTransientState(boolean hasTransientState) {
6149        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
6150                mTransientStateCount - 1;
6151        if (mTransientStateCount < 0) {
6152            mTransientStateCount = 0;
6153            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
6154                    "unmatched pair of setHasTransientState calls");
6155        } else if ((hasTransientState && mTransientStateCount == 1) ||
6156                (!hasTransientState && mTransientStateCount == 0)) {
6157            // update flag if we've just incremented up from 0 or decremented down to 0
6158            mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) |
6159                    (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0);
6160            if (mParent != null) {
6161                try {
6162                    mParent.childHasTransientStateChanged(this, hasTransientState);
6163                } catch (AbstractMethodError e) {
6164                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
6165                            " does not fully implement ViewParent", e);
6166                }
6167            }
6168        }
6169    }
6170
6171    /**
6172     * Returns true if this view is currently attached to a window.
6173     */
6174    public boolean isAttachedToWindow() {
6175        return mAttachInfo != null;
6176    }
6177
6178    /**
6179     * Returns true if this view has been through at least one layout since it
6180     * was last attached to or detached from a window.
6181     */
6182    public boolean isLaidOut() {
6183        return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT;
6184    }
6185
6186    /**
6187     * If this view doesn't do any drawing on its own, set this flag to
6188     * allow further optimizations. By default, this flag is not set on
6189     * View, but could be set on some View subclasses such as ViewGroup.
6190     *
6191     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
6192     * you should clear this flag.
6193     *
6194     * @param willNotDraw whether or not this View draw on its own
6195     */
6196    public void setWillNotDraw(boolean willNotDraw) {
6197        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
6198    }
6199
6200    /**
6201     * Returns whether or not this View draws on its own.
6202     *
6203     * @return true if this view has nothing to draw, false otherwise
6204     */
6205    @ViewDebug.ExportedProperty(category = "drawing")
6206    public boolean willNotDraw() {
6207        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
6208    }
6209
6210    /**
6211     * When a View's drawing cache is enabled, drawing is redirected to an
6212     * offscreen bitmap. Some views, like an ImageView, must be able to
6213     * bypass this mechanism if they already draw a single bitmap, to avoid
6214     * unnecessary usage of the memory.
6215     *
6216     * @param willNotCacheDrawing true if this view does not cache its
6217     *        drawing, false otherwise
6218     */
6219    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
6220        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
6221    }
6222
6223    /**
6224     * Returns whether or not this View can cache its drawing or not.
6225     *
6226     * @return true if this view does not cache its drawing, false otherwise
6227     */
6228    @ViewDebug.ExportedProperty(category = "drawing")
6229    public boolean willNotCacheDrawing() {
6230        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
6231    }
6232
6233    /**
6234     * Indicates whether this view reacts to click events or not.
6235     *
6236     * @return true if the view is clickable, false otherwise
6237     *
6238     * @see #setClickable(boolean)
6239     * @attr ref android.R.styleable#View_clickable
6240     */
6241    @ViewDebug.ExportedProperty
6242    public boolean isClickable() {
6243        return (mViewFlags & CLICKABLE) == CLICKABLE;
6244    }
6245
6246    /**
6247     * Enables or disables click events for this view. When a view
6248     * is clickable it will change its state to "pressed" on every click.
6249     * Subclasses should set the view clickable to visually react to
6250     * user's clicks.
6251     *
6252     * @param clickable true to make the view clickable, false otherwise
6253     *
6254     * @see #isClickable()
6255     * @attr ref android.R.styleable#View_clickable
6256     */
6257    public void setClickable(boolean clickable) {
6258        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
6259    }
6260
6261    /**
6262     * Indicates whether this view reacts to long click events or not.
6263     *
6264     * @return true if the view is long clickable, false otherwise
6265     *
6266     * @see #setLongClickable(boolean)
6267     * @attr ref android.R.styleable#View_longClickable
6268     */
6269    public boolean isLongClickable() {
6270        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
6271    }
6272
6273    /**
6274     * Enables or disables long click events for this view. When a view is long
6275     * clickable it reacts to the user holding down the button for a longer
6276     * duration than a tap. This event can either launch the listener or a
6277     * context menu.
6278     *
6279     * @param longClickable true to make the view long clickable, false otherwise
6280     * @see #isLongClickable()
6281     * @attr ref android.R.styleable#View_longClickable
6282     */
6283    public void setLongClickable(boolean longClickable) {
6284        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
6285    }
6286
6287    /**
6288     * Sets the pressed state for this view.
6289     *
6290     * @see #isClickable()
6291     * @see #setClickable(boolean)
6292     *
6293     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
6294     *        the View's internal state from a previously set "pressed" state.
6295     */
6296    public void setPressed(boolean pressed) {
6297        final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
6298
6299        if (pressed) {
6300            mPrivateFlags |= PFLAG_PRESSED;
6301        } else {
6302            mPrivateFlags &= ~PFLAG_PRESSED;
6303        }
6304
6305        if (needsRefresh) {
6306            refreshDrawableState();
6307        }
6308        dispatchSetPressed(pressed);
6309    }
6310
6311    /**
6312     * Dispatch setPressed to all of this View's children.
6313     *
6314     * @see #setPressed(boolean)
6315     *
6316     * @param pressed The new pressed state
6317     */
6318    protected void dispatchSetPressed(boolean pressed) {
6319    }
6320
6321    /**
6322     * Indicates whether the view is currently in pressed state. Unless
6323     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
6324     * the pressed state.
6325     *
6326     * @see #setPressed(boolean)
6327     * @see #isClickable()
6328     * @see #setClickable(boolean)
6329     *
6330     * @return true if the view is currently pressed, false otherwise
6331     */
6332    public boolean isPressed() {
6333        return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED;
6334    }
6335
6336    /**
6337     * Indicates whether this view will save its state (that is,
6338     * whether its {@link #onSaveInstanceState} method will be called).
6339     *
6340     * @return Returns true if the view state saving is enabled, else false.
6341     *
6342     * @see #setSaveEnabled(boolean)
6343     * @attr ref android.R.styleable#View_saveEnabled
6344     */
6345    public boolean isSaveEnabled() {
6346        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
6347    }
6348
6349    /**
6350     * Controls whether the saving of this view's state is
6351     * enabled (that is, whether its {@link #onSaveInstanceState} method
6352     * will be called).  Note that even if freezing is enabled, the
6353     * view still must have an id assigned to it (via {@link #setId(int)})
6354     * for its state to be saved.  This flag can only disable the
6355     * saving of this view; any child views may still have their state saved.
6356     *
6357     * @param enabled Set to false to <em>disable</em> state saving, or true
6358     * (the default) to allow it.
6359     *
6360     * @see #isSaveEnabled()
6361     * @see #setId(int)
6362     * @see #onSaveInstanceState()
6363     * @attr ref android.R.styleable#View_saveEnabled
6364     */
6365    public void setSaveEnabled(boolean enabled) {
6366        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
6367    }
6368
6369    /**
6370     * Gets whether the framework should discard touches when the view's
6371     * window is obscured by another visible window.
6372     * Refer to the {@link View} security documentation for more details.
6373     *
6374     * @return True if touch filtering is enabled.
6375     *
6376     * @see #setFilterTouchesWhenObscured(boolean)
6377     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
6378     */
6379    @ViewDebug.ExportedProperty
6380    public boolean getFilterTouchesWhenObscured() {
6381        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
6382    }
6383
6384    /**
6385     * Sets whether the framework should discard touches when the view's
6386     * window is obscured by another visible window.
6387     * Refer to the {@link View} security documentation for more details.
6388     *
6389     * @param enabled True if touch filtering should be enabled.
6390     *
6391     * @see #getFilterTouchesWhenObscured
6392     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
6393     */
6394    public void setFilterTouchesWhenObscured(boolean enabled) {
6395        setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
6396                FILTER_TOUCHES_WHEN_OBSCURED);
6397    }
6398
6399    /**
6400     * Indicates whether the entire hierarchy under this view will save its
6401     * state when a state saving traversal occurs from its parent.  The default
6402     * is true; if false, these views will not be saved unless
6403     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
6404     *
6405     * @return Returns true if the view state saving from parent is enabled, else false.
6406     *
6407     * @see #setSaveFromParentEnabled(boolean)
6408     */
6409    public boolean isSaveFromParentEnabled() {
6410        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
6411    }
6412
6413    /**
6414     * Controls whether the entire hierarchy under this view will save its
6415     * state when a state saving traversal occurs from its parent.  The default
6416     * is true; if false, these views will not be saved unless
6417     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
6418     *
6419     * @param enabled Set to false to <em>disable</em> state saving, or true
6420     * (the default) to allow it.
6421     *
6422     * @see #isSaveFromParentEnabled()
6423     * @see #setId(int)
6424     * @see #onSaveInstanceState()
6425     */
6426    public void setSaveFromParentEnabled(boolean enabled) {
6427        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
6428    }
6429
6430
6431    /**
6432     * Returns whether this View is able to take focus.
6433     *
6434     * @return True if this view can take focus, or false otherwise.
6435     * @attr ref android.R.styleable#View_focusable
6436     */
6437    @ViewDebug.ExportedProperty(category = "focus")
6438    public final boolean isFocusable() {
6439        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
6440    }
6441
6442    /**
6443     * When a view is focusable, it may not want to take focus when in touch mode.
6444     * For example, a button would like focus when the user is navigating via a D-pad
6445     * so that the user can click on it, but once the user starts touching the screen,
6446     * the button shouldn't take focus
6447     * @return Whether the view is focusable in touch mode.
6448     * @attr ref android.R.styleable#View_focusableInTouchMode
6449     */
6450    @ViewDebug.ExportedProperty
6451    public final boolean isFocusableInTouchMode() {
6452        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
6453    }
6454
6455    /**
6456     * Find the nearest view in the specified direction that can take focus.
6457     * This does not actually give focus to that view.
6458     *
6459     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6460     *
6461     * @return The nearest focusable in the specified direction, or null if none
6462     *         can be found.
6463     */
6464    public View focusSearch(int direction) {
6465        if (mParent != null) {
6466            return mParent.focusSearch(this, direction);
6467        } else {
6468            return null;
6469        }
6470    }
6471
6472    /**
6473     * This method is the last chance for the focused view and its ancestors to
6474     * respond to an arrow key. This is called when the focused view did not
6475     * consume the key internally, nor could the view system find a new view in
6476     * the requested direction to give focus to.
6477     *
6478     * @param focused The currently focused view.
6479     * @param direction The direction focus wants to move. One of FOCUS_UP,
6480     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
6481     * @return True if the this view consumed this unhandled move.
6482     */
6483    public boolean dispatchUnhandledMove(View focused, int direction) {
6484        return false;
6485    }
6486
6487    /**
6488     * If a user manually specified the next view id for a particular direction,
6489     * use the root to look up the view.
6490     * @param root The root view of the hierarchy containing this view.
6491     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
6492     * or FOCUS_BACKWARD.
6493     * @return The user specified next view, or null if there is none.
6494     */
6495    View findUserSetNextFocus(View root, int direction) {
6496        switch (direction) {
6497            case FOCUS_LEFT:
6498                if (mNextFocusLeftId == View.NO_ID) return null;
6499                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
6500            case FOCUS_RIGHT:
6501                if (mNextFocusRightId == View.NO_ID) return null;
6502                return findViewInsideOutShouldExist(root, mNextFocusRightId);
6503            case FOCUS_UP:
6504                if (mNextFocusUpId == View.NO_ID) return null;
6505                return findViewInsideOutShouldExist(root, mNextFocusUpId);
6506            case FOCUS_DOWN:
6507                if (mNextFocusDownId == View.NO_ID) return null;
6508                return findViewInsideOutShouldExist(root, mNextFocusDownId);
6509            case FOCUS_FORWARD:
6510                if (mNextFocusForwardId == View.NO_ID) return null;
6511                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
6512            case FOCUS_BACKWARD: {
6513                if (mID == View.NO_ID) return null;
6514                final int id = mID;
6515                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
6516                    @Override
6517                    public boolean apply(View t) {
6518                        return t.mNextFocusForwardId == id;
6519                    }
6520                });
6521            }
6522        }
6523        return null;
6524    }
6525
6526    private View findViewInsideOutShouldExist(View root, int id) {
6527        if (mMatchIdPredicate == null) {
6528            mMatchIdPredicate = new MatchIdPredicate();
6529        }
6530        mMatchIdPredicate.mId = id;
6531        View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate);
6532        if (result == null) {
6533            Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id);
6534        }
6535        return result;
6536    }
6537
6538    /**
6539     * Find and return all focusable views that are descendants of this view,
6540     * possibly including this view if it is focusable itself.
6541     *
6542     * @param direction The direction of the focus
6543     * @return A list of focusable views
6544     */
6545    public ArrayList<View> getFocusables(int direction) {
6546        ArrayList<View> result = new ArrayList<View>(24);
6547        addFocusables(result, direction);
6548        return result;
6549    }
6550
6551    /**
6552     * Add any focusable views that are descendants of this view (possibly
6553     * including this view if it is focusable itself) to views.  If we are in touch mode,
6554     * only add views that are also focusable in touch mode.
6555     *
6556     * @param views Focusable views found so far
6557     * @param direction The direction of the focus
6558     */
6559    public void addFocusables(ArrayList<View> views, int direction) {
6560        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
6561    }
6562
6563    /**
6564     * Adds any focusable views that are descendants of this view (possibly
6565     * including this view if it is focusable itself) to views. This method
6566     * adds all focusable views regardless if we are in touch mode or
6567     * only views focusable in touch mode if we are in touch mode or
6568     * only views that can take accessibility focus if accessibility is enabeld
6569     * depending on the focusable mode paramater.
6570     *
6571     * @param views Focusable views found so far or null if all we are interested is
6572     *        the number of focusables.
6573     * @param direction The direction of the focus.
6574     * @param focusableMode The type of focusables to be added.
6575     *
6576     * @see #FOCUSABLES_ALL
6577     * @see #FOCUSABLES_TOUCH_MODE
6578     */
6579    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
6580        if (views == null) {
6581            return;
6582        }
6583        if (!isFocusable()) {
6584            return;
6585        }
6586        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
6587                && isInTouchMode() && !isFocusableInTouchMode()) {
6588            return;
6589        }
6590        views.add(this);
6591    }
6592
6593    /**
6594     * Finds the Views that contain given text. The containment is case insensitive.
6595     * The search is performed by either the text that the View renders or the content
6596     * description that describes the view for accessibility purposes and the view does
6597     * not render or both. Clients can specify how the search is to be performed via
6598     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
6599     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
6600     *
6601     * @param outViews The output list of matching Views.
6602     * @param searched The text to match against.
6603     *
6604     * @see #FIND_VIEWS_WITH_TEXT
6605     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
6606     * @see #setContentDescription(CharSequence)
6607     */
6608    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) {
6609        if (getAccessibilityNodeProvider() != null) {
6610            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
6611                outViews.add(this);
6612            }
6613        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
6614                && (searched != null && searched.length() > 0)
6615                && (mContentDescription != null && mContentDescription.length() > 0)) {
6616            String searchedLowerCase = searched.toString().toLowerCase();
6617            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
6618            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
6619                outViews.add(this);
6620            }
6621        }
6622    }
6623
6624    /**
6625     * Find and return all touchable views that are descendants of this view,
6626     * possibly including this view if it is touchable itself.
6627     *
6628     * @return A list of touchable views
6629     */
6630    public ArrayList<View> getTouchables() {
6631        ArrayList<View> result = new ArrayList<View>();
6632        addTouchables(result);
6633        return result;
6634    }
6635
6636    /**
6637     * Add any touchable views that are descendants of this view (possibly
6638     * including this view if it is touchable itself) to views.
6639     *
6640     * @param views Touchable views found so far
6641     */
6642    public void addTouchables(ArrayList<View> views) {
6643        final int viewFlags = mViewFlags;
6644
6645        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
6646                && (viewFlags & ENABLED_MASK) == ENABLED) {
6647            views.add(this);
6648        }
6649    }
6650
6651    /**
6652     * Returns whether this View is accessibility focused.
6653     *
6654     * @return True if this View is accessibility focused.
6655     */
6656    boolean isAccessibilityFocused() {
6657        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
6658    }
6659
6660    /**
6661     * Call this to try to give accessibility focus to this view.
6662     *
6663     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
6664     * returns false or the view is no visible or the view already has accessibility
6665     * focus.
6666     *
6667     * See also {@link #focusSearch(int)}, which is what you call to say that you
6668     * have focus, and you want your parent to look for the next one.
6669     *
6670     * @return Whether this view actually took accessibility focus.
6671     *
6672     * @hide
6673     */
6674    public boolean requestAccessibilityFocus() {
6675        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
6676        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
6677            return false;
6678        }
6679        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6680            return false;
6681        }
6682        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
6683            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
6684            ViewRootImpl viewRootImpl = getViewRootImpl();
6685            if (viewRootImpl != null) {
6686                viewRootImpl.setAccessibilityFocus(this, null);
6687            }
6688            invalidate();
6689            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
6690            return true;
6691        }
6692        return false;
6693    }
6694
6695    /**
6696     * Call this to try to clear accessibility focus of this view.
6697     *
6698     * See also {@link #focusSearch(int)}, which is what you call to say that you
6699     * have focus, and you want your parent to look for the next one.
6700     *
6701     * @hide
6702     */
6703    public void clearAccessibilityFocus() {
6704        clearAccessibilityFocusNoCallbacks();
6705        // Clear the global reference of accessibility focus if this
6706        // view or any of its descendants had accessibility focus.
6707        ViewRootImpl viewRootImpl = getViewRootImpl();
6708        if (viewRootImpl != null) {
6709            View focusHost = viewRootImpl.getAccessibilityFocusedHost();
6710            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
6711                viewRootImpl.setAccessibilityFocus(null, null);
6712            }
6713        }
6714    }
6715
6716    private void sendAccessibilityHoverEvent(int eventType) {
6717        // Since we are not delivering to a client accessibility events from not
6718        // important views (unless the clinet request that) we need to fire the
6719        // event from the deepest view exposed to the client. As a consequence if
6720        // the user crosses a not exposed view the client will see enter and exit
6721        // of the exposed predecessor followed by and enter and exit of that same
6722        // predecessor when entering and exiting the not exposed descendant. This
6723        // is fine since the client has a clear idea which view is hovered at the
6724        // price of a couple more events being sent. This is a simple and
6725        // working solution.
6726        View source = this;
6727        while (true) {
6728            if (source.includeForAccessibility()) {
6729                source.sendAccessibilityEvent(eventType);
6730                return;
6731            }
6732            ViewParent parent = source.getParent();
6733            if (parent instanceof View) {
6734                source = (View) parent;
6735            } else {
6736                return;
6737            }
6738        }
6739    }
6740
6741    /**
6742     * Clears accessibility focus without calling any callback methods
6743     * normally invoked in {@link #clearAccessibilityFocus()}. This method
6744     * is used for clearing accessibility focus when giving this focus to
6745     * another view.
6746     */
6747    void clearAccessibilityFocusNoCallbacks() {
6748        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
6749            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
6750            invalidate();
6751            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
6752        }
6753    }
6754
6755    /**
6756     * Call this to try to give focus to a specific view or to one of its
6757     * descendants.
6758     *
6759     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6760     * false), or if it is focusable and it is not focusable in touch mode
6761     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6762     *
6763     * See also {@link #focusSearch(int)}, which is what you call to say that you
6764     * have focus, and you want your parent to look for the next one.
6765     *
6766     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
6767     * {@link #FOCUS_DOWN} and <code>null</code>.
6768     *
6769     * @return Whether this view or one of its descendants actually took focus.
6770     */
6771    public final boolean requestFocus() {
6772        return requestFocus(View.FOCUS_DOWN);
6773    }
6774
6775    /**
6776     * Call this to try to give focus to a specific view or to one of its
6777     * descendants and give it a hint about what direction focus is heading.
6778     *
6779     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6780     * false), or if it is focusable and it is not focusable in touch mode
6781     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6782     *
6783     * See also {@link #focusSearch(int)}, which is what you call to say that you
6784     * have focus, and you want your parent to look for the next one.
6785     *
6786     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
6787     * <code>null</code> set for the previously focused rectangle.
6788     *
6789     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6790     * @return Whether this view or one of its descendants actually took focus.
6791     */
6792    public final boolean requestFocus(int direction) {
6793        return requestFocus(direction, null);
6794    }
6795
6796    /**
6797     * Call this to try to give focus to a specific view or to one of its descendants
6798     * and give it hints about the direction and a specific rectangle that the focus
6799     * is coming from.  The rectangle can help give larger views a finer grained hint
6800     * about where focus is coming from, and therefore, where to show selection, or
6801     * forward focus change internally.
6802     *
6803     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6804     * false), or if it is focusable and it is not focusable in touch mode
6805     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6806     *
6807     * A View will not take focus if it is not visible.
6808     *
6809     * A View will not take focus if one of its parents has
6810     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
6811     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
6812     *
6813     * See also {@link #focusSearch(int)}, which is what you call to say that you
6814     * have focus, and you want your parent to look for the next one.
6815     *
6816     * You may wish to override this method if your custom {@link View} has an internal
6817     * {@link View} that it wishes to forward the request to.
6818     *
6819     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6820     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
6821     *        to give a finer grained hint about where focus is coming from.  May be null
6822     *        if there is no hint.
6823     * @return Whether this view or one of its descendants actually took focus.
6824     */
6825    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
6826        return requestFocusNoSearch(direction, previouslyFocusedRect);
6827    }
6828
6829    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
6830        // need to be focusable
6831        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
6832                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6833            return false;
6834        }
6835
6836        // need to be focusable in touch mode if in touch mode
6837        if (isInTouchMode() &&
6838            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
6839               return false;
6840        }
6841
6842        // need to not have any parents blocking us
6843        if (hasAncestorThatBlocksDescendantFocus()) {
6844            return false;
6845        }
6846
6847        handleFocusGainInternal(direction, previouslyFocusedRect);
6848        return true;
6849    }
6850
6851    /**
6852     * Call this to try to give focus to a specific view or to one of its descendants. This is a
6853     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
6854     * touch mode to request focus when they are touched.
6855     *
6856     * @return Whether this view or one of its descendants actually took focus.
6857     *
6858     * @see #isInTouchMode()
6859     *
6860     */
6861    public final boolean requestFocusFromTouch() {
6862        // Leave touch mode if we need to
6863        if (isInTouchMode()) {
6864            ViewRootImpl viewRoot = getViewRootImpl();
6865            if (viewRoot != null) {
6866                viewRoot.ensureTouchMode(false);
6867            }
6868        }
6869        return requestFocus(View.FOCUS_DOWN);
6870    }
6871
6872    /**
6873     * @return Whether any ancestor of this view blocks descendant focus.
6874     */
6875    private boolean hasAncestorThatBlocksDescendantFocus() {
6876        ViewParent ancestor = mParent;
6877        while (ancestor instanceof ViewGroup) {
6878            final ViewGroup vgAncestor = (ViewGroup) ancestor;
6879            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
6880                return true;
6881            } else {
6882                ancestor = vgAncestor.getParent();
6883            }
6884        }
6885        return false;
6886    }
6887
6888    /**
6889     * Gets the mode for determining whether this View is important for accessibility
6890     * which is if it fires accessibility events and if it is reported to
6891     * accessibility services that query the screen.
6892     *
6893     * @return The mode for determining whether a View is important for accessibility.
6894     *
6895     * @attr ref android.R.styleable#View_importantForAccessibility
6896     *
6897     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
6898     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
6899     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
6900     */
6901    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
6902            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
6903            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
6904            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no")
6905        })
6906    public int getImportantForAccessibility() {
6907        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
6908                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
6909    }
6910
6911    /**
6912     * Sets how to determine whether this view is important for accessibility
6913     * which is if it fires accessibility events and if it is reported to
6914     * accessibility services that query the screen.
6915     *
6916     * @param mode How to determine whether this view is important for accessibility.
6917     *
6918     * @attr ref android.R.styleable#View_importantForAccessibility
6919     *
6920     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
6921     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
6922     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
6923     */
6924    public void setImportantForAccessibility(int mode) {
6925        final boolean oldIncludeForAccessibility = includeForAccessibility();
6926        if (mode != getImportantForAccessibility()) {
6927            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
6928            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
6929                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
6930            if (oldIncludeForAccessibility != includeForAccessibility()) {
6931                notifySubtreeAccessibilityStateChangedIfNeeded();
6932            } else {
6933                notifyViewAccessibilityStateChangedIfNeeded();
6934            }
6935        }
6936    }
6937
6938    /**
6939     * Gets whether this view should be exposed for accessibility.
6940     *
6941     * @return Whether the view is exposed for accessibility.
6942     *
6943     * @hide
6944     */
6945    public boolean isImportantForAccessibility() {
6946        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
6947                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
6948        switch (mode) {
6949            case IMPORTANT_FOR_ACCESSIBILITY_YES:
6950                return true;
6951            case IMPORTANT_FOR_ACCESSIBILITY_NO:
6952                return false;
6953            case IMPORTANT_FOR_ACCESSIBILITY_AUTO:
6954                return isActionableForAccessibility() || hasListenersForAccessibility()
6955                        || getAccessibilityNodeProvider() != null;
6956            default:
6957                throw new IllegalArgumentException("Unknow important for accessibility mode: "
6958                        + mode);
6959        }
6960    }
6961
6962    /**
6963     * Gets the parent for accessibility purposes. Note that the parent for
6964     * accessibility is not necessary the immediate parent. It is the first
6965     * predecessor that is important for accessibility.
6966     *
6967     * @return The parent for accessibility purposes.
6968     */
6969    public ViewParent getParentForAccessibility() {
6970        if (mParent instanceof View) {
6971            View parentView = (View) mParent;
6972            if (parentView.includeForAccessibility()) {
6973                return mParent;
6974            } else {
6975                return mParent.getParentForAccessibility();
6976            }
6977        }
6978        return null;
6979    }
6980
6981    /**
6982     * Adds the children of a given View for accessibility. Since some Views are
6983     * not important for accessibility the children for accessibility are not
6984     * necessarily direct children of the view, rather they are the first level of
6985     * descendants important for accessibility.
6986     *
6987     * @param children The list of children for accessibility.
6988     */
6989    public void addChildrenForAccessibility(ArrayList<View> children) {
6990        if (includeForAccessibility()) {
6991            children.add(this);
6992        }
6993    }
6994
6995    /**
6996     * Whether to regard this view for accessibility. A view is regarded for
6997     * accessibility if it is important for accessibility or the querying
6998     * accessibility service has explicitly requested that view not
6999     * important for accessibility are regarded.
7000     *
7001     * @return Whether to regard the view for accessibility.
7002     *
7003     * @hide
7004     */
7005    public boolean includeForAccessibility() {
7006        //noinspection SimplifiableIfStatement
7007        if (mAttachInfo != null) {
7008            return (mAttachInfo.mAccessibilityFetchFlags
7009                    & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0
7010                    || isImportantForAccessibility();
7011        }
7012        return false;
7013    }
7014
7015    /**
7016     * Returns whether the View is considered actionable from
7017     * accessibility perspective. Such view are important for
7018     * accessibility.
7019     *
7020     * @return True if the view is actionable for accessibility.
7021     *
7022     * @hide
7023     */
7024    public boolean isActionableForAccessibility() {
7025        return (isClickable() || isLongClickable() || isFocusable());
7026    }
7027
7028    /**
7029     * Returns whether the View has registered callbacks wich makes it
7030     * important for accessibility.
7031     *
7032     * @return True if the view is actionable for accessibility.
7033     */
7034    private boolean hasListenersForAccessibility() {
7035        ListenerInfo info = getListenerInfo();
7036        return mTouchDelegate != null || info.mOnKeyListener != null
7037                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
7038                || info.mOnHoverListener != null || info.mOnDragListener != null;
7039    }
7040
7041    /**
7042     * Notifies that the accessibility state of this view changed. The change
7043     * is local to this view and does not represent structural changes such
7044     * as children and parent. For example, the view became focusable. The
7045     * notification is at at most once every
7046     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
7047     * to avoid unnecessary load to the system. Also once a view has a pending
7048     * notifucation this method is a NOP until the notification has been sent.
7049     *
7050     * @hide
7051     */
7052    public void notifyViewAccessibilityStateChangedIfNeeded() {
7053        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
7054            return;
7055        }
7056        if (mSendViewStateChangedAccessibilityEvent == null) {
7057            mSendViewStateChangedAccessibilityEvent =
7058                    new SendViewStateChangedAccessibilityEvent();
7059        }
7060        mSendViewStateChangedAccessibilityEvent.runOrPost();
7061    }
7062
7063    /**
7064     * Notifies that the accessibility state of this view changed. The change
7065     * is *not* local to this view and does represent structural changes such
7066     * as children and parent. For example, the view size changed. The
7067     * notification is at at most once every
7068     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
7069     * to avoid unnecessary load to the system. Also once a view has a pending
7070     * notifucation this method is a NOP until the notification has been sent.
7071     *
7072     * @hide
7073     */
7074    public void notifySubtreeAccessibilityStateChangedIfNeeded() {
7075        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
7076            return;
7077        }
7078        if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) {
7079            mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
7080            if (mParent != null) {
7081                try {
7082                    mParent.childAccessibilityStateChanged(this);
7083                } catch (AbstractMethodError e) {
7084                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
7085                            " does not fully implement ViewParent", e);
7086                }
7087            }
7088        }
7089    }
7090
7091    /**
7092     * Reset the flag indicating the accessibility state of the subtree rooted
7093     * at this view changed.
7094     */
7095    void resetSubtreeAccessibilityStateChanged() {
7096        mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
7097    }
7098
7099    /**
7100     * Performs the specified accessibility action on the view. For
7101     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
7102     * <p>
7103     * If an {@link AccessibilityDelegate} has been specified via calling
7104     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
7105     * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
7106     * is responsible for handling this call.
7107     * </p>
7108     *
7109     * @param action The action to perform.
7110     * @param arguments Optional action arguments.
7111     * @return Whether the action was performed.
7112     */
7113    public boolean performAccessibilityAction(int action, Bundle arguments) {
7114      if (mAccessibilityDelegate != null) {
7115          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
7116      } else {
7117          return performAccessibilityActionInternal(action, arguments);
7118      }
7119    }
7120
7121   /**
7122    * @see #performAccessibilityAction(int, Bundle)
7123    *
7124    * Note: Called from the default {@link AccessibilityDelegate}.
7125    */
7126    boolean performAccessibilityActionInternal(int action, Bundle arguments) {
7127        switch (action) {
7128            case AccessibilityNodeInfo.ACTION_CLICK: {
7129                if (isClickable()) {
7130                    performClick();
7131                    return true;
7132                }
7133            } break;
7134            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
7135                if (isLongClickable()) {
7136                    performLongClick();
7137                    return true;
7138                }
7139            } break;
7140            case AccessibilityNodeInfo.ACTION_FOCUS: {
7141                if (!hasFocus()) {
7142                    // Get out of touch mode since accessibility
7143                    // wants to move focus around.
7144                    getViewRootImpl().ensureTouchMode(false);
7145                    return requestFocus();
7146                }
7147            } break;
7148            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
7149                if (hasFocus()) {
7150                    clearFocus();
7151                    return !isFocused();
7152                }
7153            } break;
7154            case AccessibilityNodeInfo.ACTION_SELECT: {
7155                if (!isSelected()) {
7156                    setSelected(true);
7157                    return isSelected();
7158                }
7159            } break;
7160            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
7161                if (isSelected()) {
7162                    setSelected(false);
7163                    return !isSelected();
7164                }
7165            } break;
7166            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
7167                if (!isAccessibilityFocused()) {
7168                    return requestAccessibilityFocus();
7169                }
7170            } break;
7171            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
7172                if (isAccessibilityFocused()) {
7173                    clearAccessibilityFocus();
7174                    return true;
7175                }
7176            } break;
7177            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
7178                if (arguments != null) {
7179                    final int granularity = arguments.getInt(
7180                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
7181                    final boolean extendSelection = arguments.getBoolean(
7182                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
7183                    return traverseAtGranularity(granularity, true, extendSelection);
7184                }
7185            } break;
7186            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
7187                if (arguments != null) {
7188                    final int granularity = arguments.getInt(
7189                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
7190                    final boolean extendSelection = arguments.getBoolean(
7191                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
7192                    return traverseAtGranularity(granularity, false, extendSelection);
7193                }
7194            } break;
7195            case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
7196                CharSequence text = getIterableTextForAccessibility();
7197                if (text == null) {
7198                    return false;
7199                }
7200                final int start = (arguments != null) ? arguments.getInt(
7201                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1;
7202                final int end = (arguments != null) ? arguments.getInt(
7203                AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1;
7204                // Only cursor position can be specified (selection length == 0)
7205                if ((getAccessibilitySelectionStart() != start
7206                        || getAccessibilitySelectionEnd() != end)
7207                        && (start == end)) {
7208                    setAccessibilitySelection(start, end);
7209                    notifyViewAccessibilityStateChangedIfNeeded();
7210                    return true;
7211                }
7212            } break;
7213        }
7214        return false;
7215    }
7216
7217    private boolean traverseAtGranularity(int granularity, boolean forward,
7218            boolean extendSelection) {
7219        CharSequence text = getIterableTextForAccessibility();
7220        if (text == null || text.length() == 0) {
7221            return false;
7222        }
7223        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
7224        if (iterator == null) {
7225            return false;
7226        }
7227        int current = getAccessibilitySelectionEnd();
7228        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7229            current = forward ? 0 : text.length();
7230        }
7231        final int[] range = forward ? iterator.following(current) : iterator.preceding(current);
7232        if (range == null) {
7233            return false;
7234        }
7235        final int segmentStart = range[0];
7236        final int segmentEnd = range[1];
7237        int selectionStart;
7238        int selectionEnd;
7239        if (extendSelection && isAccessibilitySelectionExtendable()) {
7240            selectionStart = getAccessibilitySelectionStart();
7241            if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7242                selectionStart = forward ? segmentStart : segmentEnd;
7243            }
7244            selectionEnd = forward ? segmentEnd : segmentStart;
7245        } else {
7246            selectionStart = selectionEnd= forward ? segmentEnd : segmentStart;
7247        }
7248        setAccessibilitySelection(selectionStart, selectionEnd);
7249        final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY
7250                : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY;
7251        sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd);
7252        return true;
7253    }
7254
7255    /**
7256     * Gets the text reported for accessibility purposes.
7257     *
7258     * @return The accessibility text.
7259     *
7260     * @hide
7261     */
7262    public CharSequence getIterableTextForAccessibility() {
7263        return getContentDescription();
7264    }
7265
7266    /**
7267     * Gets whether accessibility selection can be extended.
7268     *
7269     * @return If selection is extensible.
7270     *
7271     * @hide
7272     */
7273    public boolean isAccessibilitySelectionExtendable() {
7274        return false;
7275    }
7276
7277    /**
7278     * @hide
7279     */
7280    public int getAccessibilitySelectionStart() {
7281        return mAccessibilityCursorPosition;
7282    }
7283
7284    /**
7285     * @hide
7286     */
7287    public int getAccessibilitySelectionEnd() {
7288        return getAccessibilitySelectionStart();
7289    }
7290
7291    /**
7292     * @hide
7293     */
7294    public void setAccessibilitySelection(int start, int end) {
7295        if (start ==  end && end == mAccessibilityCursorPosition) {
7296            return;
7297        }
7298        if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) {
7299            mAccessibilityCursorPosition = start;
7300        } else {
7301            mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
7302        }
7303        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
7304    }
7305
7306    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
7307            int fromIndex, int toIndex) {
7308        if (mParent == null) {
7309            return;
7310        }
7311        AccessibilityEvent event = AccessibilityEvent.obtain(
7312                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
7313        onInitializeAccessibilityEvent(event);
7314        onPopulateAccessibilityEvent(event);
7315        event.setFromIndex(fromIndex);
7316        event.setToIndex(toIndex);
7317        event.setAction(action);
7318        event.setMovementGranularity(granularity);
7319        mParent.requestSendAccessibilityEvent(this, event);
7320    }
7321
7322    /**
7323     * @hide
7324     */
7325    public TextSegmentIterator getIteratorForGranularity(int granularity) {
7326        switch (granularity) {
7327            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
7328                CharSequence text = getIterableTextForAccessibility();
7329                if (text != null && text.length() > 0) {
7330                    CharacterTextSegmentIterator iterator =
7331                        CharacterTextSegmentIterator.getInstance(
7332                                mContext.getResources().getConfiguration().locale);
7333                    iterator.initialize(text.toString());
7334                    return iterator;
7335                }
7336            } break;
7337            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
7338                CharSequence text = getIterableTextForAccessibility();
7339                if (text != null && text.length() > 0) {
7340                    WordTextSegmentIterator iterator =
7341                        WordTextSegmentIterator.getInstance(
7342                                mContext.getResources().getConfiguration().locale);
7343                    iterator.initialize(text.toString());
7344                    return iterator;
7345                }
7346            } break;
7347            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
7348                CharSequence text = getIterableTextForAccessibility();
7349                if (text != null && text.length() > 0) {
7350                    ParagraphTextSegmentIterator iterator =
7351                        ParagraphTextSegmentIterator.getInstance();
7352                    iterator.initialize(text.toString());
7353                    return iterator;
7354                }
7355            } break;
7356        }
7357        return null;
7358    }
7359
7360    /**
7361     * @hide
7362     */
7363    public void dispatchStartTemporaryDetach() {
7364        clearAccessibilityFocus();
7365        clearDisplayList();
7366
7367        onStartTemporaryDetach();
7368    }
7369
7370    /**
7371     * This is called when a container is going to temporarily detach a child, with
7372     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
7373     * It will either be followed by {@link #onFinishTemporaryDetach()} or
7374     * {@link #onDetachedFromWindow()} when the container is done.
7375     */
7376    public void onStartTemporaryDetach() {
7377        removeUnsetPressCallback();
7378        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
7379    }
7380
7381    /**
7382     * @hide
7383     */
7384    public void dispatchFinishTemporaryDetach() {
7385        onFinishTemporaryDetach();
7386    }
7387
7388    /**
7389     * Called after {@link #onStartTemporaryDetach} when the container is done
7390     * changing the view.
7391     */
7392    public void onFinishTemporaryDetach() {
7393    }
7394
7395    /**
7396     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
7397     * for this view's window.  Returns null if the view is not currently attached
7398     * to the window.  Normally you will not need to use this directly, but
7399     * just use the standard high-level event callbacks like
7400     * {@link #onKeyDown(int, KeyEvent)}.
7401     */
7402    public KeyEvent.DispatcherState getKeyDispatcherState() {
7403        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
7404    }
7405
7406    /**
7407     * Dispatch a key event before it is processed by any input method
7408     * associated with the view hierarchy.  This can be used to intercept
7409     * key events in special situations before the IME consumes them; a
7410     * typical example would be handling the BACK key to update the application's
7411     * UI instead of allowing the IME to see it and close itself.
7412     *
7413     * @param event The key event to be dispatched.
7414     * @return True if the event was handled, false otherwise.
7415     */
7416    public boolean dispatchKeyEventPreIme(KeyEvent event) {
7417        return onKeyPreIme(event.getKeyCode(), event);
7418    }
7419
7420    /**
7421     * Dispatch a key event to the next view on the focus path. This path runs
7422     * from the top of the view tree down to the currently focused view. If this
7423     * view has focus, it will dispatch to itself. Otherwise it will dispatch
7424     * the next node down the focus path. This method also fires any key
7425     * listeners.
7426     *
7427     * @param event The key event to be dispatched.
7428     * @return True if the event was handled, false otherwise.
7429     */
7430    public boolean dispatchKeyEvent(KeyEvent event) {
7431        if (mInputEventConsistencyVerifier != null) {
7432            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
7433        }
7434
7435        // Give any attached key listener a first crack at the event.
7436        //noinspection SimplifiableIfStatement
7437        ListenerInfo li = mListenerInfo;
7438        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
7439                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
7440            return true;
7441        }
7442
7443        if (event.dispatch(this, mAttachInfo != null
7444                ? mAttachInfo.mKeyDispatchState : null, this)) {
7445            return true;
7446        }
7447
7448        if (mInputEventConsistencyVerifier != null) {
7449            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7450        }
7451        return false;
7452    }
7453
7454    /**
7455     * Dispatches a key shortcut event.
7456     *
7457     * @param event The key event to be dispatched.
7458     * @return True if the event was handled by the view, false otherwise.
7459     */
7460    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
7461        return onKeyShortcut(event.getKeyCode(), event);
7462    }
7463
7464    /**
7465     * Pass the touch screen motion event down to the target view, or this
7466     * view if it is the target.
7467     *
7468     * @param event The motion event to be dispatched.
7469     * @return True if the event was handled by the view, false otherwise.
7470     */
7471    public boolean dispatchTouchEvent(MotionEvent event) {
7472        if (mInputEventConsistencyVerifier != null) {
7473            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
7474        }
7475
7476        if (onFilterTouchEventForSecurity(event)) {
7477            //noinspection SimplifiableIfStatement
7478            ListenerInfo li = mListenerInfo;
7479            if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
7480                    && li.mOnTouchListener.onTouch(this, event)) {
7481                return true;
7482            }
7483
7484            if (onTouchEvent(event)) {
7485                return true;
7486            }
7487        }
7488
7489        if (mInputEventConsistencyVerifier != null) {
7490            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7491        }
7492        return false;
7493    }
7494
7495    /**
7496     * Filter the touch event to apply security policies.
7497     *
7498     * @param event The motion event to be filtered.
7499     * @return True if the event should be dispatched, false if the event should be dropped.
7500     *
7501     * @see #getFilterTouchesWhenObscured
7502     */
7503    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
7504        //noinspection RedundantIfStatement
7505        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
7506                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
7507            // Window is obscured, drop this touch.
7508            return false;
7509        }
7510        return true;
7511    }
7512
7513    /**
7514     * Pass a trackball motion event down to the focused view.
7515     *
7516     * @param event The motion event to be dispatched.
7517     * @return True if the event was handled by the view, false otherwise.
7518     */
7519    public boolean dispatchTrackballEvent(MotionEvent event) {
7520        if (mInputEventConsistencyVerifier != null) {
7521            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
7522        }
7523
7524        return onTrackballEvent(event);
7525    }
7526
7527    /**
7528     * Dispatch a generic motion event.
7529     * <p>
7530     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
7531     * are delivered to the view under the pointer.  All other generic motion events are
7532     * delivered to the focused view.  Hover events are handled specially and are delivered
7533     * to {@link #onHoverEvent(MotionEvent)}.
7534     * </p>
7535     *
7536     * @param event The motion event to be dispatched.
7537     * @return True if the event was handled by the view, false otherwise.
7538     */
7539    public boolean dispatchGenericMotionEvent(MotionEvent event) {
7540        if (mInputEventConsistencyVerifier != null) {
7541            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
7542        }
7543
7544        final int source = event.getSource();
7545        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
7546            final int action = event.getAction();
7547            if (action == MotionEvent.ACTION_HOVER_ENTER
7548                    || action == MotionEvent.ACTION_HOVER_MOVE
7549                    || action == MotionEvent.ACTION_HOVER_EXIT) {
7550                if (dispatchHoverEvent(event)) {
7551                    return true;
7552                }
7553            } else if (dispatchGenericPointerEvent(event)) {
7554                return true;
7555            }
7556        } else if (dispatchGenericFocusedEvent(event)) {
7557            return true;
7558        }
7559
7560        if (dispatchGenericMotionEventInternal(event)) {
7561            return true;
7562        }
7563
7564        if (mInputEventConsistencyVerifier != null) {
7565            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7566        }
7567        return false;
7568    }
7569
7570    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
7571        //noinspection SimplifiableIfStatement
7572        ListenerInfo li = mListenerInfo;
7573        if (li != null && li.mOnGenericMotionListener != null
7574                && (mViewFlags & ENABLED_MASK) == ENABLED
7575                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
7576            return true;
7577        }
7578
7579        if (onGenericMotionEvent(event)) {
7580            return true;
7581        }
7582
7583        if (mInputEventConsistencyVerifier != null) {
7584            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7585        }
7586        return false;
7587    }
7588
7589    /**
7590     * Dispatch a hover event.
7591     * <p>
7592     * Do not call this method directly.
7593     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7594     * </p>
7595     *
7596     * @param event The motion event to be dispatched.
7597     * @return True if the event was handled by the view, false otherwise.
7598     */
7599    protected boolean dispatchHoverEvent(MotionEvent event) {
7600        ListenerInfo li = mListenerInfo;
7601        //noinspection SimplifiableIfStatement
7602        if (li != null && li.mOnHoverListener != null
7603                && (mViewFlags & ENABLED_MASK) == ENABLED
7604                && li.mOnHoverListener.onHover(this, event)) {
7605            return true;
7606        }
7607
7608        return onHoverEvent(event);
7609    }
7610
7611    /**
7612     * Returns true if the view has a child to which it has recently sent
7613     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
7614     * it does not have a hovered child, then it must be the innermost hovered view.
7615     * @hide
7616     */
7617    protected boolean hasHoveredChild() {
7618        return false;
7619    }
7620
7621    /**
7622     * Dispatch a generic motion event to the view under the first pointer.
7623     * <p>
7624     * Do not call this method directly.
7625     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7626     * </p>
7627     *
7628     * @param event The motion event to be dispatched.
7629     * @return True if the event was handled by the view, false otherwise.
7630     */
7631    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
7632        return false;
7633    }
7634
7635    /**
7636     * Dispatch a generic motion event to the currently focused view.
7637     * <p>
7638     * Do not call this method directly.
7639     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7640     * </p>
7641     *
7642     * @param event The motion event to be dispatched.
7643     * @return True if the event was handled by the view, false otherwise.
7644     */
7645    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
7646        return false;
7647    }
7648
7649    /**
7650     * Dispatch a pointer event.
7651     * <p>
7652     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
7653     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
7654     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
7655     * and should not be expected to handle other pointing device features.
7656     * </p>
7657     *
7658     * @param event The motion event to be dispatched.
7659     * @return True if the event was handled by the view, false otherwise.
7660     * @hide
7661     */
7662    public final boolean dispatchPointerEvent(MotionEvent event) {
7663        if (event.isTouchEvent()) {
7664            return dispatchTouchEvent(event);
7665        } else {
7666            return dispatchGenericMotionEvent(event);
7667        }
7668    }
7669
7670    /**
7671     * Called when the window containing this view gains or loses window focus.
7672     * ViewGroups should override to route to their children.
7673     *
7674     * @param hasFocus True if the window containing this view now has focus,
7675     *        false otherwise.
7676     */
7677    public void dispatchWindowFocusChanged(boolean hasFocus) {
7678        onWindowFocusChanged(hasFocus);
7679    }
7680
7681    /**
7682     * Called when the window containing this view gains or loses focus.  Note
7683     * that this is separate from view focus: to receive key events, both
7684     * your view and its window must have focus.  If a window is displayed
7685     * on top of yours that takes input focus, then your own window will lose
7686     * focus but the view focus will remain unchanged.
7687     *
7688     * @param hasWindowFocus True if the window containing this view now has
7689     *        focus, false otherwise.
7690     */
7691    public void onWindowFocusChanged(boolean hasWindowFocus) {
7692        InputMethodManager imm = InputMethodManager.peekInstance();
7693        if (!hasWindowFocus) {
7694            if (isPressed()) {
7695                setPressed(false);
7696            }
7697            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
7698                imm.focusOut(this);
7699            }
7700            removeLongPressCallback();
7701            removeTapCallback();
7702            onFocusLost();
7703        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
7704            imm.focusIn(this);
7705        }
7706        refreshDrawableState();
7707    }
7708
7709    /**
7710     * Returns true if this view is in a window that currently has window focus.
7711     * Note that this is not the same as the view itself having focus.
7712     *
7713     * @return True if this view is in a window that currently has window focus.
7714     */
7715    public boolean hasWindowFocus() {
7716        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
7717    }
7718
7719    /**
7720     * Dispatch a view visibility change down the view hierarchy.
7721     * ViewGroups should override to route to their children.
7722     * @param changedView The view whose visibility changed. Could be 'this' or
7723     * an ancestor view.
7724     * @param visibility The new visibility of changedView: {@link #VISIBLE},
7725     * {@link #INVISIBLE} or {@link #GONE}.
7726     */
7727    protected void dispatchVisibilityChanged(View changedView, int visibility) {
7728        onVisibilityChanged(changedView, visibility);
7729    }
7730
7731    /**
7732     * Called when the visibility of the view or an ancestor of the view is changed.
7733     * @param changedView The view whose visibility changed. Could be 'this' or
7734     * an ancestor view.
7735     * @param visibility The new visibility of changedView: {@link #VISIBLE},
7736     * {@link #INVISIBLE} or {@link #GONE}.
7737     */
7738    protected void onVisibilityChanged(View changedView, int visibility) {
7739        if (visibility == VISIBLE) {
7740            if (mAttachInfo != null) {
7741                initialAwakenScrollBars();
7742            } else {
7743                mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
7744            }
7745        }
7746    }
7747
7748    /**
7749     * Dispatch a hint about whether this view is displayed. For instance, when
7750     * a View moves out of the screen, it might receives a display hint indicating
7751     * the view is not displayed. Applications should not <em>rely</em> on this hint
7752     * as there is no guarantee that they will receive one.
7753     *
7754     * @param hint A hint about whether or not this view is displayed:
7755     * {@link #VISIBLE} or {@link #INVISIBLE}.
7756     */
7757    public void dispatchDisplayHint(int hint) {
7758        onDisplayHint(hint);
7759    }
7760
7761    /**
7762     * Gives this view a hint about whether is displayed or not. For instance, when
7763     * a View moves out of the screen, it might receives a display hint indicating
7764     * the view is not displayed. Applications should not <em>rely</em> on this hint
7765     * as there is no guarantee that they will receive one.
7766     *
7767     * @param hint A hint about whether or not this view is displayed:
7768     * {@link #VISIBLE} or {@link #INVISIBLE}.
7769     */
7770    protected void onDisplayHint(int hint) {
7771    }
7772
7773    /**
7774     * Dispatch a window visibility change down the view hierarchy.
7775     * ViewGroups should override to route to their children.
7776     *
7777     * @param visibility The new visibility of the window.
7778     *
7779     * @see #onWindowVisibilityChanged(int)
7780     */
7781    public void dispatchWindowVisibilityChanged(int visibility) {
7782        onWindowVisibilityChanged(visibility);
7783    }
7784
7785    /**
7786     * Called when the window containing has change its visibility
7787     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
7788     * that this tells you whether or not your window is being made visible
7789     * to the window manager; this does <em>not</em> tell you whether or not
7790     * your window is obscured by other windows on the screen, even if it
7791     * is itself visible.
7792     *
7793     * @param visibility The new visibility of the window.
7794     */
7795    protected void onWindowVisibilityChanged(int visibility) {
7796        if (visibility == VISIBLE) {
7797            initialAwakenScrollBars();
7798        }
7799    }
7800
7801    /**
7802     * Returns the current visibility of the window this view is attached to
7803     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
7804     *
7805     * @return Returns the current visibility of the view's window.
7806     */
7807    public int getWindowVisibility() {
7808        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
7809    }
7810
7811    /**
7812     * Retrieve the overall visible display size in which the window this view is
7813     * attached to has been positioned in.  This takes into account screen
7814     * decorations above the window, for both cases where the window itself
7815     * is being position inside of them or the window is being placed under
7816     * then and covered insets are used for the window to position its content
7817     * inside.  In effect, this tells you the available area where content can
7818     * be placed and remain visible to users.
7819     *
7820     * <p>This function requires an IPC back to the window manager to retrieve
7821     * the requested information, so should not be used in performance critical
7822     * code like drawing.
7823     *
7824     * @param outRect Filled in with the visible display frame.  If the view
7825     * is not attached to a window, this is simply the raw display size.
7826     */
7827    public void getWindowVisibleDisplayFrame(Rect outRect) {
7828        if (mAttachInfo != null) {
7829            try {
7830                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
7831            } catch (RemoteException e) {
7832                return;
7833            }
7834            // XXX This is really broken, and probably all needs to be done
7835            // in the window manager, and we need to know more about whether
7836            // we want the area behind or in front of the IME.
7837            final Rect insets = mAttachInfo.mVisibleInsets;
7838            outRect.left += insets.left;
7839            outRect.top += insets.top;
7840            outRect.right -= insets.right;
7841            outRect.bottom -= insets.bottom;
7842            return;
7843        }
7844        // The view is not attached to a display so we don't have a context.
7845        // Make a best guess about the display size.
7846        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
7847        d.getRectSize(outRect);
7848    }
7849
7850    /**
7851     * Dispatch a notification about a resource configuration change down
7852     * the view hierarchy.
7853     * ViewGroups should override to route to their children.
7854     *
7855     * @param newConfig The new resource configuration.
7856     *
7857     * @see #onConfigurationChanged(android.content.res.Configuration)
7858     */
7859    public void dispatchConfigurationChanged(Configuration newConfig) {
7860        onConfigurationChanged(newConfig);
7861    }
7862
7863    /**
7864     * Called when the current configuration of the resources being used
7865     * by the application have changed.  You can use this to decide when
7866     * to reload resources that can changed based on orientation and other
7867     * configuration characterstics.  You only need to use this if you are
7868     * not relying on the normal {@link android.app.Activity} mechanism of
7869     * recreating the activity instance upon a configuration change.
7870     *
7871     * @param newConfig The new resource configuration.
7872     */
7873    protected void onConfigurationChanged(Configuration newConfig) {
7874    }
7875
7876    /**
7877     * Private function to aggregate all per-view attributes in to the view
7878     * root.
7879     */
7880    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
7881        performCollectViewAttributes(attachInfo, visibility);
7882    }
7883
7884    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
7885        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
7886            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
7887                attachInfo.mKeepScreenOn = true;
7888            }
7889            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
7890            ListenerInfo li = mListenerInfo;
7891            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
7892                attachInfo.mHasSystemUiListeners = true;
7893            }
7894        }
7895    }
7896
7897    void needGlobalAttributesUpdate(boolean force) {
7898        final AttachInfo ai = mAttachInfo;
7899        if (ai != null && !ai.mRecomputeGlobalAttributes) {
7900            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
7901                    || ai.mHasSystemUiListeners) {
7902                ai.mRecomputeGlobalAttributes = true;
7903            }
7904        }
7905    }
7906
7907    /**
7908     * Returns whether the device is currently in touch mode.  Touch mode is entered
7909     * once the user begins interacting with the device by touch, and affects various
7910     * things like whether focus is always visible to the user.
7911     *
7912     * @return Whether the device is in touch mode.
7913     */
7914    @ViewDebug.ExportedProperty
7915    public boolean isInTouchMode() {
7916        if (mAttachInfo != null) {
7917            return mAttachInfo.mInTouchMode;
7918        } else {
7919            return ViewRootImpl.isInTouchMode();
7920        }
7921    }
7922
7923    /**
7924     * Returns the context the view is running in, through which it can
7925     * access the current theme, resources, etc.
7926     *
7927     * @return The view's Context.
7928     */
7929    @ViewDebug.CapturedViewProperty
7930    public final Context getContext() {
7931        return mContext;
7932    }
7933
7934    /**
7935     * Handle a key event before it is processed by any input method
7936     * associated with the view hierarchy.  This can be used to intercept
7937     * key events in special situations before the IME consumes them; a
7938     * typical example would be handling the BACK key to update the application's
7939     * UI instead of allowing the IME to see it and close itself.
7940     *
7941     * @param keyCode The value in event.getKeyCode().
7942     * @param event Description of the key event.
7943     * @return If you handled the event, return true. If you want to allow the
7944     *         event to be handled by the next receiver, return false.
7945     */
7946    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
7947        return false;
7948    }
7949
7950    /**
7951     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
7952     * KeyEvent.Callback.onKeyDown()}: perform press of the view
7953     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
7954     * is released, if the view is enabled and clickable.
7955     *
7956     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7957     * although some may elect to do so in some situations. Do not rely on this to
7958     * catch software key presses.
7959     *
7960     * @param keyCode A key code that represents the button pressed, from
7961     *                {@link android.view.KeyEvent}.
7962     * @param event   The KeyEvent object that defines the button action.
7963     */
7964    public boolean onKeyDown(int keyCode, KeyEvent event) {
7965        boolean result = false;
7966
7967        if (KeyEvent.isConfirmKey(event.getKeyCode())) {
7968            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7969                return true;
7970            }
7971            // Long clickable items don't necessarily have to be clickable
7972            if (((mViewFlags & CLICKABLE) == CLICKABLE ||
7973                    (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
7974                    (event.getRepeatCount() == 0)) {
7975                setPressed(true);
7976                checkForLongClick(0);
7977                return true;
7978            }
7979        }
7980        return result;
7981    }
7982
7983    /**
7984     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
7985     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
7986     * the event).
7987     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7988     * although some may elect to do so in some situations. Do not rely on this to
7989     * catch software key presses.
7990     */
7991    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
7992        return false;
7993    }
7994
7995    /**
7996     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
7997     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
7998     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
7999     * {@link KeyEvent#KEYCODE_ENTER} is released.
8000     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8001     * although some may elect to do so in some situations. Do not rely on this to
8002     * catch software key presses.
8003     *
8004     * @param keyCode A key code that represents the button pressed, from
8005     *                {@link android.view.KeyEvent}.
8006     * @param event   The KeyEvent object that defines the button action.
8007     */
8008    public boolean onKeyUp(int keyCode, KeyEvent event) {
8009        boolean result = false;
8010
8011        switch (keyCode) {
8012            case KeyEvent.KEYCODE_DPAD_CENTER:
8013            case KeyEvent.KEYCODE_ENTER: {
8014                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
8015                    return true;
8016                }
8017                if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
8018                    setPressed(false);
8019
8020                    if (!mHasPerformedLongPress) {
8021                        // This is a tap, so remove the longpress check
8022                        removeLongPressCallback();
8023
8024                        result = performClick();
8025                    }
8026                }
8027                break;
8028            }
8029        }
8030        return result;
8031    }
8032
8033    /**
8034     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
8035     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
8036     * the event).
8037     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8038     * although some may elect to do so in some situations. Do not rely on this to
8039     * catch software key presses.
8040     *
8041     * @param keyCode     A key code that represents the button pressed, from
8042     *                    {@link android.view.KeyEvent}.
8043     * @param repeatCount The number of times the action was made.
8044     * @param event       The KeyEvent object that defines the button action.
8045     */
8046    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
8047        return false;
8048    }
8049
8050    /**
8051     * Called on the focused view when a key shortcut event is not handled.
8052     * Override this method to implement local key shortcuts for the View.
8053     * Key shortcuts can also be implemented by setting the
8054     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
8055     *
8056     * @param keyCode The value in event.getKeyCode().
8057     * @param event Description of the key event.
8058     * @return If you handled the event, return true. If you want to allow the
8059     *         event to be handled by the next receiver, return false.
8060     */
8061    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
8062        return false;
8063    }
8064
8065    /**
8066     * Check whether the called view is a text editor, in which case it
8067     * would make sense to automatically display a soft input window for
8068     * it.  Subclasses should override this if they implement
8069     * {@link #onCreateInputConnection(EditorInfo)} to return true if
8070     * a call on that method would return a non-null InputConnection, and
8071     * they are really a first-class editor that the user would normally
8072     * start typing on when the go into a window containing your view.
8073     *
8074     * <p>The default implementation always returns false.  This does
8075     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
8076     * will not be called or the user can not otherwise perform edits on your
8077     * view; it is just a hint to the system that this is not the primary
8078     * purpose of this view.
8079     *
8080     * @return Returns true if this view is a text editor, else false.
8081     */
8082    public boolean onCheckIsTextEditor() {
8083        return false;
8084    }
8085
8086    /**
8087     * Create a new InputConnection for an InputMethod to interact
8088     * with the view.  The default implementation returns null, since it doesn't
8089     * support input methods.  You can override this to implement such support.
8090     * This is only needed for views that take focus and text input.
8091     *
8092     * <p>When implementing this, you probably also want to implement
8093     * {@link #onCheckIsTextEditor()} to indicate you will return a
8094     * non-null InputConnection.
8095     *
8096     * @param outAttrs Fill in with attribute information about the connection.
8097     */
8098    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
8099        return null;
8100    }
8101
8102    /**
8103     * Called by the {@link android.view.inputmethod.InputMethodManager}
8104     * when a view who is not the current
8105     * input connection target is trying to make a call on the manager.  The
8106     * default implementation returns false; you can override this to return
8107     * true for certain views if you are performing InputConnection proxying
8108     * to them.
8109     * @param view The View that is making the InputMethodManager call.
8110     * @return Return true to allow the call, false to reject.
8111     */
8112    public boolean checkInputConnectionProxy(View view) {
8113        return false;
8114    }
8115
8116    /**
8117     * Show the context menu for this view. It is not safe to hold on to the
8118     * menu after returning from this method.
8119     *
8120     * You should normally not overload this method. Overload
8121     * {@link #onCreateContextMenu(ContextMenu)} or define an
8122     * {@link OnCreateContextMenuListener} to add items to the context menu.
8123     *
8124     * @param menu The context menu to populate
8125     */
8126    public void createContextMenu(ContextMenu menu) {
8127        ContextMenuInfo menuInfo = getContextMenuInfo();
8128
8129        // Sets the current menu info so all items added to menu will have
8130        // my extra info set.
8131        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
8132
8133        onCreateContextMenu(menu);
8134        ListenerInfo li = mListenerInfo;
8135        if (li != null && li.mOnCreateContextMenuListener != null) {
8136            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
8137        }
8138
8139        // Clear the extra information so subsequent items that aren't mine don't
8140        // have my extra info.
8141        ((MenuBuilder)menu).setCurrentMenuInfo(null);
8142
8143        if (mParent != null) {
8144            mParent.createContextMenu(menu);
8145        }
8146    }
8147
8148    /**
8149     * Views should implement this if they have extra information to associate
8150     * with the context menu. The return result is supplied as a parameter to
8151     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
8152     * callback.
8153     *
8154     * @return Extra information about the item for which the context menu
8155     *         should be shown. This information will vary across different
8156     *         subclasses of View.
8157     */
8158    protected ContextMenuInfo getContextMenuInfo() {
8159        return null;
8160    }
8161
8162    /**
8163     * Views should implement this if the view itself is going to add items to
8164     * the context menu.
8165     *
8166     * @param menu the context menu to populate
8167     */
8168    protected void onCreateContextMenu(ContextMenu menu) {
8169    }
8170
8171    /**
8172     * Implement this method to handle trackball motion events.  The
8173     * <em>relative</em> movement of the trackball since the last event
8174     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
8175     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
8176     * that a movement of 1 corresponds to the user pressing one DPAD key (so
8177     * they will often be fractional values, representing the more fine-grained
8178     * movement information available from a trackball).
8179     *
8180     * @param event The motion event.
8181     * @return True if the event was handled, false otherwise.
8182     */
8183    public boolean onTrackballEvent(MotionEvent event) {
8184        return false;
8185    }
8186
8187    /**
8188     * Implement this method to handle generic motion events.
8189     * <p>
8190     * Generic motion events describe joystick movements, mouse hovers, track pad
8191     * touches, scroll wheel movements and other input events.  The
8192     * {@link MotionEvent#getSource() source} of the motion event specifies
8193     * the class of input that was received.  Implementations of this method
8194     * must examine the bits in the source before processing the event.
8195     * The following code example shows how this is done.
8196     * </p><p>
8197     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
8198     * are delivered to the view under the pointer.  All other generic motion events are
8199     * delivered to the focused view.
8200     * </p>
8201     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
8202     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {
8203     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
8204     *             // process the joystick movement...
8205     *             return true;
8206     *         }
8207     *     }
8208     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
8209     *         switch (event.getAction()) {
8210     *             case MotionEvent.ACTION_HOVER_MOVE:
8211     *                 // process the mouse hover movement...
8212     *                 return true;
8213     *             case MotionEvent.ACTION_SCROLL:
8214     *                 // process the scroll wheel movement...
8215     *                 return true;
8216     *         }
8217     *     }
8218     *     return super.onGenericMotionEvent(event);
8219     * }</pre>
8220     *
8221     * @param event The generic motion event being processed.
8222     * @return True if the event was handled, false otherwise.
8223     */
8224    public boolean onGenericMotionEvent(MotionEvent event) {
8225        return false;
8226    }
8227
8228    /**
8229     * Implement this method to handle hover events.
8230     * <p>
8231     * This method is called whenever a pointer is hovering into, over, or out of the
8232     * bounds of a view and the view is not currently being touched.
8233     * Hover events are represented as pointer events with action
8234     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
8235     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
8236     * </p>
8237     * <ul>
8238     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
8239     * when the pointer enters the bounds of the view.</li>
8240     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
8241     * when the pointer has already entered the bounds of the view and has moved.</li>
8242     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
8243     * when the pointer has exited the bounds of the view or when the pointer is
8244     * about to go down due to a button click, tap, or similar user action that
8245     * causes the view to be touched.</li>
8246     * </ul>
8247     * <p>
8248     * The view should implement this method to return true to indicate that it is
8249     * handling the hover event, such as by changing its drawable state.
8250     * </p><p>
8251     * The default implementation calls {@link #setHovered} to update the hovered state
8252     * of the view when a hover enter or hover exit event is received, if the view
8253     * is enabled and is clickable.  The default implementation also sends hover
8254     * accessibility events.
8255     * </p>
8256     *
8257     * @param event The motion event that describes the hover.
8258     * @return True if the view handled the hover event.
8259     *
8260     * @see #isHovered
8261     * @see #setHovered
8262     * @see #onHoverChanged
8263     */
8264    public boolean onHoverEvent(MotionEvent event) {
8265        // The root view may receive hover (or touch) events that are outside the bounds of
8266        // the window.  This code ensures that we only send accessibility events for
8267        // hovers that are actually within the bounds of the root view.
8268        final int action = event.getActionMasked();
8269        if (!mSendingHoverAccessibilityEvents) {
8270            if ((action == MotionEvent.ACTION_HOVER_ENTER
8271                    || action == MotionEvent.ACTION_HOVER_MOVE)
8272                    && !hasHoveredChild()
8273                    && pointInView(event.getX(), event.getY())) {
8274                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
8275                mSendingHoverAccessibilityEvents = true;
8276            }
8277        } else {
8278            if (action == MotionEvent.ACTION_HOVER_EXIT
8279                    || (action == MotionEvent.ACTION_MOVE
8280                            && !pointInView(event.getX(), event.getY()))) {
8281                mSendingHoverAccessibilityEvents = false;
8282                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
8283                // If the window does not have input focus we take away accessibility
8284                // focus as soon as the user stop hovering over the view.
8285                if (mAttachInfo != null && !mAttachInfo.mHasWindowFocus) {
8286                    getViewRootImpl().setAccessibilityFocus(null, null);
8287                }
8288            }
8289        }
8290
8291        if (isHoverable()) {
8292            switch (action) {
8293                case MotionEvent.ACTION_HOVER_ENTER:
8294                    setHovered(true);
8295                    break;
8296                case MotionEvent.ACTION_HOVER_EXIT:
8297                    setHovered(false);
8298                    break;
8299            }
8300
8301            // Dispatch the event to onGenericMotionEvent before returning true.
8302            // This is to provide compatibility with existing applications that
8303            // handled HOVER_MOVE events in onGenericMotionEvent and that would
8304            // break because of the new default handling for hoverable views
8305            // in onHoverEvent.
8306            // Note that onGenericMotionEvent will be called by default when
8307            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
8308            dispatchGenericMotionEventInternal(event);
8309            // The event was already handled by calling setHovered(), so always
8310            // return true.
8311            return true;
8312        }
8313
8314        return false;
8315    }
8316
8317    /**
8318     * Returns true if the view should handle {@link #onHoverEvent}
8319     * by calling {@link #setHovered} to change its hovered state.
8320     *
8321     * @return True if the view is hoverable.
8322     */
8323    private boolean isHoverable() {
8324        final int viewFlags = mViewFlags;
8325        if ((viewFlags & ENABLED_MASK) == DISABLED) {
8326            return false;
8327        }
8328
8329        return (viewFlags & CLICKABLE) == CLICKABLE
8330                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
8331    }
8332
8333    /**
8334     * Returns true if the view is currently hovered.
8335     *
8336     * @return True if the view is currently hovered.
8337     *
8338     * @see #setHovered
8339     * @see #onHoverChanged
8340     */
8341    @ViewDebug.ExportedProperty
8342    public boolean isHovered() {
8343        return (mPrivateFlags & PFLAG_HOVERED) != 0;
8344    }
8345
8346    /**
8347     * Sets whether the view is currently hovered.
8348     * <p>
8349     * Calling this method also changes the drawable state of the view.  This
8350     * enables the view to react to hover by using different drawable resources
8351     * to change its appearance.
8352     * </p><p>
8353     * The {@link #onHoverChanged} method is called when the hovered state changes.
8354     * </p>
8355     *
8356     * @param hovered True if the view is hovered.
8357     *
8358     * @see #isHovered
8359     * @see #onHoverChanged
8360     */
8361    public void setHovered(boolean hovered) {
8362        if (hovered) {
8363            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
8364                mPrivateFlags |= PFLAG_HOVERED;
8365                refreshDrawableState();
8366                onHoverChanged(true);
8367            }
8368        } else {
8369            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
8370                mPrivateFlags &= ~PFLAG_HOVERED;
8371                refreshDrawableState();
8372                onHoverChanged(false);
8373            }
8374        }
8375    }
8376
8377    /**
8378     * Implement this method to handle hover state changes.
8379     * <p>
8380     * This method is called whenever the hover state changes as a result of a
8381     * call to {@link #setHovered}.
8382     * </p>
8383     *
8384     * @param hovered The current hover state, as returned by {@link #isHovered}.
8385     *
8386     * @see #isHovered
8387     * @see #setHovered
8388     */
8389    public void onHoverChanged(boolean hovered) {
8390    }
8391
8392    /**
8393     * Implement this method to handle touch screen motion events.
8394     *
8395     * @param event The motion event.
8396     * @return True if the event was handled, false otherwise.
8397     */
8398    public boolean onTouchEvent(MotionEvent event) {
8399        final int viewFlags = mViewFlags;
8400
8401        if ((viewFlags & ENABLED_MASK) == DISABLED) {
8402            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
8403                setPressed(false);
8404            }
8405            // A disabled view that is clickable still consumes the touch
8406            // events, it just doesn't respond to them.
8407            return (((viewFlags & CLICKABLE) == CLICKABLE ||
8408                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
8409        }
8410
8411        if (mTouchDelegate != null) {
8412            if (mTouchDelegate.onTouchEvent(event)) {
8413                return true;
8414            }
8415        }
8416
8417        if (((viewFlags & CLICKABLE) == CLICKABLE ||
8418                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
8419            switch (event.getAction()) {
8420                case MotionEvent.ACTION_UP:
8421                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
8422                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
8423                        // take focus if we don't have it already and we should in
8424                        // touch mode.
8425                        boolean focusTaken = false;
8426                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
8427                            focusTaken = requestFocus();
8428                        }
8429
8430                        if (prepressed) {
8431                            // The button is being released before we actually
8432                            // showed it as pressed.  Make it show the pressed
8433                            // state now (before scheduling the click) to ensure
8434                            // the user sees it.
8435                            setPressed(true);
8436                       }
8437
8438                        if (!mHasPerformedLongPress) {
8439                            // This is a tap, so remove the longpress check
8440                            removeLongPressCallback();
8441
8442                            // Only perform take click actions if we were in the pressed state
8443                            if (!focusTaken) {
8444                                // Use a Runnable and post this rather than calling
8445                                // performClick directly. This lets other visual state
8446                                // of the view update before click actions start.
8447                                if (mPerformClick == null) {
8448                                    mPerformClick = new PerformClick();
8449                                }
8450                                if (!post(mPerformClick)) {
8451                                    performClick();
8452                                }
8453                            }
8454                        }
8455
8456                        if (mUnsetPressedState == null) {
8457                            mUnsetPressedState = new UnsetPressedState();
8458                        }
8459
8460                        if (prepressed) {
8461                            postDelayed(mUnsetPressedState,
8462                                    ViewConfiguration.getPressedStateDuration());
8463                        } else if (!post(mUnsetPressedState)) {
8464                            // If the post failed, unpress right now
8465                            mUnsetPressedState.run();
8466                        }
8467                        removeTapCallback();
8468                    }
8469                    break;
8470
8471                case MotionEvent.ACTION_DOWN:
8472                    mHasPerformedLongPress = false;
8473
8474                    if (performButtonActionOnTouchDown(event)) {
8475                        break;
8476                    }
8477
8478                    // Walk up the hierarchy to determine if we're inside a scrolling container.
8479                    boolean isInScrollingContainer = isInScrollingContainer();
8480
8481                    // For views inside a scrolling container, delay the pressed feedback for
8482                    // a short period in case this is a scroll.
8483                    if (isInScrollingContainer) {
8484                        mPrivateFlags |= PFLAG_PREPRESSED;
8485                        if (mPendingCheckForTap == null) {
8486                            mPendingCheckForTap = new CheckForTap();
8487                        }
8488                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
8489                    } else {
8490                        // Not inside a scrolling container, so show the feedback right away
8491                        setPressed(true);
8492                        checkForLongClick(0);
8493                    }
8494                    break;
8495
8496                case MotionEvent.ACTION_CANCEL:
8497                    setPressed(false);
8498                    removeTapCallback();
8499                    removeLongPressCallback();
8500                    break;
8501
8502                case MotionEvent.ACTION_MOVE:
8503                    final int x = (int) event.getX();
8504                    final int y = (int) event.getY();
8505
8506                    // Be lenient about moving outside of buttons
8507                    if (!pointInView(x, y, mTouchSlop)) {
8508                        // Outside button
8509                        removeTapCallback();
8510                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
8511                            // Remove any future long press/tap checks
8512                            removeLongPressCallback();
8513
8514                            setPressed(false);
8515                        }
8516                    }
8517                    break;
8518            }
8519            return true;
8520        }
8521
8522        return false;
8523    }
8524
8525    /**
8526     * @hide
8527     */
8528    public boolean isInScrollingContainer() {
8529        ViewParent p = getParent();
8530        while (p != null && p instanceof ViewGroup) {
8531            if (((ViewGroup) p).shouldDelayChildPressedState()) {
8532                return true;
8533            }
8534            p = p.getParent();
8535        }
8536        return false;
8537    }
8538
8539    /**
8540     * Remove the longpress detection timer.
8541     */
8542    private void removeLongPressCallback() {
8543        if (mPendingCheckForLongPress != null) {
8544          removeCallbacks(mPendingCheckForLongPress);
8545        }
8546    }
8547
8548    /**
8549     * Remove the pending click action
8550     */
8551    private void removePerformClickCallback() {
8552        if (mPerformClick != null) {
8553            removeCallbacks(mPerformClick);
8554        }
8555    }
8556
8557    /**
8558     * Remove the prepress detection timer.
8559     */
8560    private void removeUnsetPressCallback() {
8561        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
8562            setPressed(false);
8563            removeCallbacks(mUnsetPressedState);
8564        }
8565    }
8566
8567    /**
8568     * Remove the tap detection timer.
8569     */
8570    private void removeTapCallback() {
8571        if (mPendingCheckForTap != null) {
8572            mPrivateFlags &= ~PFLAG_PREPRESSED;
8573            removeCallbacks(mPendingCheckForTap);
8574        }
8575    }
8576
8577    /**
8578     * Cancels a pending long press.  Your subclass can use this if you
8579     * want the context menu to come up if the user presses and holds
8580     * at the same place, but you don't want it to come up if they press
8581     * and then move around enough to cause scrolling.
8582     */
8583    public void cancelLongPress() {
8584        removeLongPressCallback();
8585
8586        /*
8587         * The prepressed state handled by the tap callback is a display
8588         * construct, but the tap callback will post a long press callback
8589         * less its own timeout. Remove it here.
8590         */
8591        removeTapCallback();
8592    }
8593
8594    /**
8595     * Remove the pending callback for sending a
8596     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
8597     */
8598    private void removeSendViewScrolledAccessibilityEventCallback() {
8599        if (mSendViewScrolledAccessibilityEvent != null) {
8600            removeCallbacks(mSendViewScrolledAccessibilityEvent);
8601            mSendViewScrolledAccessibilityEvent.mIsPending = false;
8602        }
8603    }
8604
8605    /**
8606     * Sets the TouchDelegate for this View.
8607     */
8608    public void setTouchDelegate(TouchDelegate delegate) {
8609        mTouchDelegate = delegate;
8610    }
8611
8612    /**
8613     * Gets the TouchDelegate for this View.
8614     */
8615    public TouchDelegate getTouchDelegate() {
8616        return mTouchDelegate;
8617    }
8618
8619    /**
8620     * Set flags controlling behavior of this view.
8621     *
8622     * @param flags Constant indicating the value which should be set
8623     * @param mask Constant indicating the bit range that should be changed
8624     */
8625    void setFlags(int flags, int mask) {
8626        final boolean accessibilityEnabled =
8627                AccessibilityManager.getInstance(mContext).isEnabled();
8628        final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility();
8629
8630        int old = mViewFlags;
8631        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
8632
8633        int changed = mViewFlags ^ old;
8634        if (changed == 0) {
8635            return;
8636        }
8637        int privateFlags = mPrivateFlags;
8638
8639        /* Check if the FOCUSABLE bit has changed */
8640        if (((changed & FOCUSABLE_MASK) != 0) &&
8641                ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) {
8642            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
8643                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
8644                /* Give up focus if we are no longer focusable */
8645                clearFocus();
8646            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
8647                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
8648                /*
8649                 * Tell the view system that we are now available to take focus
8650                 * if no one else already has it.
8651                 */
8652                if (mParent != null) mParent.focusableViewAvailable(this);
8653            }
8654        }
8655
8656        final int newVisibility = flags & VISIBILITY_MASK;
8657        if (newVisibility == VISIBLE) {
8658            if ((changed & VISIBILITY_MASK) != 0) {
8659                /*
8660                 * If this view is becoming visible, invalidate it in case it changed while
8661                 * it was not visible. Marking it drawn ensures that the invalidation will
8662                 * go through.
8663                 */
8664                mPrivateFlags |= PFLAG_DRAWN;
8665                invalidate(true);
8666
8667                needGlobalAttributesUpdate(true);
8668
8669                // a view becoming visible is worth notifying the parent
8670                // about in case nothing has focus.  even if this specific view
8671                // isn't focusable, it may contain something that is, so let
8672                // the root view try to give this focus if nothing else does.
8673                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
8674                    mParent.focusableViewAvailable(this);
8675                }
8676            }
8677        }
8678
8679        /* Check if the GONE bit has changed */
8680        if ((changed & GONE) != 0) {
8681            needGlobalAttributesUpdate(false);
8682            requestLayout();
8683
8684            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
8685                if (hasFocus()) clearFocus();
8686                clearAccessibilityFocus();
8687                destroyDrawingCache();
8688                if (mParent instanceof View) {
8689                    // GONE views noop invalidation, so invalidate the parent
8690                    ((View) mParent).invalidate(true);
8691                }
8692                // Mark the view drawn to ensure that it gets invalidated properly the next
8693                // time it is visible and gets invalidated
8694                mPrivateFlags |= PFLAG_DRAWN;
8695            }
8696            if (mAttachInfo != null) {
8697                mAttachInfo.mViewVisibilityChanged = true;
8698            }
8699        }
8700
8701        /* Check if the VISIBLE bit has changed */
8702        if ((changed & INVISIBLE) != 0) {
8703            needGlobalAttributesUpdate(false);
8704            /*
8705             * If this view is becoming invisible, set the DRAWN flag so that
8706             * the next invalidate() will not be skipped.
8707             */
8708            mPrivateFlags |= PFLAG_DRAWN;
8709
8710            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
8711                // root view becoming invisible shouldn't clear focus and accessibility focus
8712                if (getRootView() != this) {
8713                    clearFocus();
8714                    clearAccessibilityFocus();
8715                }
8716            }
8717            if (mAttachInfo != null) {
8718                mAttachInfo.mViewVisibilityChanged = true;
8719            }
8720        }
8721
8722        if ((changed & VISIBILITY_MASK) != 0) {
8723            // If the view is invisible, cleanup its display list to free up resources
8724            if (newVisibility != VISIBLE) {
8725                cleanupDraw();
8726            }
8727
8728            if (mParent instanceof ViewGroup) {
8729                ((ViewGroup) mParent).onChildVisibilityChanged(this,
8730                        (changed & VISIBILITY_MASK), newVisibility);
8731                ((View) mParent).invalidate(true);
8732            } else if (mParent != null) {
8733                mParent.invalidateChild(this, null);
8734            }
8735            dispatchVisibilityChanged(this, newVisibility);
8736        }
8737
8738        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
8739            destroyDrawingCache();
8740        }
8741
8742        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
8743            destroyDrawingCache();
8744            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
8745            invalidateParentCaches();
8746        }
8747
8748        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
8749            destroyDrawingCache();
8750            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
8751        }
8752
8753        if ((changed & DRAW_MASK) != 0) {
8754            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
8755                if (mBackground != null) {
8756                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
8757                    mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
8758                } else {
8759                    mPrivateFlags |= PFLAG_SKIP_DRAW;
8760                }
8761            } else {
8762                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
8763            }
8764            requestLayout();
8765            invalidate(true);
8766        }
8767
8768        if ((changed & KEEP_SCREEN_ON) != 0) {
8769            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
8770                mParent.recomputeViewAttributes(this);
8771            }
8772        }
8773
8774        if (accessibilityEnabled) {
8775            if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0
8776                    || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0) {
8777                if (oldIncludeForAccessibility != includeForAccessibility()) {
8778                    notifySubtreeAccessibilityStateChangedIfNeeded();
8779                } else {
8780                    notifyViewAccessibilityStateChangedIfNeeded();
8781                }
8782            }
8783            if ((changed & ENABLED_MASK) != 0) {
8784                notifyViewAccessibilityStateChangedIfNeeded();
8785            }
8786        }
8787    }
8788
8789    /**
8790     * Change the view's z order in the tree, so it's on top of other sibling
8791     * views. This ordering change may affect layout, if the parent container
8792     * uses an order-dependent layout scheme (e.g., LinearLayout). This
8793     * method should be followed by calls to {@link #requestLayout()} and
8794     * {@link View#invalidate()} on the parent.
8795     *
8796     * @see ViewGroup#bringChildToFront(View)
8797     */
8798    public void bringToFront() {
8799        if (mParent != null) {
8800            mParent.bringChildToFront(this);
8801        }
8802    }
8803
8804    /**
8805     * This is called in response to an internal scroll in this view (i.e., the
8806     * view scrolled its own contents). This is typically as a result of
8807     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
8808     * called.
8809     *
8810     * @param l Current horizontal scroll origin.
8811     * @param t Current vertical scroll origin.
8812     * @param oldl Previous horizontal scroll origin.
8813     * @param oldt Previous vertical scroll origin.
8814     */
8815    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
8816        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
8817            postSendViewScrolledAccessibilityEventCallback();
8818        }
8819
8820        mBackgroundSizeChanged = true;
8821
8822        final AttachInfo ai = mAttachInfo;
8823        if (ai != null) {
8824            ai.mViewScrollChanged = true;
8825        }
8826    }
8827
8828    /**
8829     * Interface definition for a callback to be invoked when the layout bounds of a view
8830     * changes due to layout processing.
8831     */
8832    public interface OnLayoutChangeListener {
8833        /**
8834         * Called when the focus state of a view has changed.
8835         *
8836         * @param v The view whose state has changed.
8837         * @param left The new value of the view's left property.
8838         * @param top The new value of the view's top property.
8839         * @param right The new value of the view's right property.
8840         * @param bottom The new value of the view's bottom property.
8841         * @param oldLeft The previous value of the view's left property.
8842         * @param oldTop The previous value of the view's top property.
8843         * @param oldRight The previous value of the view's right property.
8844         * @param oldBottom The previous value of the view's bottom property.
8845         */
8846        void onLayoutChange(View v, int left, int top, int right, int bottom,
8847            int oldLeft, int oldTop, int oldRight, int oldBottom);
8848    }
8849
8850    /**
8851     * This is called during layout when the size of this view has changed. If
8852     * you were just added to the view hierarchy, you're called with the old
8853     * values of 0.
8854     *
8855     * @param w Current width of this view.
8856     * @param h Current height of this view.
8857     * @param oldw Old width of this view.
8858     * @param oldh Old height of this view.
8859     */
8860    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
8861    }
8862
8863    /**
8864     * Called by draw to draw the child views. This may be overridden
8865     * by derived classes to gain control just before its children are drawn
8866     * (but after its own view has been drawn).
8867     * @param canvas the canvas on which to draw the view
8868     */
8869    protected void dispatchDraw(Canvas canvas) {
8870
8871    }
8872
8873    /**
8874     * Gets the parent of this view. Note that the parent is a
8875     * ViewParent and not necessarily a View.
8876     *
8877     * @return Parent of this view.
8878     */
8879    public final ViewParent getParent() {
8880        return mParent;
8881    }
8882
8883    /**
8884     * Set the horizontal scrolled position of your view. This will cause a call to
8885     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8886     * invalidated.
8887     * @param value the x position to scroll to
8888     */
8889    public void setScrollX(int value) {
8890        scrollTo(value, mScrollY);
8891    }
8892
8893    /**
8894     * Set the vertical scrolled position of your view. This will cause a call to
8895     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8896     * invalidated.
8897     * @param value the y position to scroll to
8898     */
8899    public void setScrollY(int value) {
8900        scrollTo(mScrollX, value);
8901    }
8902
8903    /**
8904     * Return the scrolled left position of this view. This is the left edge of
8905     * the displayed part of your view. You do not need to draw any pixels
8906     * farther left, since those are outside of the frame of your view on
8907     * screen.
8908     *
8909     * @return The left edge of the displayed part of your view, in pixels.
8910     */
8911    public final int getScrollX() {
8912        return mScrollX;
8913    }
8914
8915    /**
8916     * Return the scrolled top position of this view. This is the top edge of
8917     * the displayed part of your view. You do not need to draw any pixels above
8918     * it, since those are outside of the frame of your view on screen.
8919     *
8920     * @return The top edge of the displayed part of your view, in pixels.
8921     */
8922    public final int getScrollY() {
8923        return mScrollY;
8924    }
8925
8926    /**
8927     * Return the width of the your view.
8928     *
8929     * @return The width of your view, in pixels.
8930     */
8931    @ViewDebug.ExportedProperty(category = "layout")
8932    public final int getWidth() {
8933        return mRight - mLeft;
8934    }
8935
8936    /**
8937     * Return the height of your view.
8938     *
8939     * @return The height of your view, in pixels.
8940     */
8941    @ViewDebug.ExportedProperty(category = "layout")
8942    public final int getHeight() {
8943        return mBottom - mTop;
8944    }
8945
8946    /**
8947     * Return the visible drawing bounds of your view. Fills in the output
8948     * rectangle with the values from getScrollX(), getScrollY(),
8949     * getWidth(), and getHeight(). These bounds do not account for any
8950     * transformation properties currently set on the view, such as
8951     * {@link #setScaleX(float)} or {@link #setRotation(float)}.
8952     *
8953     * @param outRect The (scrolled) drawing bounds of the view.
8954     */
8955    public void getDrawingRect(Rect outRect) {
8956        outRect.left = mScrollX;
8957        outRect.top = mScrollY;
8958        outRect.right = mScrollX + (mRight - mLeft);
8959        outRect.bottom = mScrollY + (mBottom - mTop);
8960    }
8961
8962    /**
8963     * Like {@link #getMeasuredWidthAndState()}, but only returns the
8964     * raw width component (that is the result is masked by
8965     * {@link #MEASURED_SIZE_MASK}).
8966     *
8967     * @return The raw measured width of this view.
8968     */
8969    public final int getMeasuredWidth() {
8970        return mMeasuredWidth & MEASURED_SIZE_MASK;
8971    }
8972
8973    /**
8974     * Return the full width measurement information for this view as computed
8975     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
8976     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
8977     * This should be used during measurement and layout calculations only. Use
8978     * {@link #getWidth()} to see how wide a view is after layout.
8979     *
8980     * @return The measured width of this view as a bit mask.
8981     */
8982    public final int getMeasuredWidthAndState() {
8983        return mMeasuredWidth;
8984    }
8985
8986    /**
8987     * Like {@link #getMeasuredHeightAndState()}, but only returns the
8988     * raw width component (that is the result is masked by
8989     * {@link #MEASURED_SIZE_MASK}).
8990     *
8991     * @return The raw measured height of this view.
8992     */
8993    public final int getMeasuredHeight() {
8994        return mMeasuredHeight & MEASURED_SIZE_MASK;
8995    }
8996
8997    /**
8998     * Return the full height measurement information for this view as computed
8999     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
9000     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
9001     * This should be used during measurement and layout calculations only. Use
9002     * {@link #getHeight()} to see how wide a view is after layout.
9003     *
9004     * @return The measured width of this view as a bit mask.
9005     */
9006    public final int getMeasuredHeightAndState() {
9007        return mMeasuredHeight;
9008    }
9009
9010    /**
9011     * Return only the state bits of {@link #getMeasuredWidthAndState()}
9012     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
9013     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
9014     * and the height component is at the shifted bits
9015     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
9016     */
9017    public final int getMeasuredState() {
9018        return (mMeasuredWidth&MEASURED_STATE_MASK)
9019                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
9020                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
9021    }
9022
9023    /**
9024     * The transform matrix of this view, which is calculated based on the current
9025     * roation, scale, and pivot properties.
9026     *
9027     * @see #getRotation()
9028     * @see #getScaleX()
9029     * @see #getScaleY()
9030     * @see #getPivotX()
9031     * @see #getPivotY()
9032     * @return The current transform matrix for the view
9033     */
9034    public Matrix getMatrix() {
9035        if (mTransformationInfo != null) {
9036            updateMatrix();
9037            return mTransformationInfo.mMatrix;
9038        }
9039        return Matrix.IDENTITY_MATRIX;
9040    }
9041
9042    /**
9043     * Utility function to determine if the value is far enough away from zero to be
9044     * considered non-zero.
9045     * @param value A floating point value to check for zero-ness
9046     * @return whether the passed-in value is far enough away from zero to be considered non-zero
9047     */
9048    private static boolean nonzero(float value) {
9049        return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
9050    }
9051
9052    /**
9053     * Returns true if the transform matrix is the identity matrix.
9054     * Recomputes the matrix if necessary.
9055     *
9056     * @return True if the transform matrix is the identity matrix, false otherwise.
9057     */
9058    final boolean hasIdentityMatrix() {
9059        if (mTransformationInfo != null) {
9060            updateMatrix();
9061            return mTransformationInfo.mMatrixIsIdentity;
9062        }
9063        return true;
9064    }
9065
9066    void ensureTransformationInfo() {
9067        if (mTransformationInfo == null) {
9068            mTransformationInfo = new TransformationInfo();
9069        }
9070    }
9071
9072    /**
9073     * Recomputes the transform matrix if necessary.
9074     */
9075    private void updateMatrix() {
9076        final TransformationInfo info = mTransformationInfo;
9077        if (info == null) {
9078            return;
9079        }
9080        if (info.mMatrixDirty) {
9081            // transform-related properties have changed since the last time someone
9082            // asked for the matrix; recalculate it with the current values
9083
9084            // Figure out if we need to update the pivot point
9085            if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9086                if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) {
9087                    info.mPrevWidth = mRight - mLeft;
9088                    info.mPrevHeight = mBottom - mTop;
9089                    info.mPivotX = info.mPrevWidth / 2f;
9090                    info.mPivotY = info.mPrevHeight / 2f;
9091                }
9092            }
9093            info.mMatrix.reset();
9094            if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) {
9095                info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY);
9096                info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY);
9097                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
9098            } else {
9099                if (info.mCamera == null) {
9100                    info.mCamera = new Camera();
9101                    info.matrix3D = new Matrix();
9102                }
9103                info.mCamera.save();
9104                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
9105                info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation);
9106                info.mCamera.getMatrix(info.matrix3D);
9107                info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY);
9108                info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX,
9109                        info.mPivotY + info.mTranslationY);
9110                info.mMatrix.postConcat(info.matrix3D);
9111                info.mCamera.restore();
9112            }
9113            info.mMatrixDirty = false;
9114            info.mMatrixIsIdentity = info.mMatrix.isIdentity();
9115            info.mInverseMatrixDirty = true;
9116        }
9117    }
9118
9119   /**
9120     * Utility method to retrieve the inverse of the current mMatrix property.
9121     * We cache the matrix to avoid recalculating it when transform properties
9122     * have not changed.
9123     *
9124     * @return The inverse of the current matrix of this view.
9125     */
9126    final Matrix getInverseMatrix() {
9127        final TransformationInfo info = mTransformationInfo;
9128        if (info != null) {
9129            updateMatrix();
9130            if (info.mInverseMatrixDirty) {
9131                if (info.mInverseMatrix == null) {
9132                    info.mInverseMatrix = new Matrix();
9133                }
9134                info.mMatrix.invert(info.mInverseMatrix);
9135                info.mInverseMatrixDirty = false;
9136            }
9137            return info.mInverseMatrix;
9138        }
9139        return Matrix.IDENTITY_MATRIX;
9140    }
9141
9142    /**
9143     * Gets the distance along the Z axis from the camera to this view.
9144     *
9145     * @see #setCameraDistance(float)
9146     *
9147     * @return The distance along the Z axis.
9148     */
9149    public float getCameraDistance() {
9150        ensureTransformationInfo();
9151        final float dpi = mResources.getDisplayMetrics().densityDpi;
9152        final TransformationInfo info = mTransformationInfo;
9153        if (info.mCamera == null) {
9154            info.mCamera = new Camera();
9155            info.matrix3D = new Matrix();
9156        }
9157        return -(info.mCamera.getLocationZ() * dpi);
9158    }
9159
9160    /**
9161     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
9162     * views are drawn) from the camera to this view. The camera's distance
9163     * affects 3D transformations, for instance rotations around the X and Y
9164     * axis. If the rotationX or rotationY properties are changed and this view is
9165     * large (more than half the size of the screen), it is recommended to always
9166     * use a camera distance that's greater than the height (X axis rotation) or
9167     * the width (Y axis rotation) of this view.</p>
9168     *
9169     * <p>The distance of the camera from the view plane can have an affect on the
9170     * perspective distortion of the view when it is rotated around the x or y axis.
9171     * For example, a large distance will result in a large viewing angle, and there
9172     * will not be much perspective distortion of the view as it rotates. A short
9173     * distance may cause much more perspective distortion upon rotation, and can
9174     * also result in some drawing artifacts if the rotated view ends up partially
9175     * behind the camera (which is why the recommendation is to use a distance at
9176     * least as far as the size of the view, if the view is to be rotated.)</p>
9177     *
9178     * <p>The distance is expressed in "depth pixels." The default distance depends
9179     * on the screen density. For instance, on a medium density display, the
9180     * default distance is 1280. On a high density display, the default distance
9181     * is 1920.</p>
9182     *
9183     * <p>If you want to specify a distance that leads to visually consistent
9184     * results across various densities, use the following formula:</p>
9185     * <pre>
9186     * float scale = context.getResources().getDisplayMetrics().density;
9187     * view.setCameraDistance(distance * scale);
9188     * </pre>
9189     *
9190     * <p>The density scale factor of a high density display is 1.5,
9191     * and 1920 = 1280 * 1.5.</p>
9192     *
9193     * @param distance The distance in "depth pixels", if negative the opposite
9194     *        value is used
9195     *
9196     * @see #setRotationX(float)
9197     * @see #setRotationY(float)
9198     */
9199    public void setCameraDistance(float distance) {
9200        invalidateViewProperty(true, false);
9201
9202        ensureTransformationInfo();
9203        final float dpi = mResources.getDisplayMetrics().densityDpi;
9204        final TransformationInfo info = mTransformationInfo;
9205        if (info.mCamera == null) {
9206            info.mCamera = new Camera();
9207            info.matrix3D = new Matrix();
9208        }
9209
9210        info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi);
9211        info.mMatrixDirty = true;
9212
9213        invalidateViewProperty(false, false);
9214        if (mDisplayList != null) {
9215            mDisplayList.setCameraDistance(-Math.abs(distance) / dpi);
9216        }
9217        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9218            // View was rejected last time it was drawn by its parent; this may have changed
9219            invalidateParentIfNeeded();
9220        }
9221    }
9222
9223    /**
9224     * The degrees that the view is rotated around the pivot point.
9225     *
9226     * @see #setRotation(float)
9227     * @see #getPivotX()
9228     * @see #getPivotY()
9229     *
9230     * @return The degrees of rotation.
9231     */
9232    @ViewDebug.ExportedProperty(category = "drawing")
9233    public float getRotation() {
9234        return mTransformationInfo != null ? mTransformationInfo.mRotation : 0;
9235    }
9236
9237    /**
9238     * Sets the degrees that the view is rotated around the pivot point. Increasing values
9239     * result in clockwise rotation.
9240     *
9241     * @param rotation The degrees of rotation.
9242     *
9243     * @see #getRotation()
9244     * @see #getPivotX()
9245     * @see #getPivotY()
9246     * @see #setRotationX(float)
9247     * @see #setRotationY(float)
9248     *
9249     * @attr ref android.R.styleable#View_rotation
9250     */
9251    public void setRotation(float rotation) {
9252        ensureTransformationInfo();
9253        final TransformationInfo info = mTransformationInfo;
9254        if (info.mRotation != rotation) {
9255            // Double-invalidation is necessary to capture view's old and new areas
9256            invalidateViewProperty(true, false);
9257            info.mRotation = rotation;
9258            info.mMatrixDirty = true;
9259            invalidateViewProperty(false, true);
9260            if (mDisplayList != null) {
9261                mDisplayList.setRotation(rotation);
9262            }
9263            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9264                // View was rejected last time it was drawn by its parent; this may have changed
9265                invalidateParentIfNeeded();
9266            }
9267        }
9268    }
9269
9270    /**
9271     * The degrees that the view is rotated around the vertical axis through the pivot point.
9272     *
9273     * @see #getPivotX()
9274     * @see #getPivotY()
9275     * @see #setRotationY(float)
9276     *
9277     * @return The degrees of Y rotation.
9278     */
9279    @ViewDebug.ExportedProperty(category = "drawing")
9280    public float getRotationY() {
9281        return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0;
9282    }
9283
9284    /**
9285     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
9286     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
9287     * down the y axis.
9288     *
9289     * When rotating large views, it is recommended to adjust the camera distance
9290     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
9291     *
9292     * @param rotationY The degrees of Y rotation.
9293     *
9294     * @see #getRotationY()
9295     * @see #getPivotX()
9296     * @see #getPivotY()
9297     * @see #setRotation(float)
9298     * @see #setRotationX(float)
9299     * @see #setCameraDistance(float)
9300     *
9301     * @attr ref android.R.styleable#View_rotationY
9302     */
9303    public void setRotationY(float rotationY) {
9304        ensureTransformationInfo();
9305        final TransformationInfo info = mTransformationInfo;
9306        if (info.mRotationY != rotationY) {
9307            invalidateViewProperty(true, false);
9308            info.mRotationY = rotationY;
9309            info.mMatrixDirty = true;
9310            invalidateViewProperty(false, true);
9311            if (mDisplayList != null) {
9312                mDisplayList.setRotationY(rotationY);
9313            }
9314            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9315                // View was rejected last time it was drawn by its parent; this may have changed
9316                invalidateParentIfNeeded();
9317            }
9318        }
9319    }
9320
9321    /**
9322     * The degrees that the view is rotated around the horizontal axis through the pivot point.
9323     *
9324     * @see #getPivotX()
9325     * @see #getPivotY()
9326     * @see #setRotationX(float)
9327     *
9328     * @return The degrees of X rotation.
9329     */
9330    @ViewDebug.ExportedProperty(category = "drawing")
9331    public float getRotationX() {
9332        return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0;
9333    }
9334
9335    /**
9336     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
9337     * Increasing values result in clockwise rotation from the viewpoint of looking down the
9338     * x axis.
9339     *
9340     * When rotating large views, it is recommended to adjust the camera distance
9341     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
9342     *
9343     * @param rotationX The degrees of X rotation.
9344     *
9345     * @see #getRotationX()
9346     * @see #getPivotX()
9347     * @see #getPivotY()
9348     * @see #setRotation(float)
9349     * @see #setRotationY(float)
9350     * @see #setCameraDistance(float)
9351     *
9352     * @attr ref android.R.styleable#View_rotationX
9353     */
9354    public void setRotationX(float rotationX) {
9355        ensureTransformationInfo();
9356        final TransformationInfo info = mTransformationInfo;
9357        if (info.mRotationX != rotationX) {
9358            invalidateViewProperty(true, false);
9359            info.mRotationX = rotationX;
9360            info.mMatrixDirty = true;
9361            invalidateViewProperty(false, true);
9362            if (mDisplayList != null) {
9363                mDisplayList.setRotationX(rotationX);
9364            }
9365            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9366                // View was rejected last time it was drawn by its parent; this may have changed
9367                invalidateParentIfNeeded();
9368            }
9369        }
9370    }
9371
9372    /**
9373     * The amount that the view is scaled in x around the pivot point, as a proportion of
9374     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
9375     *
9376     * <p>By default, this is 1.0f.
9377     *
9378     * @see #getPivotX()
9379     * @see #getPivotY()
9380     * @return The scaling factor.
9381     */
9382    @ViewDebug.ExportedProperty(category = "drawing")
9383    public float getScaleX() {
9384        return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1;
9385    }
9386
9387    /**
9388     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
9389     * the view's unscaled width. A value of 1 means that no scaling is applied.
9390     *
9391     * @param scaleX The scaling factor.
9392     * @see #getPivotX()
9393     * @see #getPivotY()
9394     *
9395     * @attr ref android.R.styleable#View_scaleX
9396     */
9397    public void setScaleX(float scaleX) {
9398        ensureTransformationInfo();
9399        final TransformationInfo info = mTransformationInfo;
9400        if (info.mScaleX != scaleX) {
9401            invalidateViewProperty(true, false);
9402            info.mScaleX = scaleX;
9403            info.mMatrixDirty = true;
9404            invalidateViewProperty(false, true);
9405            if (mDisplayList != null) {
9406                mDisplayList.setScaleX(scaleX);
9407            }
9408            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9409                // View was rejected last time it was drawn by its parent; this may have changed
9410                invalidateParentIfNeeded();
9411            }
9412        }
9413    }
9414
9415    /**
9416     * The amount that the view is scaled in y around the pivot point, as a proportion of
9417     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
9418     *
9419     * <p>By default, this is 1.0f.
9420     *
9421     * @see #getPivotX()
9422     * @see #getPivotY()
9423     * @return The scaling factor.
9424     */
9425    @ViewDebug.ExportedProperty(category = "drawing")
9426    public float getScaleY() {
9427        return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1;
9428    }
9429
9430    /**
9431     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
9432     * the view's unscaled width. A value of 1 means that no scaling is applied.
9433     *
9434     * @param scaleY The scaling factor.
9435     * @see #getPivotX()
9436     * @see #getPivotY()
9437     *
9438     * @attr ref android.R.styleable#View_scaleY
9439     */
9440    public void setScaleY(float scaleY) {
9441        ensureTransformationInfo();
9442        final TransformationInfo info = mTransformationInfo;
9443        if (info.mScaleY != scaleY) {
9444            invalidateViewProperty(true, false);
9445            info.mScaleY = scaleY;
9446            info.mMatrixDirty = true;
9447            invalidateViewProperty(false, true);
9448            if (mDisplayList != null) {
9449                mDisplayList.setScaleY(scaleY);
9450            }
9451            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9452                // View was rejected last time it was drawn by its parent; this may have changed
9453                invalidateParentIfNeeded();
9454            }
9455        }
9456    }
9457
9458    /**
9459     * The x location of the point around which the view is {@link #setRotation(float) rotated}
9460     * and {@link #setScaleX(float) scaled}.
9461     *
9462     * @see #getRotation()
9463     * @see #getScaleX()
9464     * @see #getScaleY()
9465     * @see #getPivotY()
9466     * @return The x location of the pivot point.
9467     *
9468     * @attr ref android.R.styleable#View_transformPivotX
9469     */
9470    @ViewDebug.ExportedProperty(category = "drawing")
9471    public float getPivotX() {
9472        return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0;
9473    }
9474
9475    /**
9476     * Sets the x location of the point around which the view is
9477     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
9478     * By default, the pivot point is centered on the object.
9479     * Setting this property disables this behavior and causes the view to use only the
9480     * explicitly set pivotX and pivotY values.
9481     *
9482     * @param pivotX The x location of the pivot point.
9483     * @see #getRotation()
9484     * @see #getScaleX()
9485     * @see #getScaleY()
9486     * @see #getPivotY()
9487     *
9488     * @attr ref android.R.styleable#View_transformPivotX
9489     */
9490    public void setPivotX(float pivotX) {
9491        ensureTransformationInfo();
9492        mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET;
9493        final TransformationInfo info = mTransformationInfo;
9494        if (info.mPivotX != pivotX) {
9495            invalidateViewProperty(true, false);
9496            info.mPivotX = pivotX;
9497            info.mMatrixDirty = true;
9498            invalidateViewProperty(false, true);
9499            if (mDisplayList != null) {
9500                mDisplayList.setPivotX(pivotX);
9501            }
9502            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9503                // View was rejected last time it was drawn by its parent; this may have changed
9504                invalidateParentIfNeeded();
9505            }
9506        }
9507    }
9508
9509    /**
9510     * The y location of the point around which the view is {@link #setRotation(float) rotated}
9511     * and {@link #setScaleY(float) scaled}.
9512     *
9513     * @see #getRotation()
9514     * @see #getScaleX()
9515     * @see #getScaleY()
9516     * @see #getPivotY()
9517     * @return The y location of the pivot point.
9518     *
9519     * @attr ref android.R.styleable#View_transformPivotY
9520     */
9521    @ViewDebug.ExportedProperty(category = "drawing")
9522    public float getPivotY() {
9523        return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0;
9524    }
9525
9526    /**
9527     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
9528     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
9529     * Setting this property disables this behavior and causes the view to use only the
9530     * explicitly set pivotX and pivotY values.
9531     *
9532     * @param pivotY The y location of the pivot point.
9533     * @see #getRotation()
9534     * @see #getScaleX()
9535     * @see #getScaleY()
9536     * @see #getPivotY()
9537     *
9538     * @attr ref android.R.styleable#View_transformPivotY
9539     */
9540    public void setPivotY(float pivotY) {
9541        ensureTransformationInfo();
9542        mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET;
9543        final TransformationInfo info = mTransformationInfo;
9544        if (info.mPivotY != pivotY) {
9545            invalidateViewProperty(true, false);
9546            info.mPivotY = pivotY;
9547            info.mMatrixDirty = true;
9548            invalidateViewProperty(false, true);
9549            if (mDisplayList != null) {
9550                mDisplayList.setPivotY(pivotY);
9551            }
9552            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9553                // View was rejected last time it was drawn by its parent; this may have changed
9554                invalidateParentIfNeeded();
9555            }
9556        }
9557    }
9558
9559    /**
9560     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
9561     * completely transparent and 1 means the view is completely opaque.
9562     *
9563     * <p>By default this is 1.0f.
9564     * @return The opacity of the view.
9565     */
9566    @ViewDebug.ExportedProperty(category = "drawing")
9567    public float getAlpha() {
9568        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
9569    }
9570
9571    /**
9572     * Returns whether this View has content which overlaps. This function, intended to be
9573     * overridden by specific View types, is an optimization when alpha is set on a view. If
9574     * rendering overlaps in a view with alpha < 1, that view is drawn to an offscreen buffer
9575     * and then composited it into place, which can be expensive. If the view has no overlapping
9576     * rendering, the view can draw each primitive with the appropriate alpha value directly.
9577     * An example of overlapping rendering is a TextView with a background image, such as a
9578     * Button. An example of non-overlapping rendering is a TextView with no background, or
9579     * an ImageView with only the foreground image. The default implementation returns true;
9580     * subclasses should override if they have cases which can be optimized.
9581     *
9582     * @return true if the content in this view might overlap, false otherwise.
9583     */
9584    public boolean hasOverlappingRendering() {
9585        return true;
9586    }
9587
9588    /**
9589     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
9590     * completely transparent and 1 means the view is completely opaque.</p>
9591     *
9592     * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant
9593     * performance implications, especially for large views. It is best to use the alpha property
9594     * sparingly and transiently, as in the case of fading animations.</p>
9595     *
9596     * <p>For a view with a frequently changing alpha, such as during a fading animation, it is
9597     * strongly recommended for performance reasons to either override
9598     * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a
9599     * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p>
9600     *
9601     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
9602     * responsible for applying the opacity itself.</p>
9603     *
9604     * <p>Note that if the view is backed by a
9605     * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a
9606     * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than
9607     * 1.0 will supercede the alpha of the layer paint.</p>
9608     *
9609     * @param alpha The opacity of the view.
9610     *
9611     * @see #hasOverlappingRendering()
9612     * @see #setLayerType(int, android.graphics.Paint)
9613     *
9614     * @attr ref android.R.styleable#View_alpha
9615     */
9616    public void setAlpha(float alpha) {
9617        ensureTransformationInfo();
9618        if (mTransformationInfo.mAlpha != alpha) {
9619            mTransformationInfo.mAlpha = alpha;
9620            if (onSetAlpha((int) (alpha * 255))) {
9621                mPrivateFlags |= PFLAG_ALPHA_SET;
9622                // subclass is handling alpha - don't optimize rendering cache invalidation
9623                invalidateParentCaches();
9624                invalidate(true);
9625            } else {
9626                mPrivateFlags &= ~PFLAG_ALPHA_SET;
9627                invalidateViewProperty(true, false);
9628                if (mDisplayList != null) {
9629                    mDisplayList.setAlpha(alpha);
9630                }
9631            }
9632        }
9633    }
9634
9635    /**
9636     * Faster version of setAlpha() which performs the same steps except there are
9637     * no calls to invalidate(). The caller of this function should perform proper invalidation
9638     * on the parent and this object. The return value indicates whether the subclass handles
9639     * alpha (the return value for onSetAlpha()).
9640     *
9641     * @param alpha The new value for the alpha property
9642     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
9643     *         the new value for the alpha property is different from the old value
9644     */
9645    boolean setAlphaNoInvalidation(float alpha) {
9646        ensureTransformationInfo();
9647        if (mTransformationInfo.mAlpha != alpha) {
9648            mTransformationInfo.mAlpha = alpha;
9649            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
9650            if (subclassHandlesAlpha) {
9651                mPrivateFlags |= PFLAG_ALPHA_SET;
9652                return true;
9653            } else {
9654                mPrivateFlags &= ~PFLAG_ALPHA_SET;
9655                if (mDisplayList != null) {
9656                    mDisplayList.setAlpha(alpha);
9657                }
9658            }
9659        }
9660        return false;
9661    }
9662
9663    /**
9664     * Top position of this view relative to its parent.
9665     *
9666     * @return The top of this view, in pixels.
9667     */
9668    @ViewDebug.CapturedViewProperty
9669    public final int getTop() {
9670        return mTop;
9671    }
9672
9673    /**
9674     * Sets the top position of this view relative to its parent. This method is meant to be called
9675     * by the layout system and should not generally be called otherwise, because the property
9676     * may be changed at any time by the layout.
9677     *
9678     * @param top The top of this view, in pixels.
9679     */
9680    public final void setTop(int top) {
9681        if (top != mTop) {
9682            updateMatrix();
9683            final boolean matrixIsIdentity = mTransformationInfo == null
9684                    || mTransformationInfo.mMatrixIsIdentity;
9685            if (matrixIsIdentity) {
9686                if (mAttachInfo != null) {
9687                    int minTop;
9688                    int yLoc;
9689                    if (top < mTop) {
9690                        minTop = top;
9691                        yLoc = top - mTop;
9692                    } else {
9693                        minTop = mTop;
9694                        yLoc = 0;
9695                    }
9696                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
9697                }
9698            } else {
9699                // Double-invalidation is necessary to capture view's old and new areas
9700                invalidate(true);
9701            }
9702
9703            int width = mRight - mLeft;
9704            int oldHeight = mBottom - mTop;
9705
9706            mTop = top;
9707            if (mDisplayList != null) {
9708                mDisplayList.setTop(mTop);
9709            }
9710
9711            sizeChange(width, mBottom - mTop, width, oldHeight);
9712
9713            if (!matrixIsIdentity) {
9714                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9715                    // A change in dimension means an auto-centered pivot point changes, too
9716                    mTransformationInfo.mMatrixDirty = true;
9717                }
9718                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
9719                invalidate(true);
9720            }
9721            mBackgroundSizeChanged = true;
9722            invalidateParentIfNeeded();
9723            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9724                // View was rejected last time it was drawn by its parent; this may have changed
9725                invalidateParentIfNeeded();
9726            }
9727        }
9728    }
9729
9730    /**
9731     * Bottom position of this view relative to its parent.
9732     *
9733     * @return The bottom of this view, in pixels.
9734     */
9735    @ViewDebug.CapturedViewProperty
9736    public final int getBottom() {
9737        return mBottom;
9738    }
9739
9740    /**
9741     * True if this view has changed since the last time being drawn.
9742     *
9743     * @return The dirty state of this view.
9744     */
9745    public boolean isDirty() {
9746        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
9747    }
9748
9749    /**
9750     * Sets the bottom position of this view relative to its parent. This method is meant to be
9751     * called by the layout system and should not generally be called otherwise, because the
9752     * property may be changed at any time by the layout.
9753     *
9754     * @param bottom The bottom of this view, in pixels.
9755     */
9756    public final void setBottom(int bottom) {
9757        if (bottom != mBottom) {
9758            updateMatrix();
9759            final boolean matrixIsIdentity = mTransformationInfo == null
9760                    || mTransformationInfo.mMatrixIsIdentity;
9761            if (matrixIsIdentity) {
9762                if (mAttachInfo != null) {
9763                    int maxBottom;
9764                    if (bottom < mBottom) {
9765                        maxBottom = mBottom;
9766                    } else {
9767                        maxBottom = bottom;
9768                    }
9769                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
9770                }
9771            } else {
9772                // Double-invalidation is necessary to capture view's old and new areas
9773                invalidate(true);
9774            }
9775
9776            int width = mRight - mLeft;
9777            int oldHeight = mBottom - mTop;
9778
9779            mBottom = bottom;
9780            if (mDisplayList != null) {
9781                mDisplayList.setBottom(mBottom);
9782            }
9783
9784            sizeChange(width, mBottom - mTop, width, oldHeight);
9785
9786            if (!matrixIsIdentity) {
9787                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9788                    // A change in dimension means an auto-centered pivot point changes, too
9789                    mTransformationInfo.mMatrixDirty = true;
9790                }
9791                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
9792                invalidate(true);
9793            }
9794            mBackgroundSizeChanged = true;
9795            invalidateParentIfNeeded();
9796            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9797                // View was rejected last time it was drawn by its parent; this may have changed
9798                invalidateParentIfNeeded();
9799            }
9800        }
9801    }
9802
9803    /**
9804     * Left position of this view relative to its parent.
9805     *
9806     * @return The left edge of this view, in pixels.
9807     */
9808    @ViewDebug.CapturedViewProperty
9809    public final int getLeft() {
9810        return mLeft;
9811    }
9812
9813    /**
9814     * Sets the left position of this view relative to its parent. This method is meant to be called
9815     * by the layout system and should not generally be called otherwise, because the property
9816     * may be changed at any time by the layout.
9817     *
9818     * @param left The bottom of this view, in pixels.
9819     */
9820    public final void setLeft(int left) {
9821        if (left != mLeft) {
9822            updateMatrix();
9823            final boolean matrixIsIdentity = mTransformationInfo == null
9824                    || mTransformationInfo.mMatrixIsIdentity;
9825            if (matrixIsIdentity) {
9826                if (mAttachInfo != null) {
9827                    int minLeft;
9828                    int xLoc;
9829                    if (left < mLeft) {
9830                        minLeft = left;
9831                        xLoc = left - mLeft;
9832                    } else {
9833                        minLeft = mLeft;
9834                        xLoc = 0;
9835                    }
9836                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
9837                }
9838            } else {
9839                // Double-invalidation is necessary to capture view's old and new areas
9840                invalidate(true);
9841            }
9842
9843            int oldWidth = mRight - mLeft;
9844            int height = mBottom - mTop;
9845
9846            mLeft = left;
9847            if (mDisplayList != null) {
9848                mDisplayList.setLeft(left);
9849            }
9850
9851            sizeChange(mRight - mLeft, height, oldWidth, height);
9852
9853            if (!matrixIsIdentity) {
9854                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9855                    // A change in dimension means an auto-centered pivot point changes, too
9856                    mTransformationInfo.mMatrixDirty = true;
9857                }
9858                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
9859                invalidate(true);
9860            }
9861            mBackgroundSizeChanged = true;
9862            invalidateParentIfNeeded();
9863            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9864                // View was rejected last time it was drawn by its parent; this may have changed
9865                invalidateParentIfNeeded();
9866            }
9867        }
9868    }
9869
9870    /**
9871     * Right position of this view relative to its parent.
9872     *
9873     * @return The right edge of this view, in pixels.
9874     */
9875    @ViewDebug.CapturedViewProperty
9876    public final int getRight() {
9877        return mRight;
9878    }
9879
9880    /**
9881     * Sets the right position of this view relative to its parent. This method is meant to be called
9882     * by the layout system and should not generally be called otherwise, because the property
9883     * may be changed at any time by the layout.
9884     *
9885     * @param right The bottom of this view, in pixels.
9886     */
9887    public final void setRight(int right) {
9888        if (right != mRight) {
9889            updateMatrix();
9890            final boolean matrixIsIdentity = mTransformationInfo == null
9891                    || mTransformationInfo.mMatrixIsIdentity;
9892            if (matrixIsIdentity) {
9893                if (mAttachInfo != null) {
9894                    int maxRight;
9895                    if (right < mRight) {
9896                        maxRight = mRight;
9897                    } else {
9898                        maxRight = right;
9899                    }
9900                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
9901                }
9902            } else {
9903                // Double-invalidation is necessary to capture view's old and new areas
9904                invalidate(true);
9905            }
9906
9907            int oldWidth = mRight - mLeft;
9908            int height = mBottom - mTop;
9909
9910            mRight = right;
9911            if (mDisplayList != null) {
9912                mDisplayList.setRight(mRight);
9913            }
9914
9915            sizeChange(mRight - mLeft, height, oldWidth, height);
9916
9917            if (!matrixIsIdentity) {
9918                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9919                    // A change in dimension means an auto-centered pivot point changes, too
9920                    mTransformationInfo.mMatrixDirty = true;
9921                }
9922                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
9923                invalidate(true);
9924            }
9925            mBackgroundSizeChanged = true;
9926            invalidateParentIfNeeded();
9927            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9928                // View was rejected last time it was drawn by its parent; this may have changed
9929                invalidateParentIfNeeded();
9930            }
9931        }
9932    }
9933
9934    /**
9935     * The visual x position of this view, in pixels. This is equivalent to the
9936     * {@link #setTranslationX(float) translationX} property plus the current
9937     * {@link #getLeft() left} property.
9938     *
9939     * @return The visual x position of this view, in pixels.
9940     */
9941    @ViewDebug.ExportedProperty(category = "drawing")
9942    public float getX() {
9943        return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0);
9944    }
9945
9946    /**
9947     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
9948     * {@link #setTranslationX(float) translationX} property to be the difference between
9949     * the x value passed in and the current {@link #getLeft() left} property.
9950     *
9951     * @param x The visual x position of this view, in pixels.
9952     */
9953    public void setX(float x) {
9954        setTranslationX(x - mLeft);
9955    }
9956
9957    /**
9958     * The visual y position of this view, in pixels. This is equivalent to the
9959     * {@link #setTranslationY(float) translationY} property plus the current
9960     * {@link #getTop() top} property.
9961     *
9962     * @return The visual y position of this view, in pixels.
9963     */
9964    @ViewDebug.ExportedProperty(category = "drawing")
9965    public float getY() {
9966        return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0);
9967    }
9968
9969    /**
9970     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
9971     * {@link #setTranslationY(float) translationY} property to be the difference between
9972     * the y value passed in and the current {@link #getTop() top} property.
9973     *
9974     * @param y The visual y position of this view, in pixels.
9975     */
9976    public void setY(float y) {
9977        setTranslationY(y - mTop);
9978    }
9979
9980
9981    /**
9982     * The horizontal location of this view relative to its {@link #getLeft() left} position.
9983     * This position is post-layout, in addition to wherever the object's
9984     * layout placed it.
9985     *
9986     * @return The horizontal position of this view relative to its left position, in pixels.
9987     */
9988    @ViewDebug.ExportedProperty(category = "drawing")
9989    public float getTranslationX() {
9990        return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0;
9991    }
9992
9993    /**
9994     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
9995     * This effectively positions the object post-layout, in addition to wherever the object's
9996     * layout placed it.
9997     *
9998     * @param translationX The horizontal position of this view relative to its left position,
9999     * in pixels.
10000     *
10001     * @attr ref android.R.styleable#View_translationX
10002     */
10003    public void setTranslationX(float translationX) {
10004        ensureTransformationInfo();
10005        final TransformationInfo info = mTransformationInfo;
10006        if (info.mTranslationX != translationX) {
10007            // Double-invalidation is necessary to capture view's old and new areas
10008            invalidateViewProperty(true, false);
10009            info.mTranslationX = translationX;
10010            info.mMatrixDirty = true;
10011            invalidateViewProperty(false, true);
10012            if (mDisplayList != null) {
10013                mDisplayList.setTranslationX(translationX);
10014            }
10015            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10016                // View was rejected last time it was drawn by its parent; this may have changed
10017                invalidateParentIfNeeded();
10018            }
10019        }
10020    }
10021
10022    /**
10023     * The horizontal location of this view relative to its {@link #getTop() top} position.
10024     * This position is post-layout, in addition to wherever the object's
10025     * layout placed it.
10026     *
10027     * @return The vertical position of this view relative to its top position,
10028     * in pixels.
10029     */
10030    @ViewDebug.ExportedProperty(category = "drawing")
10031    public float getTranslationY() {
10032        return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0;
10033    }
10034
10035    /**
10036     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
10037     * This effectively positions the object post-layout, in addition to wherever the object's
10038     * layout placed it.
10039     *
10040     * @param translationY The vertical position of this view relative to its top position,
10041     * in pixels.
10042     *
10043     * @attr ref android.R.styleable#View_translationY
10044     */
10045    public void setTranslationY(float translationY) {
10046        ensureTransformationInfo();
10047        final TransformationInfo info = mTransformationInfo;
10048        if (info.mTranslationY != translationY) {
10049            invalidateViewProperty(true, false);
10050            info.mTranslationY = translationY;
10051            info.mMatrixDirty = true;
10052            invalidateViewProperty(false, true);
10053            if (mDisplayList != null) {
10054                mDisplayList.setTranslationY(translationY);
10055            }
10056            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10057                // View was rejected last time it was drawn by its parent; this may have changed
10058                invalidateParentIfNeeded();
10059            }
10060        }
10061    }
10062
10063    /**
10064     * Hit rectangle in parent's coordinates
10065     *
10066     * @param outRect The hit rectangle of the view.
10067     */
10068    public void getHitRect(Rect outRect) {
10069        updateMatrix();
10070        final TransformationInfo info = mTransformationInfo;
10071        if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) {
10072            outRect.set(mLeft, mTop, mRight, mBottom);
10073        } else {
10074            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
10075            tmpRect.set(0, 0, getWidth(), getHeight());
10076            info.mMatrix.mapRect(tmpRect);
10077            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
10078                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
10079        }
10080    }
10081
10082    /**
10083     * Determines whether the given point, in local coordinates is inside the view.
10084     */
10085    /*package*/ final boolean pointInView(float localX, float localY) {
10086        return localX >= 0 && localX < (mRight - mLeft)
10087                && localY >= 0 && localY < (mBottom - mTop);
10088    }
10089
10090    /**
10091     * Utility method to determine whether the given point, in local coordinates,
10092     * is inside the view, where the area of the view is expanded by the slop factor.
10093     * This method is called while processing touch-move events to determine if the event
10094     * is still within the view.
10095     *
10096     * @hide
10097     */
10098    public boolean pointInView(float localX, float localY, float slop) {
10099        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
10100                localY < ((mBottom - mTop) + slop);
10101    }
10102
10103    /**
10104     * When a view has focus and the user navigates away from it, the next view is searched for
10105     * starting from the rectangle filled in by this method.
10106     *
10107     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
10108     * of the view.  However, if your view maintains some idea of internal selection,
10109     * such as a cursor, or a selected row or column, you should override this method and
10110     * fill in a more specific rectangle.
10111     *
10112     * @param r The rectangle to fill in, in this view's coordinates.
10113     */
10114    public void getFocusedRect(Rect r) {
10115        getDrawingRect(r);
10116    }
10117
10118    /**
10119     * If some part of this view is not clipped by any of its parents, then
10120     * return that area in r in global (root) coordinates. To convert r to local
10121     * coordinates (without taking possible View rotations into account), offset
10122     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
10123     * If the view is completely clipped or translated out, return false.
10124     *
10125     * @param r If true is returned, r holds the global coordinates of the
10126     *        visible portion of this view.
10127     * @param globalOffset If true is returned, globalOffset holds the dx,dy
10128     *        between this view and its root. globalOffet may be null.
10129     * @return true if r is non-empty (i.e. part of the view is visible at the
10130     *         root level.
10131     */
10132    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
10133        int width = mRight - mLeft;
10134        int height = mBottom - mTop;
10135        if (width > 0 && height > 0) {
10136            r.set(0, 0, width, height);
10137            if (globalOffset != null) {
10138                globalOffset.set(-mScrollX, -mScrollY);
10139            }
10140            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
10141        }
10142        return false;
10143    }
10144
10145    public final boolean getGlobalVisibleRect(Rect r) {
10146        return getGlobalVisibleRect(r, null);
10147    }
10148
10149    public final boolean getLocalVisibleRect(Rect r) {
10150        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
10151        if (getGlobalVisibleRect(r, offset)) {
10152            r.offset(-offset.x, -offset.y); // make r local
10153            return true;
10154        }
10155        return false;
10156    }
10157
10158    /**
10159     * Offset this view's vertical location by the specified number of pixels.
10160     *
10161     * @param offset the number of pixels to offset the view by
10162     */
10163    public void offsetTopAndBottom(int offset) {
10164        if (offset != 0) {
10165            updateMatrix();
10166            final boolean matrixIsIdentity = mTransformationInfo == null
10167                    || mTransformationInfo.mMatrixIsIdentity;
10168            if (matrixIsIdentity) {
10169                if (mDisplayList != null) {
10170                    invalidateViewProperty(false, false);
10171                } else {
10172                    final ViewParent p = mParent;
10173                    if (p != null && mAttachInfo != null) {
10174                        final Rect r = mAttachInfo.mTmpInvalRect;
10175                        int minTop;
10176                        int maxBottom;
10177                        int yLoc;
10178                        if (offset < 0) {
10179                            minTop = mTop + offset;
10180                            maxBottom = mBottom;
10181                            yLoc = offset;
10182                        } else {
10183                            minTop = mTop;
10184                            maxBottom = mBottom + offset;
10185                            yLoc = 0;
10186                        }
10187                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
10188                        p.invalidateChild(this, r);
10189                    }
10190                }
10191            } else {
10192                invalidateViewProperty(false, false);
10193            }
10194
10195            mTop += offset;
10196            mBottom += offset;
10197            if (mDisplayList != null) {
10198                mDisplayList.offsetTopAndBottom(offset);
10199                invalidateViewProperty(false, false);
10200            } else {
10201                if (!matrixIsIdentity) {
10202                    invalidateViewProperty(false, true);
10203                }
10204                invalidateParentIfNeeded();
10205            }
10206        }
10207    }
10208
10209    /**
10210     * Offset this view's horizontal location by the specified amount of pixels.
10211     *
10212     * @param offset the number of pixels to offset the view by
10213     */
10214    public void offsetLeftAndRight(int offset) {
10215        if (offset != 0) {
10216            updateMatrix();
10217            final boolean matrixIsIdentity = mTransformationInfo == null
10218                    || mTransformationInfo.mMatrixIsIdentity;
10219            if (matrixIsIdentity) {
10220                if (mDisplayList != null) {
10221                    invalidateViewProperty(false, false);
10222                } else {
10223                    final ViewParent p = mParent;
10224                    if (p != null && mAttachInfo != null) {
10225                        final Rect r = mAttachInfo.mTmpInvalRect;
10226                        int minLeft;
10227                        int maxRight;
10228                        if (offset < 0) {
10229                            minLeft = mLeft + offset;
10230                            maxRight = mRight;
10231                        } else {
10232                            minLeft = mLeft;
10233                            maxRight = mRight + offset;
10234                        }
10235                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
10236                        p.invalidateChild(this, r);
10237                    }
10238                }
10239            } else {
10240                invalidateViewProperty(false, false);
10241            }
10242
10243            mLeft += offset;
10244            mRight += offset;
10245            if (mDisplayList != null) {
10246                mDisplayList.offsetLeftAndRight(offset);
10247                invalidateViewProperty(false, false);
10248            } else {
10249                if (!matrixIsIdentity) {
10250                    invalidateViewProperty(false, true);
10251                }
10252                invalidateParentIfNeeded();
10253            }
10254        }
10255    }
10256
10257    /**
10258     * Get the LayoutParams associated with this view. All views should have
10259     * layout parameters. These supply parameters to the <i>parent</i> of this
10260     * view specifying how it should be arranged. There are many subclasses of
10261     * ViewGroup.LayoutParams, and these correspond to the different subclasses
10262     * of ViewGroup that are responsible for arranging their children.
10263     *
10264     * This method may return null if this View is not attached to a parent
10265     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
10266     * was not invoked successfully. When a View is attached to a parent
10267     * ViewGroup, this method must not return null.
10268     *
10269     * @return The LayoutParams associated with this view, or null if no
10270     *         parameters have been set yet
10271     */
10272    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
10273    public ViewGroup.LayoutParams getLayoutParams() {
10274        return mLayoutParams;
10275    }
10276
10277    /**
10278     * Set the layout parameters associated with this view. These supply
10279     * parameters to the <i>parent</i> of this view specifying how it should be
10280     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
10281     * correspond to the different subclasses of ViewGroup that are responsible
10282     * for arranging their children.
10283     *
10284     * @param params The layout parameters for this view, cannot be null
10285     */
10286    public void setLayoutParams(ViewGroup.LayoutParams params) {
10287        if (params == null) {
10288            throw new NullPointerException("Layout parameters cannot be null");
10289        }
10290        mLayoutParams = params;
10291        resolveLayoutParams();
10292        if (mParent instanceof ViewGroup) {
10293            ((ViewGroup) mParent).onSetLayoutParams(this, params);
10294        }
10295        requestLayout();
10296    }
10297
10298    /**
10299     * Resolve the layout parameters depending on the resolved layout direction
10300     *
10301     * @hide
10302     */
10303    public void resolveLayoutParams() {
10304        if (mLayoutParams != null) {
10305            mLayoutParams.resolveLayoutDirection(getLayoutDirection());
10306        }
10307    }
10308
10309    /**
10310     * Set the scrolled position of your view. This will cause a call to
10311     * {@link #onScrollChanged(int, int, int, int)} and the view will be
10312     * invalidated.
10313     * @param x the x position to scroll to
10314     * @param y the y position to scroll to
10315     */
10316    public void scrollTo(int x, int y) {
10317        if (mScrollX != x || mScrollY != y) {
10318            int oldX = mScrollX;
10319            int oldY = mScrollY;
10320            mScrollX = x;
10321            mScrollY = y;
10322            invalidateParentCaches();
10323            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
10324            if (!awakenScrollBars()) {
10325                postInvalidateOnAnimation();
10326            }
10327        }
10328    }
10329
10330    /**
10331     * Move the scrolled position of your view. This will cause a call to
10332     * {@link #onScrollChanged(int, int, int, int)} and the view will be
10333     * invalidated.
10334     * @param x the amount of pixels to scroll by horizontally
10335     * @param y the amount of pixels to scroll by vertically
10336     */
10337    public void scrollBy(int x, int y) {
10338        scrollTo(mScrollX + x, mScrollY + y);
10339    }
10340
10341    /**
10342     * <p>Trigger the scrollbars to draw. When invoked this method starts an
10343     * animation to fade the scrollbars out after a default delay. If a subclass
10344     * provides animated scrolling, the start delay should equal the duration
10345     * of the scrolling animation.</p>
10346     *
10347     * <p>The animation starts only if at least one of the scrollbars is
10348     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
10349     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
10350     * this method returns true, and false otherwise. If the animation is
10351     * started, this method calls {@link #invalidate()}; in that case the
10352     * caller should not call {@link #invalidate()}.</p>
10353     *
10354     * <p>This method should be invoked every time a subclass directly updates
10355     * the scroll parameters.</p>
10356     *
10357     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
10358     * and {@link #scrollTo(int, int)}.</p>
10359     *
10360     * @return true if the animation is played, false otherwise
10361     *
10362     * @see #awakenScrollBars(int)
10363     * @see #scrollBy(int, int)
10364     * @see #scrollTo(int, int)
10365     * @see #isHorizontalScrollBarEnabled()
10366     * @see #isVerticalScrollBarEnabled()
10367     * @see #setHorizontalScrollBarEnabled(boolean)
10368     * @see #setVerticalScrollBarEnabled(boolean)
10369     */
10370    protected boolean awakenScrollBars() {
10371        return mScrollCache != null &&
10372                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
10373    }
10374
10375    /**
10376     * Trigger the scrollbars to draw.
10377     * This method differs from awakenScrollBars() only in its default duration.
10378     * initialAwakenScrollBars() will show the scroll bars for longer than
10379     * usual to give the user more of a chance to notice them.
10380     *
10381     * @return true if the animation is played, false otherwise.
10382     */
10383    private boolean initialAwakenScrollBars() {
10384        return mScrollCache != null &&
10385                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
10386    }
10387
10388    /**
10389     * <p>
10390     * Trigger the scrollbars to draw. When invoked this method starts an
10391     * animation to fade the scrollbars out after a fixed delay. If a subclass
10392     * provides animated scrolling, the start delay should equal the duration of
10393     * the scrolling animation.
10394     * </p>
10395     *
10396     * <p>
10397     * The animation starts only if at least one of the scrollbars is enabled,
10398     * as specified by {@link #isHorizontalScrollBarEnabled()} and
10399     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
10400     * this method returns true, and false otherwise. If the animation is
10401     * started, this method calls {@link #invalidate()}; in that case the caller
10402     * should not call {@link #invalidate()}.
10403     * </p>
10404     *
10405     * <p>
10406     * This method should be invoked everytime a subclass directly updates the
10407     * scroll parameters.
10408     * </p>
10409     *
10410     * @param startDelay the delay, in milliseconds, after which the animation
10411     *        should start; when the delay is 0, the animation starts
10412     *        immediately
10413     * @return true if the animation is played, false otherwise
10414     *
10415     * @see #scrollBy(int, int)
10416     * @see #scrollTo(int, int)
10417     * @see #isHorizontalScrollBarEnabled()
10418     * @see #isVerticalScrollBarEnabled()
10419     * @see #setHorizontalScrollBarEnabled(boolean)
10420     * @see #setVerticalScrollBarEnabled(boolean)
10421     */
10422    protected boolean awakenScrollBars(int startDelay) {
10423        return awakenScrollBars(startDelay, true);
10424    }
10425
10426    /**
10427     * <p>
10428     * Trigger the scrollbars to draw. When invoked this method starts an
10429     * animation to fade the scrollbars out after a fixed delay. If a subclass
10430     * provides animated scrolling, the start delay should equal the duration of
10431     * the scrolling animation.
10432     * </p>
10433     *
10434     * <p>
10435     * The animation starts only if at least one of the scrollbars is enabled,
10436     * as specified by {@link #isHorizontalScrollBarEnabled()} and
10437     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
10438     * this method returns true, and false otherwise. If the animation is
10439     * started, this method calls {@link #invalidate()} if the invalidate parameter
10440     * is set to true; in that case the caller
10441     * should not call {@link #invalidate()}.
10442     * </p>
10443     *
10444     * <p>
10445     * This method should be invoked everytime a subclass directly updates the
10446     * scroll parameters.
10447     * </p>
10448     *
10449     * @param startDelay the delay, in milliseconds, after which the animation
10450     *        should start; when the delay is 0, the animation starts
10451     *        immediately
10452     *
10453     * @param invalidate Wheter this method should call invalidate
10454     *
10455     * @return true if the animation is played, false otherwise
10456     *
10457     * @see #scrollBy(int, int)
10458     * @see #scrollTo(int, int)
10459     * @see #isHorizontalScrollBarEnabled()
10460     * @see #isVerticalScrollBarEnabled()
10461     * @see #setHorizontalScrollBarEnabled(boolean)
10462     * @see #setVerticalScrollBarEnabled(boolean)
10463     */
10464    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
10465        final ScrollabilityCache scrollCache = mScrollCache;
10466
10467        if (scrollCache == null || !scrollCache.fadeScrollBars) {
10468            return false;
10469        }
10470
10471        if (scrollCache.scrollBar == null) {
10472            scrollCache.scrollBar = new ScrollBarDrawable();
10473        }
10474
10475        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
10476
10477            if (invalidate) {
10478                // Invalidate to show the scrollbars
10479                postInvalidateOnAnimation();
10480            }
10481
10482            if (scrollCache.state == ScrollabilityCache.OFF) {
10483                // FIXME: this is copied from WindowManagerService.
10484                // We should get this value from the system when it
10485                // is possible to do so.
10486                final int KEY_REPEAT_FIRST_DELAY = 750;
10487                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
10488            }
10489
10490            // Tell mScrollCache when we should start fading. This may
10491            // extend the fade start time if one was already scheduled
10492            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
10493            scrollCache.fadeStartTime = fadeStartTime;
10494            scrollCache.state = ScrollabilityCache.ON;
10495
10496            // Schedule our fader to run, unscheduling any old ones first
10497            if (mAttachInfo != null) {
10498                mAttachInfo.mHandler.removeCallbacks(scrollCache);
10499                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
10500            }
10501
10502            return true;
10503        }
10504
10505        return false;
10506    }
10507
10508    /**
10509     * Do not invalidate views which are not visible and which are not running an animation. They
10510     * will not get drawn and they should not set dirty flags as if they will be drawn
10511     */
10512    private boolean skipInvalidate() {
10513        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
10514                (!(mParent instanceof ViewGroup) ||
10515                        !((ViewGroup) mParent).isViewTransitioning(this));
10516    }
10517    /**
10518     * Mark the area defined by dirty as needing to be drawn. If the view is
10519     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point
10520     * in the future. This must be called from a UI thread. To call from a non-UI
10521     * thread, call {@link #postInvalidate()}.
10522     *
10523     * WARNING: This method is destructive to dirty.
10524     * @param dirty the rectangle representing the bounds of the dirty region
10525     */
10526    public void invalidate(Rect dirty) {
10527        if (skipInvalidate()) {
10528            return;
10529        }
10530        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) ||
10531                (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID ||
10532                (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED) {
10533            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10534            mPrivateFlags |= PFLAG_INVALIDATED;
10535            mPrivateFlags |= PFLAG_DIRTY;
10536            final ViewParent p = mParent;
10537            final AttachInfo ai = mAttachInfo;
10538            //noinspection PointlessBooleanExpression,ConstantConditions
10539            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10540                if (p != null && ai != null && ai.mHardwareAccelerated) {
10541                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10542                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10543                    p.invalidateChild(this, null);
10544                    return;
10545                }
10546            }
10547            if (p != null && ai != null) {
10548                final int scrollX = mScrollX;
10549                final int scrollY = mScrollY;
10550                final Rect r = ai.mTmpInvalRect;
10551                r.set(dirty.left - scrollX, dirty.top - scrollY,
10552                        dirty.right - scrollX, dirty.bottom - scrollY);
10553                mParent.invalidateChild(this, r);
10554            }
10555        }
10556    }
10557
10558    /**
10559     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn.
10560     * The coordinates of the dirty rect are relative to the view.
10561     * If the view is visible, {@link #onDraw(android.graphics.Canvas)}
10562     * will be called at some point in the future. This must be called from
10563     * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
10564     * @param l the left position of the dirty region
10565     * @param t the top position of the dirty region
10566     * @param r the right position of the dirty region
10567     * @param b the bottom position of the dirty region
10568     */
10569    public void invalidate(int l, int t, int r, int b) {
10570        if (skipInvalidate()) {
10571            return;
10572        }
10573        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) ||
10574                (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID ||
10575                (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED) {
10576            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10577            mPrivateFlags |= PFLAG_INVALIDATED;
10578            mPrivateFlags |= PFLAG_DIRTY;
10579            final ViewParent p = mParent;
10580            final AttachInfo ai = mAttachInfo;
10581            //noinspection PointlessBooleanExpression,ConstantConditions
10582            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10583                if (p != null && ai != null && ai.mHardwareAccelerated) {
10584                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10585                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10586                    p.invalidateChild(this, null);
10587                    return;
10588                }
10589            }
10590            if (p != null && ai != null && l < r && t < b) {
10591                final int scrollX = mScrollX;
10592                final int scrollY = mScrollY;
10593                final Rect tmpr = ai.mTmpInvalRect;
10594                tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
10595                p.invalidateChild(this, tmpr);
10596            }
10597        }
10598    }
10599
10600    /**
10601     * Invalidate the whole view. If the view is visible,
10602     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
10603     * the future. This must be called from a UI thread. To call from a non-UI thread,
10604     * call {@link #postInvalidate()}.
10605     */
10606    public void invalidate() {
10607        invalidate(true);
10608    }
10609
10610    /**
10611     * This is where the invalidate() work actually happens. A full invalidate()
10612     * causes the drawing cache to be invalidated, but this function can be called with
10613     * invalidateCache set to false to skip that invalidation step for cases that do not
10614     * need it (for example, a component that remains at the same dimensions with the same
10615     * content).
10616     *
10617     * @param invalidateCache Whether the drawing cache for this view should be invalidated as
10618     * well. This is usually true for a full invalidate, but may be set to false if the
10619     * View's contents or dimensions have not changed.
10620     */
10621    void invalidate(boolean invalidateCache) {
10622        if (skipInvalidate()) {
10623            return;
10624        }
10625        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) ||
10626                (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) ||
10627                (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED || isOpaque() != mLastIsOpaque) {
10628            mLastIsOpaque = isOpaque();
10629            mPrivateFlags &= ~PFLAG_DRAWN;
10630            mPrivateFlags |= PFLAG_DIRTY;
10631            if (invalidateCache) {
10632                mPrivateFlags |= PFLAG_INVALIDATED;
10633                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10634            }
10635            final AttachInfo ai = mAttachInfo;
10636            final ViewParent p = mParent;
10637            //noinspection PointlessBooleanExpression,ConstantConditions
10638            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10639                if (p != null && ai != null && ai.mHardwareAccelerated) {
10640                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10641                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10642                    p.invalidateChild(this, null);
10643                    return;
10644                }
10645            }
10646
10647            if (p != null && ai != null) {
10648                final Rect r = ai.mTmpInvalRect;
10649                r.set(0, 0, mRight - mLeft, mBottom - mTop);
10650                // Don't call invalidate -- we don't want to internally scroll
10651                // our own bounds
10652                p.invalidateChild(this, r);
10653            }
10654        }
10655    }
10656
10657    /**
10658     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
10659     * set any flags or handle all of the cases handled by the default invalidation methods.
10660     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
10661     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
10662     * walk up the hierarchy, transforming the dirty rect as necessary.
10663     *
10664     * The method also handles normal invalidation logic if display list properties are not
10665     * being used in this view. The invalidateParent and forceRedraw flags are used by that
10666     * backup approach, to handle these cases used in the various property-setting methods.
10667     *
10668     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
10669     * are not being used in this view
10670     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
10671     * list properties are not being used in this view
10672     */
10673    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
10674        if (mDisplayList == null || (mPrivateFlags & PFLAG_DRAW_ANIMATION) == PFLAG_DRAW_ANIMATION) {
10675            if (invalidateParent) {
10676                invalidateParentCaches();
10677            }
10678            if (forceRedraw) {
10679                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10680            }
10681            invalidate(false);
10682        } else {
10683            final AttachInfo ai = mAttachInfo;
10684            final ViewParent p = mParent;
10685            if (p != null && ai != null) {
10686                final Rect r = ai.mTmpInvalRect;
10687                r.set(0, 0, mRight - mLeft, mBottom - mTop);
10688                if (mParent instanceof ViewGroup) {
10689                    ((ViewGroup) mParent).invalidateChildFast(this, r);
10690                } else {
10691                    mParent.invalidateChild(this, r);
10692                }
10693            }
10694        }
10695    }
10696
10697    /**
10698     * Utility method to transform a given Rect by the current matrix of this view.
10699     */
10700    void transformRect(final Rect rect) {
10701        if (!getMatrix().isIdentity()) {
10702            RectF boundingRect = mAttachInfo.mTmpTransformRect;
10703            boundingRect.set(rect);
10704            getMatrix().mapRect(boundingRect);
10705            rect.set((int) Math.floor(boundingRect.left),
10706                    (int) Math.floor(boundingRect.top),
10707                    (int) Math.ceil(boundingRect.right),
10708                    (int) Math.ceil(boundingRect.bottom));
10709        }
10710    }
10711
10712    /**
10713     * Used to indicate that the parent of this view should clear its caches. This functionality
10714     * is used to force the parent to rebuild its display list (when hardware-accelerated),
10715     * which is necessary when various parent-managed properties of the view change, such as
10716     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
10717     * clears the parent caches and does not causes an invalidate event.
10718     *
10719     * @hide
10720     */
10721    protected void invalidateParentCaches() {
10722        if (mParent instanceof View) {
10723            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
10724        }
10725    }
10726
10727    /**
10728     * Used to indicate that the parent of this view should be invalidated. This functionality
10729     * is used to force the parent to rebuild its display list (when hardware-accelerated),
10730     * which is necessary when various parent-managed properties of the view change, such as
10731     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
10732     * an invalidation event to the parent.
10733     *
10734     * @hide
10735     */
10736    protected void invalidateParentIfNeeded() {
10737        if (isHardwareAccelerated() && mParent instanceof View) {
10738            ((View) mParent).invalidate(true);
10739        }
10740    }
10741
10742    /**
10743     * Indicates whether this View is opaque. An opaque View guarantees that it will
10744     * draw all the pixels overlapping its bounds using a fully opaque color.
10745     *
10746     * Subclasses of View should override this method whenever possible to indicate
10747     * whether an instance is opaque. Opaque Views are treated in a special way by
10748     * the View hierarchy, possibly allowing it to perform optimizations during
10749     * invalidate/draw passes.
10750     *
10751     * @return True if this View is guaranteed to be fully opaque, false otherwise.
10752     */
10753    @ViewDebug.ExportedProperty(category = "drawing")
10754    public boolean isOpaque() {
10755        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
10756                ((mTransformationInfo != null ? mTransformationInfo.mAlpha : 1.0f) >= 1.0f);
10757    }
10758
10759    /**
10760     * @hide
10761     */
10762    protected void computeOpaqueFlags() {
10763        // Opaque if:
10764        //   - Has a background
10765        //   - Background is opaque
10766        //   - Doesn't have scrollbars or scrollbars overlay
10767
10768        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
10769            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
10770        } else {
10771            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
10772        }
10773
10774        final int flags = mViewFlags;
10775        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
10776                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY ||
10777                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) {
10778            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
10779        } else {
10780            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
10781        }
10782    }
10783
10784    /**
10785     * @hide
10786     */
10787    protected boolean hasOpaqueScrollbars() {
10788        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
10789    }
10790
10791    /**
10792     * @return A handler associated with the thread running the View. This
10793     * handler can be used to pump events in the UI events queue.
10794     */
10795    public Handler getHandler() {
10796        final AttachInfo attachInfo = mAttachInfo;
10797        if (attachInfo != null) {
10798            return attachInfo.mHandler;
10799        }
10800        return null;
10801    }
10802
10803    /**
10804     * Gets the view root associated with the View.
10805     * @return The view root, or null if none.
10806     * @hide
10807     */
10808    public ViewRootImpl getViewRootImpl() {
10809        if (mAttachInfo != null) {
10810            return mAttachInfo.mViewRootImpl;
10811        }
10812        return null;
10813    }
10814
10815    /**
10816     * <p>Causes the Runnable to be added to the message queue.
10817     * The runnable will be run on the user interface thread.</p>
10818     *
10819     * @param action The Runnable that will be executed.
10820     *
10821     * @return Returns true if the Runnable was successfully placed in to the
10822     *         message queue.  Returns false on failure, usually because the
10823     *         looper processing the message queue is exiting.
10824     *
10825     * @see #postDelayed
10826     * @see #removeCallbacks
10827     */
10828    public boolean post(Runnable action) {
10829        final AttachInfo attachInfo = mAttachInfo;
10830        if (attachInfo != null) {
10831            return attachInfo.mHandler.post(action);
10832        }
10833        // Assume that post will succeed later
10834        ViewRootImpl.getRunQueue().post(action);
10835        return true;
10836    }
10837
10838    /**
10839     * <p>Causes the Runnable to be added to the message queue, to be run
10840     * after the specified amount of time elapses.
10841     * The runnable will be run on the user interface thread.</p>
10842     *
10843     * @param action The Runnable that will be executed.
10844     * @param delayMillis The delay (in milliseconds) until the Runnable
10845     *        will be executed.
10846     *
10847     * @return true if the Runnable was successfully placed in to the
10848     *         message queue.  Returns false on failure, usually because the
10849     *         looper processing the message queue is exiting.  Note that a
10850     *         result of true does not mean the Runnable will be processed --
10851     *         if the looper is quit before the delivery time of the message
10852     *         occurs then the message will be dropped.
10853     *
10854     * @see #post
10855     * @see #removeCallbacks
10856     */
10857    public boolean postDelayed(Runnable action, long delayMillis) {
10858        final AttachInfo attachInfo = mAttachInfo;
10859        if (attachInfo != null) {
10860            return attachInfo.mHandler.postDelayed(action, delayMillis);
10861        }
10862        // Assume that post will succeed later
10863        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
10864        return true;
10865    }
10866
10867    /**
10868     * <p>Causes the Runnable to execute on the next animation time step.
10869     * The runnable will be run on the user interface thread.</p>
10870     *
10871     * @param action The Runnable that will be executed.
10872     *
10873     * @see #postOnAnimationDelayed
10874     * @see #removeCallbacks
10875     */
10876    public void postOnAnimation(Runnable action) {
10877        final AttachInfo attachInfo = mAttachInfo;
10878        if (attachInfo != null) {
10879            attachInfo.mViewRootImpl.mChoreographer.postCallback(
10880                    Choreographer.CALLBACK_ANIMATION, action, null);
10881        } else {
10882            // Assume that post will succeed later
10883            ViewRootImpl.getRunQueue().post(action);
10884        }
10885    }
10886
10887    /**
10888     * <p>Causes the Runnable to execute on the next animation time step,
10889     * after the specified amount of time elapses.
10890     * The runnable will be run on the user interface thread.</p>
10891     *
10892     * @param action The Runnable that will be executed.
10893     * @param delayMillis The delay (in milliseconds) until the Runnable
10894     *        will be executed.
10895     *
10896     * @see #postOnAnimation
10897     * @see #removeCallbacks
10898     */
10899    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
10900        final AttachInfo attachInfo = mAttachInfo;
10901        if (attachInfo != null) {
10902            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
10903                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
10904        } else {
10905            // Assume that post will succeed later
10906            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
10907        }
10908    }
10909
10910    /**
10911     * <p>Removes the specified Runnable from the message queue.</p>
10912     *
10913     * @param action The Runnable to remove from the message handling queue
10914     *
10915     * @return true if this view could ask the Handler to remove the Runnable,
10916     *         false otherwise. When the returned value is true, the Runnable
10917     *         may or may not have been actually removed from the message queue
10918     *         (for instance, if the Runnable was not in the queue already.)
10919     *
10920     * @see #post
10921     * @see #postDelayed
10922     * @see #postOnAnimation
10923     * @see #postOnAnimationDelayed
10924     */
10925    public boolean removeCallbacks(Runnable action) {
10926        if (action != null) {
10927            final AttachInfo attachInfo = mAttachInfo;
10928            if (attachInfo != null) {
10929                attachInfo.mHandler.removeCallbacks(action);
10930                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
10931                        Choreographer.CALLBACK_ANIMATION, action, null);
10932            } else {
10933                // Assume that post will succeed later
10934                ViewRootImpl.getRunQueue().removeCallbacks(action);
10935            }
10936        }
10937        return true;
10938    }
10939
10940    /**
10941     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
10942     * Use this to invalidate the View from a non-UI thread.</p>
10943     *
10944     * <p>This method can be invoked from outside of the UI thread
10945     * only when this View is attached to a window.</p>
10946     *
10947     * @see #invalidate()
10948     * @see #postInvalidateDelayed(long)
10949     */
10950    public void postInvalidate() {
10951        postInvalidateDelayed(0);
10952    }
10953
10954    /**
10955     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
10956     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
10957     *
10958     * <p>This method can be invoked from outside of the UI thread
10959     * only when this View is attached to a window.</p>
10960     *
10961     * @param left The left coordinate of the rectangle to invalidate.
10962     * @param top The top coordinate of the rectangle to invalidate.
10963     * @param right The right coordinate of the rectangle to invalidate.
10964     * @param bottom The bottom coordinate of the rectangle to invalidate.
10965     *
10966     * @see #invalidate(int, int, int, int)
10967     * @see #invalidate(Rect)
10968     * @see #postInvalidateDelayed(long, int, int, int, int)
10969     */
10970    public void postInvalidate(int left, int top, int right, int bottom) {
10971        postInvalidateDelayed(0, left, top, right, bottom);
10972    }
10973
10974    /**
10975     * <p>Cause an invalidate to happen on a subsequent cycle through the event
10976     * loop. Waits for the specified amount of time.</p>
10977     *
10978     * <p>This method can be invoked from outside of the UI thread
10979     * only when this View is attached to a window.</p>
10980     *
10981     * @param delayMilliseconds the duration in milliseconds to delay the
10982     *         invalidation by
10983     *
10984     * @see #invalidate()
10985     * @see #postInvalidate()
10986     */
10987    public void postInvalidateDelayed(long delayMilliseconds) {
10988        // We try only with the AttachInfo because there's no point in invalidating
10989        // if we are not attached to our window
10990        final AttachInfo attachInfo = mAttachInfo;
10991        if (attachInfo != null) {
10992            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
10993        }
10994    }
10995
10996    /**
10997     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
10998     * through the event loop. Waits for the specified amount of time.</p>
10999     *
11000     * <p>This method can be invoked from outside of the UI thread
11001     * only when this View is attached to a window.</p>
11002     *
11003     * @param delayMilliseconds the duration in milliseconds to delay the
11004     *         invalidation by
11005     * @param left The left coordinate of the rectangle to invalidate.
11006     * @param top The top coordinate of the rectangle to invalidate.
11007     * @param right The right coordinate of the rectangle to invalidate.
11008     * @param bottom The bottom coordinate of the rectangle to invalidate.
11009     *
11010     * @see #invalidate(int, int, int, int)
11011     * @see #invalidate(Rect)
11012     * @see #postInvalidate(int, int, int, int)
11013     */
11014    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
11015            int right, int bottom) {
11016
11017        // We try only with the AttachInfo because there's no point in invalidating
11018        // if we are not attached to our window
11019        final AttachInfo attachInfo = mAttachInfo;
11020        if (attachInfo != null) {
11021            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
11022            info.target = this;
11023            info.left = left;
11024            info.top = top;
11025            info.right = right;
11026            info.bottom = bottom;
11027
11028            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
11029        }
11030    }
11031
11032    /**
11033     * <p>Cause an invalidate to happen on the next animation time step, typically the
11034     * next display frame.</p>
11035     *
11036     * <p>This method can be invoked from outside of the UI thread
11037     * only when this View is attached to a window.</p>
11038     *
11039     * @see #invalidate()
11040     */
11041    public void postInvalidateOnAnimation() {
11042        // We try only with the AttachInfo because there's no point in invalidating
11043        // if we are not attached to our window
11044        final AttachInfo attachInfo = mAttachInfo;
11045        if (attachInfo != null) {
11046            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
11047        }
11048    }
11049
11050    /**
11051     * <p>Cause an invalidate of the specified area to happen on the next animation
11052     * time step, typically the next display frame.</p>
11053     *
11054     * <p>This method can be invoked from outside of the UI thread
11055     * only when this View is attached to a window.</p>
11056     *
11057     * @param left The left coordinate of the rectangle to invalidate.
11058     * @param top The top coordinate of the rectangle to invalidate.
11059     * @param right The right coordinate of the rectangle to invalidate.
11060     * @param bottom The bottom coordinate of the rectangle to invalidate.
11061     *
11062     * @see #invalidate(int, int, int, int)
11063     * @see #invalidate(Rect)
11064     */
11065    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
11066        // We try only with the AttachInfo because there's no point in invalidating
11067        // if we are not attached to our window
11068        final AttachInfo attachInfo = mAttachInfo;
11069        if (attachInfo != null) {
11070            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
11071            info.target = this;
11072            info.left = left;
11073            info.top = top;
11074            info.right = right;
11075            info.bottom = bottom;
11076
11077            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
11078        }
11079    }
11080
11081    /**
11082     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
11083     * This event is sent at most once every
11084     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
11085     */
11086    private void postSendViewScrolledAccessibilityEventCallback() {
11087        if (mSendViewScrolledAccessibilityEvent == null) {
11088            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
11089        }
11090        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
11091            mSendViewScrolledAccessibilityEvent.mIsPending = true;
11092            postDelayed(mSendViewScrolledAccessibilityEvent,
11093                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
11094        }
11095    }
11096
11097    /**
11098     * Called by a parent to request that a child update its values for mScrollX
11099     * and mScrollY if necessary. This will typically be done if the child is
11100     * animating a scroll using a {@link android.widget.Scroller Scroller}
11101     * object.
11102     */
11103    public void computeScroll() {
11104    }
11105
11106    /**
11107     * <p>Indicate whether the horizontal edges are faded when the view is
11108     * scrolled horizontally.</p>
11109     *
11110     * @return true if the horizontal edges should are faded on scroll, false
11111     *         otherwise
11112     *
11113     * @see #setHorizontalFadingEdgeEnabled(boolean)
11114     *
11115     * @attr ref android.R.styleable#View_requiresFadingEdge
11116     */
11117    public boolean isHorizontalFadingEdgeEnabled() {
11118        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
11119    }
11120
11121    /**
11122     * <p>Define whether the horizontal edges should be faded when this view
11123     * is scrolled horizontally.</p>
11124     *
11125     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
11126     *                                    be faded when the view is scrolled
11127     *                                    horizontally
11128     *
11129     * @see #isHorizontalFadingEdgeEnabled()
11130     *
11131     * @attr ref android.R.styleable#View_requiresFadingEdge
11132     */
11133    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
11134        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
11135            if (horizontalFadingEdgeEnabled) {
11136                initScrollCache();
11137            }
11138
11139            mViewFlags ^= FADING_EDGE_HORIZONTAL;
11140        }
11141    }
11142
11143    /**
11144     * <p>Indicate whether the vertical edges are faded when the view is
11145     * scrolled horizontally.</p>
11146     *
11147     * @return true if the vertical edges should are faded on scroll, false
11148     *         otherwise
11149     *
11150     * @see #setVerticalFadingEdgeEnabled(boolean)
11151     *
11152     * @attr ref android.R.styleable#View_requiresFadingEdge
11153     */
11154    public boolean isVerticalFadingEdgeEnabled() {
11155        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
11156    }
11157
11158    /**
11159     * <p>Define whether the vertical edges should be faded when this view
11160     * is scrolled vertically.</p>
11161     *
11162     * @param verticalFadingEdgeEnabled true if the vertical edges should
11163     *                                  be faded when the view is scrolled
11164     *                                  vertically
11165     *
11166     * @see #isVerticalFadingEdgeEnabled()
11167     *
11168     * @attr ref android.R.styleable#View_requiresFadingEdge
11169     */
11170    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
11171        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
11172            if (verticalFadingEdgeEnabled) {
11173                initScrollCache();
11174            }
11175
11176            mViewFlags ^= FADING_EDGE_VERTICAL;
11177        }
11178    }
11179
11180    /**
11181     * Returns the strength, or intensity, of the top faded edge. The strength is
11182     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11183     * returns 0.0 or 1.0 but no value in between.
11184     *
11185     * Subclasses should override this method to provide a smoother fade transition
11186     * when scrolling occurs.
11187     *
11188     * @return the intensity of the top fade as a float between 0.0f and 1.0f
11189     */
11190    protected float getTopFadingEdgeStrength() {
11191        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
11192    }
11193
11194    /**
11195     * Returns the strength, or intensity, of the bottom faded edge. The strength is
11196     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11197     * returns 0.0 or 1.0 but no value in between.
11198     *
11199     * Subclasses should override this method to provide a smoother fade transition
11200     * when scrolling occurs.
11201     *
11202     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
11203     */
11204    protected float getBottomFadingEdgeStrength() {
11205        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
11206                computeVerticalScrollRange() ? 1.0f : 0.0f;
11207    }
11208
11209    /**
11210     * Returns the strength, or intensity, of the left faded edge. The strength is
11211     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11212     * returns 0.0 or 1.0 but no value in between.
11213     *
11214     * Subclasses should override this method to provide a smoother fade transition
11215     * when scrolling occurs.
11216     *
11217     * @return the intensity of the left fade as a float between 0.0f and 1.0f
11218     */
11219    protected float getLeftFadingEdgeStrength() {
11220        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
11221    }
11222
11223    /**
11224     * Returns the strength, or intensity, of the right faded edge. The strength is
11225     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11226     * returns 0.0 or 1.0 but no value in between.
11227     *
11228     * Subclasses should override this method to provide a smoother fade transition
11229     * when scrolling occurs.
11230     *
11231     * @return the intensity of the right fade as a float between 0.0f and 1.0f
11232     */
11233    protected float getRightFadingEdgeStrength() {
11234        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
11235                computeHorizontalScrollRange() ? 1.0f : 0.0f;
11236    }
11237
11238    /**
11239     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
11240     * scrollbar is not drawn by default.</p>
11241     *
11242     * @return true if the horizontal scrollbar should be painted, false
11243     *         otherwise
11244     *
11245     * @see #setHorizontalScrollBarEnabled(boolean)
11246     */
11247    public boolean isHorizontalScrollBarEnabled() {
11248        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
11249    }
11250
11251    /**
11252     * <p>Define whether the horizontal scrollbar should be drawn or not. The
11253     * scrollbar is not drawn by default.</p>
11254     *
11255     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
11256     *                                   be painted
11257     *
11258     * @see #isHorizontalScrollBarEnabled()
11259     */
11260    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
11261        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
11262            mViewFlags ^= SCROLLBARS_HORIZONTAL;
11263            computeOpaqueFlags();
11264            resolvePadding();
11265        }
11266    }
11267
11268    /**
11269     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
11270     * scrollbar is not drawn by default.</p>
11271     *
11272     * @return true if the vertical scrollbar should be painted, false
11273     *         otherwise
11274     *
11275     * @see #setVerticalScrollBarEnabled(boolean)
11276     */
11277    public boolean isVerticalScrollBarEnabled() {
11278        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
11279    }
11280
11281    /**
11282     * <p>Define whether the vertical scrollbar should be drawn or not. The
11283     * scrollbar is not drawn by default.</p>
11284     *
11285     * @param verticalScrollBarEnabled true if the vertical scrollbar should
11286     *                                 be painted
11287     *
11288     * @see #isVerticalScrollBarEnabled()
11289     */
11290    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
11291        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
11292            mViewFlags ^= SCROLLBARS_VERTICAL;
11293            computeOpaqueFlags();
11294            resolvePadding();
11295        }
11296    }
11297
11298    /**
11299     * @hide
11300     */
11301    protected void recomputePadding() {
11302        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
11303    }
11304
11305    /**
11306     * Define whether scrollbars will fade when the view is not scrolling.
11307     *
11308     * @param fadeScrollbars wheter to enable fading
11309     *
11310     * @attr ref android.R.styleable#View_fadeScrollbars
11311     */
11312    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
11313        initScrollCache();
11314        final ScrollabilityCache scrollabilityCache = mScrollCache;
11315        scrollabilityCache.fadeScrollBars = fadeScrollbars;
11316        if (fadeScrollbars) {
11317            scrollabilityCache.state = ScrollabilityCache.OFF;
11318        } else {
11319            scrollabilityCache.state = ScrollabilityCache.ON;
11320        }
11321    }
11322
11323    /**
11324     *
11325     * Returns true if scrollbars will fade when this view is not scrolling
11326     *
11327     * @return true if scrollbar fading is enabled
11328     *
11329     * @attr ref android.R.styleable#View_fadeScrollbars
11330     */
11331    public boolean isScrollbarFadingEnabled() {
11332        return mScrollCache != null && mScrollCache.fadeScrollBars;
11333    }
11334
11335    /**
11336     *
11337     * Returns the delay before scrollbars fade.
11338     *
11339     * @return the delay before scrollbars fade
11340     *
11341     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
11342     */
11343    public int getScrollBarDefaultDelayBeforeFade() {
11344        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
11345                mScrollCache.scrollBarDefaultDelayBeforeFade;
11346    }
11347
11348    /**
11349     * Define the delay before scrollbars fade.
11350     *
11351     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
11352     *
11353     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
11354     */
11355    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
11356        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
11357    }
11358
11359    /**
11360     *
11361     * Returns the scrollbar fade duration.
11362     *
11363     * @return the scrollbar fade duration
11364     *
11365     * @attr ref android.R.styleable#View_scrollbarFadeDuration
11366     */
11367    public int getScrollBarFadeDuration() {
11368        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
11369                mScrollCache.scrollBarFadeDuration;
11370    }
11371
11372    /**
11373     * Define the scrollbar fade duration.
11374     *
11375     * @param scrollBarFadeDuration - the scrollbar fade duration
11376     *
11377     * @attr ref android.R.styleable#View_scrollbarFadeDuration
11378     */
11379    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
11380        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
11381    }
11382
11383    /**
11384     *
11385     * Returns the scrollbar size.
11386     *
11387     * @return the scrollbar size
11388     *
11389     * @attr ref android.R.styleable#View_scrollbarSize
11390     */
11391    public int getScrollBarSize() {
11392        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
11393                mScrollCache.scrollBarSize;
11394    }
11395
11396    /**
11397     * Define the scrollbar size.
11398     *
11399     * @param scrollBarSize - the scrollbar size
11400     *
11401     * @attr ref android.R.styleable#View_scrollbarSize
11402     */
11403    public void setScrollBarSize(int scrollBarSize) {
11404        getScrollCache().scrollBarSize = scrollBarSize;
11405    }
11406
11407    /**
11408     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
11409     * inset. When inset, they add to the padding of the view. And the scrollbars
11410     * can be drawn inside the padding area or on the edge of the view. For example,
11411     * if a view has a background drawable and you want to draw the scrollbars
11412     * inside the padding specified by the drawable, you can use
11413     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
11414     * appear at the edge of the view, ignoring the padding, then you can use
11415     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
11416     * @param style the style of the scrollbars. Should be one of
11417     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
11418     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
11419     * @see #SCROLLBARS_INSIDE_OVERLAY
11420     * @see #SCROLLBARS_INSIDE_INSET
11421     * @see #SCROLLBARS_OUTSIDE_OVERLAY
11422     * @see #SCROLLBARS_OUTSIDE_INSET
11423     *
11424     * @attr ref android.R.styleable#View_scrollbarStyle
11425     */
11426    public void setScrollBarStyle(int style) {
11427        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
11428            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
11429            computeOpaqueFlags();
11430            resolvePadding();
11431        }
11432    }
11433
11434    /**
11435     * <p>Returns the current scrollbar style.</p>
11436     * @return the current scrollbar style
11437     * @see #SCROLLBARS_INSIDE_OVERLAY
11438     * @see #SCROLLBARS_INSIDE_INSET
11439     * @see #SCROLLBARS_OUTSIDE_OVERLAY
11440     * @see #SCROLLBARS_OUTSIDE_INSET
11441     *
11442     * @attr ref android.R.styleable#View_scrollbarStyle
11443     */
11444    @ViewDebug.ExportedProperty(mapping = {
11445            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
11446            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
11447            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
11448            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
11449    })
11450    public int getScrollBarStyle() {
11451        return mViewFlags & SCROLLBARS_STYLE_MASK;
11452    }
11453
11454    /**
11455     * <p>Compute the horizontal range that the horizontal scrollbar
11456     * represents.</p>
11457     *
11458     * <p>The range is expressed in arbitrary units that must be the same as the
11459     * units used by {@link #computeHorizontalScrollExtent()} and
11460     * {@link #computeHorizontalScrollOffset()}.</p>
11461     *
11462     * <p>The default range is the drawing width of this view.</p>
11463     *
11464     * @return the total horizontal range represented by the horizontal
11465     *         scrollbar
11466     *
11467     * @see #computeHorizontalScrollExtent()
11468     * @see #computeHorizontalScrollOffset()
11469     * @see android.widget.ScrollBarDrawable
11470     */
11471    protected int computeHorizontalScrollRange() {
11472        return getWidth();
11473    }
11474
11475    /**
11476     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
11477     * within the horizontal range. This value is used to compute the position
11478     * of the thumb within the scrollbar's track.</p>
11479     *
11480     * <p>The range is expressed in arbitrary units that must be the same as the
11481     * units used by {@link #computeHorizontalScrollRange()} and
11482     * {@link #computeHorizontalScrollExtent()}.</p>
11483     *
11484     * <p>The default offset is the scroll offset of this view.</p>
11485     *
11486     * @return the horizontal offset of the scrollbar's thumb
11487     *
11488     * @see #computeHorizontalScrollRange()
11489     * @see #computeHorizontalScrollExtent()
11490     * @see android.widget.ScrollBarDrawable
11491     */
11492    protected int computeHorizontalScrollOffset() {
11493        return mScrollX;
11494    }
11495
11496    /**
11497     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
11498     * within the horizontal range. This value is used to compute the length
11499     * of the thumb within the scrollbar's track.</p>
11500     *
11501     * <p>The range is expressed in arbitrary units that must be the same as the
11502     * units used by {@link #computeHorizontalScrollRange()} and
11503     * {@link #computeHorizontalScrollOffset()}.</p>
11504     *
11505     * <p>The default extent is the drawing width of this view.</p>
11506     *
11507     * @return the horizontal extent of the scrollbar's thumb
11508     *
11509     * @see #computeHorizontalScrollRange()
11510     * @see #computeHorizontalScrollOffset()
11511     * @see android.widget.ScrollBarDrawable
11512     */
11513    protected int computeHorizontalScrollExtent() {
11514        return getWidth();
11515    }
11516
11517    /**
11518     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
11519     *
11520     * <p>The range is expressed in arbitrary units that must be the same as the
11521     * units used by {@link #computeVerticalScrollExtent()} and
11522     * {@link #computeVerticalScrollOffset()}.</p>
11523     *
11524     * @return the total vertical range represented by the vertical scrollbar
11525     *
11526     * <p>The default range is the drawing height of this view.</p>
11527     *
11528     * @see #computeVerticalScrollExtent()
11529     * @see #computeVerticalScrollOffset()
11530     * @see android.widget.ScrollBarDrawable
11531     */
11532    protected int computeVerticalScrollRange() {
11533        return getHeight();
11534    }
11535
11536    /**
11537     * <p>Compute the vertical offset of the vertical scrollbar's thumb
11538     * within the horizontal range. This value is used to compute the position
11539     * of the thumb within the scrollbar's track.</p>
11540     *
11541     * <p>The range is expressed in arbitrary units that must be the same as the
11542     * units used by {@link #computeVerticalScrollRange()} and
11543     * {@link #computeVerticalScrollExtent()}.</p>
11544     *
11545     * <p>The default offset is the scroll offset of this view.</p>
11546     *
11547     * @return the vertical offset of the scrollbar's thumb
11548     *
11549     * @see #computeVerticalScrollRange()
11550     * @see #computeVerticalScrollExtent()
11551     * @see android.widget.ScrollBarDrawable
11552     */
11553    protected int computeVerticalScrollOffset() {
11554        return mScrollY;
11555    }
11556
11557    /**
11558     * <p>Compute the vertical extent of the horizontal scrollbar's thumb
11559     * within the vertical range. This value is used to compute the length
11560     * of the thumb within the scrollbar's track.</p>
11561     *
11562     * <p>The range is expressed in arbitrary units that must be the same as the
11563     * units used by {@link #computeVerticalScrollRange()} and
11564     * {@link #computeVerticalScrollOffset()}.</p>
11565     *
11566     * <p>The default extent is the drawing height of this view.</p>
11567     *
11568     * @return the vertical extent of the scrollbar's thumb
11569     *
11570     * @see #computeVerticalScrollRange()
11571     * @see #computeVerticalScrollOffset()
11572     * @see android.widget.ScrollBarDrawable
11573     */
11574    protected int computeVerticalScrollExtent() {
11575        return getHeight();
11576    }
11577
11578    /**
11579     * Check if this view can be scrolled horizontally in a certain direction.
11580     *
11581     * @param direction Negative to check scrolling left, positive to check scrolling right.
11582     * @return true if this view can be scrolled in the specified direction, false otherwise.
11583     */
11584    public boolean canScrollHorizontally(int direction) {
11585        final int offset = computeHorizontalScrollOffset();
11586        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
11587        if (range == 0) return false;
11588        if (direction < 0) {
11589            return offset > 0;
11590        } else {
11591            return offset < range - 1;
11592        }
11593    }
11594
11595    /**
11596     * Check if this view can be scrolled vertically in a certain direction.
11597     *
11598     * @param direction Negative to check scrolling up, positive to check scrolling down.
11599     * @return true if this view can be scrolled in the specified direction, false otherwise.
11600     */
11601    public boolean canScrollVertically(int direction) {
11602        final int offset = computeVerticalScrollOffset();
11603        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
11604        if (range == 0) return false;
11605        if (direction < 0) {
11606            return offset > 0;
11607        } else {
11608            return offset < range - 1;
11609        }
11610    }
11611
11612    /**
11613     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
11614     * scrollbars are painted only if they have been awakened first.</p>
11615     *
11616     * @param canvas the canvas on which to draw the scrollbars
11617     *
11618     * @see #awakenScrollBars(int)
11619     */
11620    protected final void onDrawScrollBars(Canvas canvas) {
11621        // scrollbars are drawn only when the animation is running
11622        final ScrollabilityCache cache = mScrollCache;
11623        if (cache != null) {
11624
11625            int state = cache.state;
11626
11627            if (state == ScrollabilityCache.OFF) {
11628                return;
11629            }
11630
11631            boolean invalidate = false;
11632
11633            if (state == ScrollabilityCache.FADING) {
11634                // We're fading -- get our fade interpolation
11635                if (cache.interpolatorValues == null) {
11636                    cache.interpolatorValues = new float[1];
11637                }
11638
11639                float[] values = cache.interpolatorValues;
11640
11641                // Stops the animation if we're done
11642                if (cache.scrollBarInterpolator.timeToValues(values) ==
11643                        Interpolator.Result.FREEZE_END) {
11644                    cache.state = ScrollabilityCache.OFF;
11645                } else {
11646                    cache.scrollBar.setAlpha(Math.round(values[0]));
11647                }
11648
11649                // This will make the scroll bars inval themselves after
11650                // drawing. We only want this when we're fading so that
11651                // we prevent excessive redraws
11652                invalidate = true;
11653            } else {
11654                // We're just on -- but we may have been fading before so
11655                // reset alpha
11656                cache.scrollBar.setAlpha(255);
11657            }
11658
11659
11660            final int viewFlags = mViewFlags;
11661
11662            final boolean drawHorizontalScrollBar =
11663                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
11664            final boolean drawVerticalScrollBar =
11665                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
11666                && !isVerticalScrollBarHidden();
11667
11668            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
11669                final int width = mRight - mLeft;
11670                final int height = mBottom - mTop;
11671
11672                final ScrollBarDrawable scrollBar = cache.scrollBar;
11673
11674                final int scrollX = mScrollX;
11675                final int scrollY = mScrollY;
11676                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
11677
11678                int left;
11679                int top;
11680                int right;
11681                int bottom;
11682
11683                if (drawHorizontalScrollBar) {
11684                    int size = scrollBar.getSize(false);
11685                    if (size <= 0) {
11686                        size = cache.scrollBarSize;
11687                    }
11688
11689                    scrollBar.setParameters(computeHorizontalScrollRange(),
11690                                            computeHorizontalScrollOffset(),
11691                                            computeHorizontalScrollExtent(), false);
11692                    final int verticalScrollBarGap = drawVerticalScrollBar ?
11693                            getVerticalScrollbarWidth() : 0;
11694                    top = scrollY + height - size - (mUserPaddingBottom & inside);
11695                    left = scrollX + (mPaddingLeft & inside);
11696                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
11697                    bottom = top + size;
11698                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
11699                    if (invalidate) {
11700                        invalidate(left, top, right, bottom);
11701                    }
11702                }
11703
11704                if (drawVerticalScrollBar) {
11705                    int size = scrollBar.getSize(true);
11706                    if (size <= 0) {
11707                        size = cache.scrollBarSize;
11708                    }
11709
11710                    scrollBar.setParameters(computeVerticalScrollRange(),
11711                                            computeVerticalScrollOffset(),
11712                                            computeVerticalScrollExtent(), true);
11713                    int verticalScrollbarPosition = mVerticalScrollbarPosition;
11714                    if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
11715                        verticalScrollbarPosition = isLayoutRtl() ?
11716                                SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
11717                    }
11718                    switch (verticalScrollbarPosition) {
11719                        default:
11720                        case SCROLLBAR_POSITION_RIGHT:
11721                            left = scrollX + width - size - (mUserPaddingRight & inside);
11722                            break;
11723                        case SCROLLBAR_POSITION_LEFT:
11724                            left = scrollX + (mUserPaddingLeft & inside);
11725                            break;
11726                    }
11727                    top = scrollY + (mPaddingTop & inside);
11728                    right = left + size;
11729                    bottom = scrollY + height - (mUserPaddingBottom & inside);
11730                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
11731                    if (invalidate) {
11732                        invalidate(left, top, right, bottom);
11733                    }
11734                }
11735            }
11736        }
11737    }
11738
11739    /**
11740     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
11741     * FastScroller is visible.
11742     * @return whether to temporarily hide the vertical scrollbar
11743     * @hide
11744     */
11745    protected boolean isVerticalScrollBarHidden() {
11746        return false;
11747    }
11748
11749    /**
11750     * <p>Draw the horizontal scrollbar if
11751     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
11752     *
11753     * @param canvas the canvas on which to draw the scrollbar
11754     * @param scrollBar the scrollbar's drawable
11755     *
11756     * @see #isHorizontalScrollBarEnabled()
11757     * @see #computeHorizontalScrollRange()
11758     * @see #computeHorizontalScrollExtent()
11759     * @see #computeHorizontalScrollOffset()
11760     * @see android.widget.ScrollBarDrawable
11761     * @hide
11762     */
11763    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
11764            int l, int t, int r, int b) {
11765        scrollBar.setBounds(l, t, r, b);
11766        scrollBar.draw(canvas);
11767    }
11768
11769    /**
11770     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
11771     * returns true.</p>
11772     *
11773     * @param canvas the canvas on which to draw the scrollbar
11774     * @param scrollBar the scrollbar's drawable
11775     *
11776     * @see #isVerticalScrollBarEnabled()
11777     * @see #computeVerticalScrollRange()
11778     * @see #computeVerticalScrollExtent()
11779     * @see #computeVerticalScrollOffset()
11780     * @see android.widget.ScrollBarDrawable
11781     * @hide
11782     */
11783    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
11784            int l, int t, int r, int b) {
11785        scrollBar.setBounds(l, t, r, b);
11786        scrollBar.draw(canvas);
11787    }
11788
11789    /**
11790     * Implement this to do your drawing.
11791     *
11792     * @param canvas the canvas on which the background will be drawn
11793     */
11794    protected void onDraw(Canvas canvas) {
11795    }
11796
11797    /*
11798     * Caller is responsible for calling requestLayout if necessary.
11799     * (This allows addViewInLayout to not request a new layout.)
11800     */
11801    void assignParent(ViewParent parent) {
11802        if (mParent == null) {
11803            mParent = parent;
11804        } else if (parent == null) {
11805            mParent = null;
11806        } else {
11807            throw new RuntimeException("view " + this + " being added, but"
11808                    + " it already has a parent");
11809        }
11810    }
11811
11812    /**
11813     * This is called when the view is attached to a window.  At this point it
11814     * has a Surface and will start drawing.  Note that this function is
11815     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
11816     * however it may be called any time before the first onDraw -- including
11817     * before or after {@link #onMeasure(int, int)}.
11818     *
11819     * @see #onDetachedFromWindow()
11820     */
11821    protected void onAttachedToWindow() {
11822        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
11823            mParent.requestTransparentRegion(this);
11824        }
11825
11826        if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
11827            initialAwakenScrollBars();
11828            mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
11829        }
11830
11831        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
11832
11833        jumpDrawablesToCurrentState();
11834
11835        clearAccessibilityFocus();
11836        resetSubtreeAccessibilityStateChanged();
11837
11838        if (isFocused()) {
11839            InputMethodManager imm = InputMethodManager.peekInstance();
11840            imm.focusIn(this);
11841        }
11842
11843        if (mDisplayList != null) {
11844            mDisplayList.clearDirty();
11845        }
11846    }
11847
11848    /**
11849     * Resolve all RTL related properties.
11850     *
11851     * @return true if resolution of RTL properties has been done
11852     *
11853     * @hide
11854     */
11855    public boolean resolveRtlPropertiesIfNeeded() {
11856        if (!needRtlPropertiesResolution()) return false;
11857
11858        // Order is important here: LayoutDirection MUST be resolved first
11859        if (!isLayoutDirectionResolved()) {
11860            resolveLayoutDirection();
11861            resolveLayoutParams();
11862        }
11863        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
11864        if (!isTextDirectionResolved()) {
11865            resolveTextDirection();
11866        }
11867        if (!isTextAlignmentResolved()) {
11868            resolveTextAlignment();
11869        }
11870        if (!isPaddingResolved()) {
11871            resolvePadding();
11872        }
11873        if (!isDrawablesResolved()) {
11874            resolveDrawables();
11875        }
11876        onRtlPropertiesChanged(getLayoutDirection());
11877        return true;
11878    }
11879
11880    /**
11881     * Reset resolution of all RTL related properties.
11882     *
11883     * @hide
11884     */
11885    public void resetRtlProperties() {
11886        resetResolvedLayoutDirection();
11887        resetResolvedTextDirection();
11888        resetResolvedTextAlignment();
11889        resetResolvedPadding();
11890        resetResolvedDrawables();
11891    }
11892
11893    /**
11894     * @see #onScreenStateChanged(int)
11895     */
11896    void dispatchScreenStateChanged(int screenState) {
11897        onScreenStateChanged(screenState);
11898    }
11899
11900    /**
11901     * This method is called whenever the state of the screen this view is
11902     * attached to changes. A state change will usually occurs when the screen
11903     * turns on or off (whether it happens automatically or the user does it
11904     * manually.)
11905     *
11906     * @param screenState The new state of the screen. Can be either
11907     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
11908     */
11909    public void onScreenStateChanged(int screenState) {
11910    }
11911
11912    /**
11913     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
11914     */
11915    private boolean hasRtlSupport() {
11916        return mContext.getApplicationInfo().hasRtlSupport();
11917    }
11918
11919    /**
11920     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
11921     * RTL not supported)
11922     */
11923    private boolean isRtlCompatibilityMode() {
11924        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
11925        return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport();
11926    }
11927
11928    /**
11929     * @return true if RTL properties need resolution.
11930     *
11931     */
11932    private boolean needRtlPropertiesResolution() {
11933        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
11934    }
11935
11936    /**
11937     * Called when any RTL property (layout direction or text direction or text alignment) has
11938     * been changed.
11939     *
11940     * Subclasses need to override this method to take care of cached information that depends on the
11941     * resolved layout direction, or to inform child views that inherit their layout direction.
11942     *
11943     * The default implementation does nothing.
11944     *
11945     * @param layoutDirection the direction of the layout
11946     *
11947     * @see #LAYOUT_DIRECTION_LTR
11948     * @see #LAYOUT_DIRECTION_RTL
11949     */
11950    public void onRtlPropertiesChanged(int layoutDirection) {
11951    }
11952
11953    /**
11954     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
11955     * that the parent directionality can and will be resolved before its children.
11956     *
11957     * @return true if resolution has been done, false otherwise.
11958     *
11959     * @hide
11960     */
11961    public boolean resolveLayoutDirection() {
11962        // Clear any previous layout direction resolution
11963        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
11964
11965        if (hasRtlSupport()) {
11966            // Set resolved depending on layout direction
11967            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
11968                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
11969                case LAYOUT_DIRECTION_INHERIT:
11970                    // We cannot resolve yet. LTR is by default and let the resolution happen again
11971                    // later to get the correct resolved value
11972                    if (!canResolveLayoutDirection()) return false;
11973
11974                    // Parent has not yet resolved, LTR is still the default
11975                    try {
11976                        if (!mParent.isLayoutDirectionResolved()) return false;
11977
11978                        if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
11979                            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
11980                        }
11981                    } catch (AbstractMethodError e) {
11982                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
11983                                " does not fully implement ViewParent", e);
11984                    }
11985                    break;
11986                case LAYOUT_DIRECTION_RTL:
11987                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
11988                    break;
11989                case LAYOUT_DIRECTION_LOCALE:
11990                    if((LAYOUT_DIRECTION_RTL ==
11991                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
11992                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
11993                    }
11994                    break;
11995                default:
11996                    // Nothing to do, LTR by default
11997            }
11998        }
11999
12000        // Set to resolved
12001        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
12002        return true;
12003    }
12004
12005    /**
12006     * Check if layout direction resolution can be done.
12007     *
12008     * @return true if layout direction resolution can be done otherwise return false.
12009     */
12010    public boolean canResolveLayoutDirection() {
12011        switch (getRawLayoutDirection()) {
12012            case LAYOUT_DIRECTION_INHERIT:
12013                if (mParent != null) {
12014                    try {
12015                        return mParent.canResolveLayoutDirection();
12016                    } catch (AbstractMethodError e) {
12017                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
12018                                " does not fully implement ViewParent", e);
12019                    }
12020                }
12021                return false;
12022
12023            default:
12024                return true;
12025        }
12026    }
12027
12028    /**
12029     * Reset the resolved layout direction. Layout direction will be resolved during a call to
12030     * {@link #onMeasure(int, int)}.
12031     *
12032     * @hide
12033     */
12034    public void resetResolvedLayoutDirection() {
12035        // Reset the current resolved bits
12036        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
12037    }
12038
12039    /**
12040     * @return true if the layout direction is inherited.
12041     *
12042     * @hide
12043     */
12044    public boolean isLayoutDirectionInherited() {
12045        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
12046    }
12047
12048    /**
12049     * @return true if layout direction has been resolved.
12050     */
12051    public boolean isLayoutDirectionResolved() {
12052        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
12053    }
12054
12055    /**
12056     * Return if padding has been resolved
12057     *
12058     * @hide
12059     */
12060    boolean isPaddingResolved() {
12061        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
12062    }
12063
12064    /**
12065     * Resolve padding depending on layout direction.
12066     *
12067     * @hide
12068     */
12069    public void resolvePadding() {
12070        if (!isRtlCompatibilityMode()) {
12071            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
12072            // If start / end padding are defined, they will be resolved (hence overriding) to
12073            // left / right or right / left depending on the resolved layout direction.
12074            // If start / end padding are not defined, use the left / right ones.
12075            int resolvedLayoutDirection = getLayoutDirection();
12076            switch (resolvedLayoutDirection) {
12077                case LAYOUT_DIRECTION_RTL:
12078                    if (mUserPaddingStart != UNDEFINED_PADDING) {
12079                        mUserPaddingRight = mUserPaddingStart;
12080                    } else {
12081                        mUserPaddingRight = mUserPaddingRightInitial;
12082                    }
12083                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
12084                        mUserPaddingLeft = mUserPaddingEnd;
12085                    } else {
12086                        mUserPaddingLeft = mUserPaddingLeftInitial;
12087                    }
12088                    break;
12089                case LAYOUT_DIRECTION_LTR:
12090                default:
12091                    if (mUserPaddingStart != UNDEFINED_PADDING) {
12092                        mUserPaddingLeft = mUserPaddingStart;
12093                    } else {
12094                        mUserPaddingLeft = mUserPaddingLeftInitial;
12095                    }
12096                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
12097                        mUserPaddingRight = mUserPaddingEnd;
12098                    } else {
12099                        mUserPaddingRight = mUserPaddingRightInitial;
12100                    }
12101            }
12102
12103            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
12104
12105            internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight,
12106                    mUserPaddingBottom);
12107            onRtlPropertiesChanged(resolvedLayoutDirection);
12108        }
12109
12110        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
12111    }
12112
12113    /**
12114     * Reset the resolved layout direction.
12115     *
12116     * @hide
12117     */
12118    public void resetResolvedPadding() {
12119        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
12120    }
12121
12122    /**
12123     * This is called when the view is detached from a window.  At this point it
12124     * no longer has a surface for drawing.
12125     *
12126     * @see #onAttachedToWindow()
12127     */
12128    protected void onDetachedFromWindow() {
12129        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
12130        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
12131
12132        removeUnsetPressCallback();
12133        removeLongPressCallback();
12134        removePerformClickCallback();
12135        removeSendViewScrolledAccessibilityEventCallback();
12136
12137        destroyDrawingCache();
12138
12139        destroyLayer(false);
12140
12141        cleanupDraw();
12142
12143        mCurrentAnimation = null;
12144        mCurrentScene = null;
12145    }
12146
12147    private void cleanupDraw() {
12148        if (mAttachInfo != null) {
12149            if (mDisplayList != null) {
12150                mDisplayList.markDirty();
12151                mAttachInfo.mViewRootImpl.enqueueDisplayList(mDisplayList);
12152            }
12153            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
12154        } else {
12155            // Should never happen
12156            clearDisplayList();
12157        }
12158    }
12159
12160    void invalidateInheritedLayoutMode(int layoutModeOfRoot) {
12161    }
12162
12163    /**
12164     * @return The number of times this view has been attached to a window
12165     */
12166    protected int getWindowAttachCount() {
12167        return mWindowAttachCount;
12168    }
12169
12170    /**
12171     * Retrieve a unique token identifying the window this view is attached to.
12172     * @return Return the window's token for use in
12173     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
12174     */
12175    public IBinder getWindowToken() {
12176        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
12177    }
12178
12179    /**
12180     * Retrieve the {@link WindowId} for the window this view is
12181     * currently attached to.
12182     */
12183    public WindowId getWindowId() {
12184        if (mAttachInfo == null) {
12185            return null;
12186        }
12187        if (mAttachInfo.mWindowId == null) {
12188            try {
12189                mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId(
12190                        mAttachInfo.mWindowToken);
12191                mAttachInfo.mWindowId = new WindowId(
12192                        mAttachInfo.mIWindowId);
12193            } catch (RemoteException e) {
12194            }
12195        }
12196        return mAttachInfo.mWindowId;
12197    }
12198
12199    /**
12200     * Retrieve a unique token identifying the top-level "real" window of
12201     * the window that this view is attached to.  That is, this is like
12202     * {@link #getWindowToken}, except if the window this view in is a panel
12203     * window (attached to another containing window), then the token of
12204     * the containing window is returned instead.
12205     *
12206     * @return Returns the associated window token, either
12207     * {@link #getWindowToken()} or the containing window's token.
12208     */
12209    public IBinder getApplicationWindowToken() {
12210        AttachInfo ai = mAttachInfo;
12211        if (ai != null) {
12212            IBinder appWindowToken = ai.mPanelParentWindowToken;
12213            if (appWindowToken == null) {
12214                appWindowToken = ai.mWindowToken;
12215            }
12216            return appWindowToken;
12217        }
12218        return null;
12219    }
12220
12221    /**
12222     * Gets the logical display to which the view's window has been attached.
12223     *
12224     * @return The logical display, or null if the view is not currently attached to a window.
12225     */
12226    public Display getDisplay() {
12227        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
12228    }
12229
12230    /**
12231     * Retrieve private session object this view hierarchy is using to
12232     * communicate with the window manager.
12233     * @return the session object to communicate with the window manager
12234     */
12235    /*package*/ IWindowSession getWindowSession() {
12236        return mAttachInfo != null ? mAttachInfo.mSession : null;
12237    }
12238
12239    /**
12240     * @param info the {@link android.view.View.AttachInfo} to associated with
12241     *        this view
12242     */
12243    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
12244        //System.out.println("Attached! " + this);
12245        mAttachInfo = info;
12246        if (mOverlay != null) {
12247            mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
12248        }
12249        mWindowAttachCount++;
12250        // We will need to evaluate the drawable state at least once.
12251        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
12252        if (mFloatingTreeObserver != null) {
12253            info.mTreeObserver.merge(mFloatingTreeObserver);
12254            mFloatingTreeObserver = null;
12255        }
12256        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
12257            mAttachInfo.mScrollContainers.add(this);
12258            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
12259        }
12260        performCollectViewAttributes(mAttachInfo, visibility);
12261        onAttachedToWindow();
12262
12263        ListenerInfo li = mListenerInfo;
12264        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
12265                li != null ? li.mOnAttachStateChangeListeners : null;
12266        if (listeners != null && listeners.size() > 0) {
12267            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
12268            // perform the dispatching. The iterator is a safe guard against listeners that
12269            // could mutate the list by calling the various add/remove methods. This prevents
12270            // the array from being modified while we iterate it.
12271            for (OnAttachStateChangeListener listener : listeners) {
12272                listener.onViewAttachedToWindow(this);
12273            }
12274        }
12275
12276        int vis = info.mWindowVisibility;
12277        if (vis != GONE) {
12278            onWindowVisibilityChanged(vis);
12279        }
12280        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
12281            // If nobody has evaluated the drawable state yet, then do it now.
12282            refreshDrawableState();
12283        }
12284        needGlobalAttributesUpdate(false);
12285    }
12286
12287    void dispatchDetachedFromWindow() {
12288        AttachInfo info = mAttachInfo;
12289        if (info != null) {
12290            int vis = info.mWindowVisibility;
12291            if (vis != GONE) {
12292                onWindowVisibilityChanged(GONE);
12293            }
12294        }
12295
12296        onDetachedFromWindow();
12297
12298        ListenerInfo li = mListenerInfo;
12299        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
12300                li != null ? li.mOnAttachStateChangeListeners : null;
12301        if (listeners != null && listeners.size() > 0) {
12302            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
12303            // perform the dispatching. The iterator is a safe guard against listeners that
12304            // could mutate the list by calling the various add/remove methods. This prevents
12305            // the array from being modified while we iterate it.
12306            for (OnAttachStateChangeListener listener : listeners) {
12307                listener.onViewDetachedFromWindow(this);
12308            }
12309        }
12310
12311        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
12312            mAttachInfo.mScrollContainers.remove(this);
12313            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
12314        }
12315
12316        mAttachInfo = null;
12317        if (mOverlay != null) {
12318            mOverlay.getOverlayView().dispatchDetachedFromWindow();
12319        }
12320    }
12321
12322    /**
12323     * Store this view hierarchy's frozen state into the given container.
12324     *
12325     * @param container The SparseArray in which to save the view's state.
12326     *
12327     * @see #restoreHierarchyState(android.util.SparseArray)
12328     * @see #dispatchSaveInstanceState(android.util.SparseArray)
12329     * @see #onSaveInstanceState()
12330     */
12331    public void saveHierarchyState(SparseArray<Parcelable> container) {
12332        dispatchSaveInstanceState(container);
12333    }
12334
12335    /**
12336     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
12337     * this view and its children. May be overridden to modify how freezing happens to a
12338     * view's children; for example, some views may want to not store state for their children.
12339     *
12340     * @param container The SparseArray in which to save the view's state.
12341     *
12342     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
12343     * @see #saveHierarchyState(android.util.SparseArray)
12344     * @see #onSaveInstanceState()
12345     */
12346    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
12347        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
12348            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
12349            Parcelable state = onSaveInstanceState();
12350            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
12351                throw new IllegalStateException(
12352                        "Derived class did not call super.onSaveInstanceState()");
12353            }
12354            if (state != null) {
12355                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
12356                // + ": " + state);
12357                container.put(mID, state);
12358            }
12359        }
12360    }
12361
12362    /**
12363     * Hook allowing a view to generate a representation of its internal state
12364     * that can later be used to create a new instance with that same state.
12365     * This state should only contain information that is not persistent or can
12366     * not be reconstructed later. For example, you will never store your
12367     * current position on screen because that will be computed again when a
12368     * new instance of the view is placed in its view hierarchy.
12369     * <p>
12370     * Some examples of things you may store here: the current cursor position
12371     * in a text view (but usually not the text itself since that is stored in a
12372     * content provider or other persistent storage), the currently selected
12373     * item in a list view.
12374     *
12375     * @return Returns a Parcelable object containing the view's current dynamic
12376     *         state, or null if there is nothing interesting to save. The
12377     *         default implementation returns null.
12378     * @see #onRestoreInstanceState(android.os.Parcelable)
12379     * @see #saveHierarchyState(android.util.SparseArray)
12380     * @see #dispatchSaveInstanceState(android.util.SparseArray)
12381     * @see #setSaveEnabled(boolean)
12382     */
12383    protected Parcelable onSaveInstanceState() {
12384        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
12385        return BaseSavedState.EMPTY_STATE;
12386    }
12387
12388    /**
12389     * Restore this view hierarchy's frozen state from the given container.
12390     *
12391     * @param container The SparseArray which holds previously frozen states.
12392     *
12393     * @see #saveHierarchyState(android.util.SparseArray)
12394     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
12395     * @see #onRestoreInstanceState(android.os.Parcelable)
12396     */
12397    public void restoreHierarchyState(SparseArray<Parcelable> container) {
12398        dispatchRestoreInstanceState(container);
12399    }
12400
12401    /**
12402     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
12403     * state for this view and its children. May be overridden to modify how restoring
12404     * happens to a view's children; for example, some views may want to not store state
12405     * for their children.
12406     *
12407     * @param container The SparseArray which holds previously saved state.
12408     *
12409     * @see #dispatchSaveInstanceState(android.util.SparseArray)
12410     * @see #restoreHierarchyState(android.util.SparseArray)
12411     * @see #onRestoreInstanceState(android.os.Parcelable)
12412     */
12413    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
12414        if (mID != NO_ID) {
12415            Parcelable state = container.get(mID);
12416            if (state != null) {
12417                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
12418                // + ": " + state);
12419                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
12420                onRestoreInstanceState(state);
12421                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
12422                    throw new IllegalStateException(
12423                            "Derived class did not call super.onRestoreInstanceState()");
12424                }
12425            }
12426        }
12427    }
12428
12429    /**
12430     * Hook allowing a view to re-apply a representation of its internal state that had previously
12431     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
12432     * null state.
12433     *
12434     * @param state The frozen state that had previously been returned by
12435     *        {@link #onSaveInstanceState}.
12436     *
12437     * @see #onSaveInstanceState()
12438     * @see #restoreHierarchyState(android.util.SparseArray)
12439     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
12440     */
12441    protected void onRestoreInstanceState(Parcelable state) {
12442        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
12443        if (state != BaseSavedState.EMPTY_STATE && state != null) {
12444            throw new IllegalArgumentException("Wrong state class, expecting View State but "
12445                    + "received " + state.getClass().toString() + " instead. This usually happens "
12446                    + "when two views of different type have the same id in the same hierarchy. "
12447                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
12448                    + "other views do not use the same id.");
12449        }
12450    }
12451
12452    /**
12453     * <p>Return the time at which the drawing of the view hierarchy started.</p>
12454     *
12455     * @return the drawing start time in milliseconds
12456     */
12457    public long getDrawingTime() {
12458        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
12459    }
12460
12461    /**
12462     * <p>Enables or disables the duplication of the parent's state into this view. When
12463     * duplication is enabled, this view gets its drawable state from its parent rather
12464     * than from its own internal properties.</p>
12465     *
12466     * <p>Note: in the current implementation, setting this property to true after the
12467     * view was added to a ViewGroup might have no effect at all. This property should
12468     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
12469     *
12470     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
12471     * property is enabled, an exception will be thrown.</p>
12472     *
12473     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
12474     * parent, these states should not be affected by this method.</p>
12475     *
12476     * @param enabled True to enable duplication of the parent's drawable state, false
12477     *                to disable it.
12478     *
12479     * @see #getDrawableState()
12480     * @see #isDuplicateParentStateEnabled()
12481     */
12482    public void setDuplicateParentStateEnabled(boolean enabled) {
12483        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
12484    }
12485
12486    /**
12487     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
12488     *
12489     * @return True if this view's drawable state is duplicated from the parent,
12490     *         false otherwise
12491     *
12492     * @see #getDrawableState()
12493     * @see #setDuplicateParentStateEnabled(boolean)
12494     */
12495    public boolean isDuplicateParentStateEnabled() {
12496        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
12497    }
12498
12499    /**
12500     * <p>Specifies the type of layer backing this view. The layer can be
12501     * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
12502     * {@link #LAYER_TYPE_HARDWARE}.</p>
12503     *
12504     * <p>A layer is associated with an optional {@link android.graphics.Paint}
12505     * instance that controls how the layer is composed on screen. The following
12506     * properties of the paint are taken into account when composing the layer:</p>
12507     * <ul>
12508     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
12509     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
12510     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
12511     * </ul>
12512     *
12513     * <p>If this view has an alpha value set to < 1.0 by calling
12514     * {@link #setAlpha(float)}, the alpha value of the layer's paint is superceded
12515     * by this view's alpha value.</p>
12516     *
12517     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE},
12518     * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE}
12519     * for more information on when and how to use layers.</p>
12520     *
12521     * @param layerType The type of layer to use with this view, must be one of
12522     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
12523     *        {@link #LAYER_TYPE_HARDWARE}
12524     * @param paint The paint used to compose the layer. This argument is optional
12525     *        and can be null. It is ignored when the layer type is
12526     *        {@link #LAYER_TYPE_NONE}
12527     *
12528     * @see #getLayerType()
12529     * @see #LAYER_TYPE_NONE
12530     * @see #LAYER_TYPE_SOFTWARE
12531     * @see #LAYER_TYPE_HARDWARE
12532     * @see #setAlpha(float)
12533     *
12534     * @attr ref android.R.styleable#View_layerType
12535     */
12536    public void setLayerType(int layerType, Paint paint) {
12537        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
12538            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
12539                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
12540        }
12541
12542        if (layerType == mLayerType) {
12543            if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) {
12544                mLayerPaint = paint == null ? new Paint() : paint;
12545                invalidateParentCaches();
12546                invalidate(true);
12547            }
12548            return;
12549        }
12550
12551        // Destroy any previous software drawing cache if needed
12552        switch (mLayerType) {
12553            case LAYER_TYPE_HARDWARE:
12554                destroyLayer(false);
12555                // fall through - non-accelerated views may use software layer mechanism instead
12556            case LAYER_TYPE_SOFTWARE:
12557                destroyDrawingCache();
12558                break;
12559            default:
12560                break;
12561        }
12562
12563        mLayerType = layerType;
12564        final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE;
12565        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
12566        mLocalDirtyRect = layerDisabled ? null : new Rect();
12567
12568        invalidateParentCaches();
12569        invalidate(true);
12570    }
12571
12572    /**
12573     * Updates the {@link Paint} object used with the current layer (used only if the current
12574     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
12575     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
12576     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
12577     * ensure that the view gets redrawn immediately.
12578     *
12579     * <p>A layer is associated with an optional {@link android.graphics.Paint}
12580     * instance that controls how the layer is composed on screen. The following
12581     * properties of the paint are taken into account when composing the layer:</p>
12582     * <ul>
12583     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
12584     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
12585     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
12586     * </ul>
12587     *
12588     * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the
12589     * alpha value of the layer's paint is superceded by this view's alpha value.</p>
12590     *
12591     * @param paint The paint used to compose the layer. This argument is optional
12592     *        and can be null. It is ignored when the layer type is
12593     *        {@link #LAYER_TYPE_NONE}
12594     *
12595     * @see #setLayerType(int, android.graphics.Paint)
12596     */
12597    public void setLayerPaint(Paint paint) {
12598        int layerType = getLayerType();
12599        if (layerType != LAYER_TYPE_NONE) {
12600            mLayerPaint = paint == null ? new Paint() : paint;
12601            if (layerType == LAYER_TYPE_HARDWARE) {
12602                HardwareLayer layer = getHardwareLayer();
12603                if (layer != null) {
12604                    layer.setLayerPaint(paint);
12605                }
12606                invalidateViewProperty(false, false);
12607            } else {
12608                invalidate();
12609            }
12610        }
12611    }
12612
12613    /**
12614     * Indicates whether this view has a static layer. A view with layer type
12615     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
12616     * dynamic.
12617     */
12618    boolean hasStaticLayer() {
12619        return true;
12620    }
12621
12622    /**
12623     * Indicates what type of layer is currently associated with this view. By default
12624     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
12625     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
12626     * for more information on the different types of layers.
12627     *
12628     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
12629     *         {@link #LAYER_TYPE_HARDWARE}
12630     *
12631     * @see #setLayerType(int, android.graphics.Paint)
12632     * @see #buildLayer()
12633     * @see #LAYER_TYPE_NONE
12634     * @see #LAYER_TYPE_SOFTWARE
12635     * @see #LAYER_TYPE_HARDWARE
12636     */
12637    public int getLayerType() {
12638        return mLayerType;
12639    }
12640
12641    /**
12642     * Forces this view's layer to be created and this view to be rendered
12643     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
12644     * invoking this method will have no effect.
12645     *
12646     * This method can for instance be used to render a view into its layer before
12647     * starting an animation. If this view is complex, rendering into the layer
12648     * before starting the animation will avoid skipping frames.
12649     *
12650     * @throws IllegalStateException If this view is not attached to a window
12651     *
12652     * @see #setLayerType(int, android.graphics.Paint)
12653     */
12654    public void buildLayer() {
12655        if (mLayerType == LAYER_TYPE_NONE) return;
12656
12657        final AttachInfo attachInfo = mAttachInfo;
12658        if (attachInfo == null) {
12659            throw new IllegalStateException("This view must be attached to a window first");
12660        }
12661
12662        switch (mLayerType) {
12663            case LAYER_TYPE_HARDWARE:
12664                if (attachInfo.mHardwareRenderer != null &&
12665                        attachInfo.mHardwareRenderer.isEnabled() &&
12666                        attachInfo.mHardwareRenderer.validate()) {
12667                    getHardwareLayer();
12668                    // TODO: We need a better way to handle this case
12669                    // If views have registered pre-draw listeners they need
12670                    // to be notified before we build the layer. Those listeners
12671                    // may however rely on other events to happen first so we
12672                    // cannot just invoke them here until they don't cancel the
12673                    // current frame
12674                    if (!attachInfo.mTreeObserver.hasOnPreDrawListeners()) {
12675                        attachInfo.mViewRootImpl.dispatchFlushHardwareLayerUpdates();
12676                    }
12677                }
12678                break;
12679            case LAYER_TYPE_SOFTWARE:
12680                buildDrawingCache(true);
12681                break;
12682        }
12683    }
12684
12685    /**
12686     * <p>Returns a hardware layer that can be used to draw this view again
12687     * without executing its draw method.</p>
12688     *
12689     * @return A HardwareLayer ready to render, or null if an error occurred.
12690     */
12691    HardwareLayer getHardwareLayer() {
12692        if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null ||
12693                !mAttachInfo.mHardwareRenderer.isEnabled()) {
12694            return null;
12695        }
12696
12697        if (!mAttachInfo.mHardwareRenderer.validate()) return null;
12698
12699        final int width = mRight - mLeft;
12700        final int height = mBottom - mTop;
12701
12702        if (width == 0 || height == 0) {
12703            return null;
12704        }
12705
12706        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
12707            if (mHardwareLayer == null) {
12708                mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
12709                        width, height, isOpaque());
12710                mLocalDirtyRect.set(0, 0, width, height);
12711            } else {
12712                if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) {
12713                    if (mHardwareLayer.resize(width, height)) {
12714                        mLocalDirtyRect.set(0, 0, width, height);
12715                    }
12716                }
12717
12718                // This should not be necessary but applications that change
12719                // the parameters of their background drawable without calling
12720                // this.setBackground(Drawable) can leave the view in a bad state
12721                // (for instance isOpaque() returns true, but the background is
12722                // not opaque.)
12723                computeOpaqueFlags();
12724
12725                final boolean opaque = isOpaque();
12726                if (mHardwareLayer.isValid() && mHardwareLayer.isOpaque() != opaque) {
12727                    mHardwareLayer.setOpaque(opaque);
12728                    mLocalDirtyRect.set(0, 0, width, height);
12729                }
12730            }
12731
12732            // The layer is not valid if the underlying GPU resources cannot be allocated
12733            if (!mHardwareLayer.isValid()) {
12734                return null;
12735            }
12736
12737            mHardwareLayer.setLayerPaint(mLayerPaint);
12738            mHardwareLayer.redrawLater(getHardwareLayerDisplayList(mHardwareLayer), mLocalDirtyRect);
12739            ViewRootImpl viewRoot = getViewRootImpl();
12740            if (viewRoot != null) viewRoot.pushHardwareLayerUpdate(mHardwareLayer);
12741
12742            mLocalDirtyRect.setEmpty();
12743        }
12744
12745        return mHardwareLayer;
12746    }
12747
12748    /**
12749     * Destroys this View's hardware layer if possible.
12750     *
12751     * @return True if the layer was destroyed, false otherwise.
12752     *
12753     * @see #setLayerType(int, android.graphics.Paint)
12754     * @see #LAYER_TYPE_HARDWARE
12755     */
12756    boolean destroyLayer(boolean valid) {
12757        if (mHardwareLayer != null) {
12758            AttachInfo info = mAttachInfo;
12759            if (info != null && info.mHardwareRenderer != null &&
12760                    info.mHardwareRenderer.isEnabled() &&
12761                    (valid || info.mHardwareRenderer.validate())) {
12762
12763                info.mHardwareRenderer.cancelLayerUpdate(mHardwareLayer);
12764                mHardwareLayer.destroy();
12765                mHardwareLayer = null;
12766
12767                if (mDisplayList != null) {
12768                    mDisplayList.reset();
12769                }
12770                invalidate(true);
12771                invalidateParentCaches();
12772            }
12773            return true;
12774        }
12775        return false;
12776    }
12777
12778    /**
12779     * Destroys all hardware rendering resources. This method is invoked
12780     * when the system needs to reclaim resources. Upon execution of this
12781     * method, you should free any OpenGL resources created by the view.
12782     *
12783     * Note: you <strong>must</strong> call
12784     * <code>super.destroyHardwareResources()</code> when overriding
12785     * this method.
12786     *
12787     * @hide
12788     */
12789    protected void destroyHardwareResources() {
12790        clearDisplayList();
12791        destroyLayer(true);
12792    }
12793
12794    /**
12795     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
12796     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
12797     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
12798     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
12799     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
12800     * null.</p>
12801     *
12802     * <p>Enabling the drawing cache is similar to
12803     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
12804     * acceleration is turned off. When hardware acceleration is turned on, enabling the
12805     * drawing cache has no effect on rendering because the system uses a different mechanism
12806     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
12807     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
12808     * for information on how to enable software and hardware layers.</p>
12809     *
12810     * <p>This API can be used to manually generate
12811     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
12812     * {@link #getDrawingCache()}.</p>
12813     *
12814     * @param enabled true to enable the drawing cache, false otherwise
12815     *
12816     * @see #isDrawingCacheEnabled()
12817     * @see #getDrawingCache()
12818     * @see #buildDrawingCache()
12819     * @see #setLayerType(int, android.graphics.Paint)
12820     */
12821    public void setDrawingCacheEnabled(boolean enabled) {
12822        mCachingFailed = false;
12823        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
12824    }
12825
12826    /**
12827     * <p>Indicates whether the drawing cache is enabled for this view.</p>
12828     *
12829     * @return true if the drawing cache is enabled
12830     *
12831     * @see #setDrawingCacheEnabled(boolean)
12832     * @see #getDrawingCache()
12833     */
12834    @ViewDebug.ExportedProperty(category = "drawing")
12835    public boolean isDrawingCacheEnabled() {
12836        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
12837    }
12838
12839    /**
12840     * Debugging utility which recursively outputs the dirty state of a view and its
12841     * descendants.
12842     *
12843     * @hide
12844     */
12845    @SuppressWarnings({"UnusedDeclaration"})
12846    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
12847        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
12848                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
12849                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
12850                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
12851        if (clear) {
12852            mPrivateFlags &= clearMask;
12853        }
12854        if (this instanceof ViewGroup) {
12855            ViewGroup parent = (ViewGroup) this;
12856            final int count = parent.getChildCount();
12857            for (int i = 0; i < count; i++) {
12858                final View child = parent.getChildAt(i);
12859                child.outputDirtyFlags(indent + "  ", clear, clearMask);
12860            }
12861        }
12862    }
12863
12864    /**
12865     * This method is used by ViewGroup to cause its children to restore or recreate their
12866     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
12867     * to recreate its own display list, which would happen if it went through the normal
12868     * draw/dispatchDraw mechanisms.
12869     *
12870     * @hide
12871     */
12872    protected void dispatchGetDisplayList() {}
12873
12874    /**
12875     * A view that is not attached or hardware accelerated cannot create a display list.
12876     * This method checks these conditions and returns the appropriate result.
12877     *
12878     * @return true if view has the ability to create a display list, false otherwise.
12879     *
12880     * @hide
12881     */
12882    public boolean canHaveDisplayList() {
12883        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
12884    }
12885
12886    /**
12887     * @return The {@link HardwareRenderer} associated with that view or null if
12888     *         hardware rendering is not supported or this view is not attached
12889     *         to a window.
12890     *
12891     * @hide
12892     */
12893    public HardwareRenderer getHardwareRenderer() {
12894        if (mAttachInfo != null) {
12895            return mAttachInfo.mHardwareRenderer;
12896        }
12897        return null;
12898    }
12899
12900    /**
12901     * Returns a DisplayList. If the incoming displayList is null, one will be created.
12902     * Otherwise, the same display list will be returned (after having been rendered into
12903     * along the way, depending on the invalidation state of the view).
12904     *
12905     * @param displayList The previous version of this displayList, could be null.
12906     * @param isLayer Whether the requester of the display list is a layer. If so,
12907     * the view will avoid creating a layer inside the resulting display list.
12908     * @return A new or reused DisplayList object.
12909     */
12910    private DisplayList getDisplayList(DisplayList displayList, boolean isLayer) {
12911        if (!canHaveDisplayList()) {
12912            return null;
12913        }
12914
12915        if (((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 ||
12916                displayList == null || !displayList.isValid() ||
12917                (!isLayer && mRecreateDisplayList))) {
12918            // Don't need to recreate the display list, just need to tell our
12919            // children to restore/recreate theirs
12920            if (displayList != null && displayList.isValid() &&
12921                    !isLayer && !mRecreateDisplayList) {
12922                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
12923                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
12924                dispatchGetDisplayList();
12925
12926                return displayList;
12927            }
12928
12929            if (!isLayer) {
12930                // If we got here, we're recreating it. Mark it as such to ensure that
12931                // we copy in child display lists into ours in drawChild()
12932                mRecreateDisplayList = true;
12933            }
12934            if (displayList == null) {
12935                displayList = mAttachInfo.mHardwareRenderer.createDisplayList(getClass().getName());
12936                // If we're creating a new display list, make sure our parent gets invalidated
12937                // since they will need to recreate their display list to account for this
12938                // new child display list.
12939                invalidateParentCaches();
12940            }
12941
12942            boolean caching = false;
12943            int width = mRight - mLeft;
12944            int height = mBottom - mTop;
12945            int layerType = getLayerType();
12946
12947            final HardwareCanvas canvas = displayList.start(width, height);
12948
12949            try {
12950                if (!isLayer && layerType != LAYER_TYPE_NONE) {
12951                    if (layerType == LAYER_TYPE_HARDWARE) {
12952                        final HardwareLayer layer = getHardwareLayer();
12953                        if (layer != null && layer.isValid()) {
12954                            canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
12955                        } else {
12956                            canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint,
12957                                    Canvas.HAS_ALPHA_LAYER_SAVE_FLAG |
12958                                            Canvas.CLIP_TO_LAYER_SAVE_FLAG);
12959                        }
12960                        caching = true;
12961                    } else {
12962                        buildDrawingCache(true);
12963                        Bitmap cache = getDrawingCache(true);
12964                        if (cache != null) {
12965                            canvas.drawBitmap(cache, 0, 0, mLayerPaint);
12966                            caching = true;
12967                        }
12968                    }
12969                } else {
12970
12971                    computeScroll();
12972
12973                    canvas.translate(-mScrollX, -mScrollY);
12974                    if (!isLayer) {
12975                        mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
12976                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
12977                    }
12978
12979                    // Fast path for layouts with no backgrounds
12980                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
12981                        dispatchDraw(canvas);
12982                        if (mOverlay != null && !mOverlay.isEmpty()) {
12983                            mOverlay.getOverlayView().draw(canvas);
12984                        }
12985                    } else {
12986                        draw(canvas);
12987                    }
12988                }
12989            } finally {
12990                displayList.end();
12991                displayList.setCaching(caching);
12992                if (isLayer) {
12993                    displayList.setLeftTopRightBottom(0, 0, width, height);
12994                } else {
12995                    setDisplayListProperties(displayList);
12996                }
12997            }
12998        } else if (!isLayer) {
12999            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13000            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13001        }
13002
13003        return displayList;
13004    }
13005
13006    /**
13007     * Get the DisplayList for the HardwareLayer
13008     *
13009     * @param layer The HardwareLayer whose DisplayList we want
13010     * @return A DisplayList fopr the specified HardwareLayer
13011     */
13012    private DisplayList getHardwareLayerDisplayList(HardwareLayer layer) {
13013        DisplayList displayList = getDisplayList(layer.getDisplayList(), true);
13014        layer.setDisplayList(displayList);
13015        return displayList;
13016    }
13017
13018
13019    /**
13020     * <p>Returns a display list that can be used to draw this view again
13021     * without executing its draw method.</p>
13022     *
13023     * @return A DisplayList ready to replay, or null if caching is not enabled.
13024     *
13025     * @hide
13026     */
13027    public DisplayList getDisplayList() {
13028        mDisplayList = getDisplayList(mDisplayList, false);
13029        return mDisplayList;
13030    }
13031
13032    private void clearDisplayList() {
13033        if (mDisplayList != null) {
13034            mDisplayList.clear();
13035        }
13036    }
13037
13038    /**
13039     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
13040     *
13041     * @return A non-scaled bitmap representing this view or null if cache is disabled.
13042     *
13043     * @see #getDrawingCache(boolean)
13044     */
13045    public Bitmap getDrawingCache() {
13046        return getDrawingCache(false);
13047    }
13048
13049    /**
13050     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
13051     * is null when caching is disabled. If caching is enabled and the cache is not ready,
13052     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
13053     * draw from the cache when the cache is enabled. To benefit from the cache, you must
13054     * request the drawing cache by calling this method and draw it on screen if the
13055     * returned bitmap is not null.</p>
13056     *
13057     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
13058     * this method will create a bitmap of the same size as this view. Because this bitmap
13059     * will be drawn scaled by the parent ViewGroup, the result on screen might show
13060     * scaling artifacts. To avoid such artifacts, you should call this method by setting
13061     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
13062     * size than the view. This implies that your application must be able to handle this
13063     * size.</p>
13064     *
13065     * @param autoScale Indicates whether the generated bitmap should be scaled based on
13066     *        the current density of the screen when the application is in compatibility
13067     *        mode.
13068     *
13069     * @return A bitmap representing this view or null if cache is disabled.
13070     *
13071     * @see #setDrawingCacheEnabled(boolean)
13072     * @see #isDrawingCacheEnabled()
13073     * @see #buildDrawingCache(boolean)
13074     * @see #destroyDrawingCache()
13075     */
13076    public Bitmap getDrawingCache(boolean autoScale) {
13077        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
13078            return null;
13079        }
13080        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
13081            buildDrawingCache(autoScale);
13082        }
13083        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
13084    }
13085
13086    /**
13087     * <p>Frees the resources used by the drawing cache. If you call
13088     * {@link #buildDrawingCache()} manually without calling
13089     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
13090     * should cleanup the cache with this method afterwards.</p>
13091     *
13092     * @see #setDrawingCacheEnabled(boolean)
13093     * @see #buildDrawingCache()
13094     * @see #getDrawingCache()
13095     */
13096    public void destroyDrawingCache() {
13097        if (mDrawingCache != null) {
13098            mDrawingCache.recycle();
13099            mDrawingCache = null;
13100        }
13101        if (mUnscaledDrawingCache != null) {
13102            mUnscaledDrawingCache.recycle();
13103            mUnscaledDrawingCache = null;
13104        }
13105    }
13106
13107    /**
13108     * Setting a solid background color for the drawing cache's bitmaps will improve
13109     * performance and memory usage. Note, though that this should only be used if this
13110     * view will always be drawn on top of a solid color.
13111     *
13112     * @param color The background color to use for the drawing cache's bitmap
13113     *
13114     * @see #setDrawingCacheEnabled(boolean)
13115     * @see #buildDrawingCache()
13116     * @see #getDrawingCache()
13117     */
13118    public void setDrawingCacheBackgroundColor(int color) {
13119        if (color != mDrawingCacheBackgroundColor) {
13120            mDrawingCacheBackgroundColor = color;
13121            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
13122        }
13123    }
13124
13125    /**
13126     * @see #setDrawingCacheBackgroundColor(int)
13127     *
13128     * @return The background color to used for the drawing cache's bitmap
13129     */
13130    public int getDrawingCacheBackgroundColor() {
13131        return mDrawingCacheBackgroundColor;
13132    }
13133
13134    /**
13135     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
13136     *
13137     * @see #buildDrawingCache(boolean)
13138     */
13139    public void buildDrawingCache() {
13140        buildDrawingCache(false);
13141    }
13142
13143    /**
13144     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
13145     *
13146     * <p>If you call {@link #buildDrawingCache()} manually without calling
13147     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
13148     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
13149     *
13150     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
13151     * this method will create a bitmap of the same size as this view. Because this bitmap
13152     * will be drawn scaled by the parent ViewGroup, the result on screen might show
13153     * scaling artifacts. To avoid such artifacts, you should call this method by setting
13154     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
13155     * size than the view. This implies that your application must be able to handle this
13156     * size.</p>
13157     *
13158     * <p>You should avoid calling this method when hardware acceleration is enabled. If
13159     * you do not need the drawing cache bitmap, calling this method will increase memory
13160     * usage and cause the view to be rendered in software once, thus negatively impacting
13161     * performance.</p>
13162     *
13163     * @see #getDrawingCache()
13164     * @see #destroyDrawingCache()
13165     */
13166    public void buildDrawingCache(boolean autoScale) {
13167        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
13168                mDrawingCache == null : mUnscaledDrawingCache == null)) {
13169            mCachingFailed = false;
13170
13171            int width = mRight - mLeft;
13172            int height = mBottom - mTop;
13173
13174            final AttachInfo attachInfo = mAttachInfo;
13175            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
13176
13177            if (autoScale && scalingRequired) {
13178                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
13179                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
13180            }
13181
13182            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
13183            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
13184            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
13185
13186            final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
13187            final long drawingCacheSize =
13188                    ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
13189            if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
13190                if (width > 0 && height > 0) {
13191                    Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs "
13192                            + projectedBitmapSize + " bytes, only "
13193                            + drawingCacheSize + " available");
13194                }
13195                destroyDrawingCache();
13196                mCachingFailed = true;
13197                return;
13198            }
13199
13200            boolean clear = true;
13201            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
13202
13203            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
13204                Bitmap.Config quality;
13205                if (!opaque) {
13206                    // Never pick ARGB_4444 because it looks awful
13207                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
13208                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
13209                        case DRAWING_CACHE_QUALITY_AUTO:
13210                            quality = Bitmap.Config.ARGB_8888;
13211                            break;
13212                        case DRAWING_CACHE_QUALITY_LOW:
13213                            quality = Bitmap.Config.ARGB_8888;
13214                            break;
13215                        case DRAWING_CACHE_QUALITY_HIGH:
13216                            quality = Bitmap.Config.ARGB_8888;
13217                            break;
13218                        default:
13219                            quality = Bitmap.Config.ARGB_8888;
13220                            break;
13221                    }
13222                } else {
13223                    // Optimization for translucent windows
13224                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
13225                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
13226                }
13227
13228                // Try to cleanup memory
13229                if (bitmap != null) bitmap.recycle();
13230
13231                try {
13232                    bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
13233                            width, height, quality);
13234                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
13235                    if (autoScale) {
13236                        mDrawingCache = bitmap;
13237                    } else {
13238                        mUnscaledDrawingCache = bitmap;
13239                    }
13240                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
13241                } catch (OutOfMemoryError e) {
13242                    // If there is not enough memory to create the bitmap cache, just
13243                    // ignore the issue as bitmap caches are not required to draw the
13244                    // view hierarchy
13245                    if (autoScale) {
13246                        mDrawingCache = null;
13247                    } else {
13248                        mUnscaledDrawingCache = null;
13249                    }
13250                    mCachingFailed = true;
13251                    return;
13252                }
13253
13254                clear = drawingCacheBackgroundColor != 0;
13255            }
13256
13257            Canvas canvas;
13258            if (attachInfo != null) {
13259                canvas = attachInfo.mCanvas;
13260                if (canvas == null) {
13261                    canvas = new Canvas();
13262                }
13263                canvas.setBitmap(bitmap);
13264                // Temporarily clobber the cached Canvas in case one of our children
13265                // is also using a drawing cache. Without this, the children would
13266                // steal the canvas by attaching their own bitmap to it and bad, bad
13267                // thing would happen (invisible views, corrupted drawings, etc.)
13268                attachInfo.mCanvas = null;
13269            } else {
13270                // This case should hopefully never or seldom happen
13271                canvas = new Canvas(bitmap);
13272            }
13273
13274            if (clear) {
13275                bitmap.eraseColor(drawingCacheBackgroundColor);
13276            }
13277
13278            computeScroll();
13279            final int restoreCount = canvas.save();
13280
13281            if (autoScale && scalingRequired) {
13282                final float scale = attachInfo.mApplicationScale;
13283                canvas.scale(scale, scale);
13284            }
13285
13286            canvas.translate(-mScrollX, -mScrollY);
13287
13288            mPrivateFlags |= PFLAG_DRAWN;
13289            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
13290                    mLayerType != LAYER_TYPE_NONE) {
13291                mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
13292            }
13293
13294            // Fast path for layouts with no backgrounds
13295            if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13296                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13297                dispatchDraw(canvas);
13298                if (mOverlay != null && !mOverlay.isEmpty()) {
13299                    mOverlay.getOverlayView().draw(canvas);
13300                }
13301            } else {
13302                draw(canvas);
13303            }
13304
13305            canvas.restoreToCount(restoreCount);
13306            canvas.setBitmap(null);
13307
13308            if (attachInfo != null) {
13309                // Restore the cached Canvas for our siblings
13310                attachInfo.mCanvas = canvas;
13311            }
13312        }
13313    }
13314
13315    /**
13316     * Create a snapshot of the view into a bitmap.  We should probably make
13317     * some form of this public, but should think about the API.
13318     */
13319    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
13320        int width = mRight - mLeft;
13321        int height = mBottom - mTop;
13322
13323        final AttachInfo attachInfo = mAttachInfo;
13324        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
13325        width = (int) ((width * scale) + 0.5f);
13326        height = (int) ((height * scale) + 0.5f);
13327
13328        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
13329                width > 0 ? width : 1, height > 0 ? height : 1, quality);
13330        if (bitmap == null) {
13331            throw new OutOfMemoryError();
13332        }
13333
13334        Resources resources = getResources();
13335        if (resources != null) {
13336            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
13337        }
13338
13339        Canvas canvas;
13340        if (attachInfo != null) {
13341            canvas = attachInfo.mCanvas;
13342            if (canvas == null) {
13343                canvas = new Canvas();
13344            }
13345            canvas.setBitmap(bitmap);
13346            // Temporarily clobber the cached Canvas in case one of our children
13347            // is also using a drawing cache. Without this, the children would
13348            // steal the canvas by attaching their own bitmap to it and bad, bad
13349            // things would happen (invisible views, corrupted drawings, etc.)
13350            attachInfo.mCanvas = null;
13351        } else {
13352            // This case should hopefully never or seldom happen
13353            canvas = new Canvas(bitmap);
13354        }
13355
13356        if ((backgroundColor & 0xff000000) != 0) {
13357            bitmap.eraseColor(backgroundColor);
13358        }
13359
13360        computeScroll();
13361        final int restoreCount = canvas.save();
13362        canvas.scale(scale, scale);
13363        canvas.translate(-mScrollX, -mScrollY);
13364
13365        // Temporarily remove the dirty mask
13366        int flags = mPrivateFlags;
13367        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13368
13369        // Fast path for layouts with no backgrounds
13370        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13371            dispatchDraw(canvas);
13372        } else {
13373            draw(canvas);
13374        }
13375
13376        mPrivateFlags = flags;
13377
13378        canvas.restoreToCount(restoreCount);
13379        canvas.setBitmap(null);
13380
13381        if (attachInfo != null) {
13382            // Restore the cached Canvas for our siblings
13383            attachInfo.mCanvas = canvas;
13384        }
13385
13386        return bitmap;
13387    }
13388
13389    /**
13390     * Indicates whether this View is currently in edit mode. A View is usually
13391     * in edit mode when displayed within a developer tool. For instance, if
13392     * this View is being drawn by a visual user interface builder, this method
13393     * should return true.
13394     *
13395     * Subclasses should check the return value of this method to provide
13396     * different behaviors if their normal behavior might interfere with the
13397     * host environment. For instance: the class spawns a thread in its
13398     * constructor, the drawing code relies on device-specific features, etc.
13399     *
13400     * This method is usually checked in the drawing code of custom widgets.
13401     *
13402     * @return True if this View is in edit mode, false otherwise.
13403     */
13404    public boolean isInEditMode() {
13405        return false;
13406    }
13407
13408    /**
13409     * If the View draws content inside its padding and enables fading edges,
13410     * it needs to support padding offsets. Padding offsets are added to the
13411     * fading edges to extend the length of the fade so that it covers pixels
13412     * drawn inside the padding.
13413     *
13414     * Subclasses of this class should override this method if they need
13415     * to draw content inside the padding.
13416     *
13417     * @return True if padding offset must be applied, false otherwise.
13418     *
13419     * @see #getLeftPaddingOffset()
13420     * @see #getRightPaddingOffset()
13421     * @see #getTopPaddingOffset()
13422     * @see #getBottomPaddingOffset()
13423     *
13424     * @since CURRENT
13425     */
13426    protected boolean isPaddingOffsetRequired() {
13427        return false;
13428    }
13429
13430    /**
13431     * Amount by which to extend the left fading region. Called only when
13432     * {@link #isPaddingOffsetRequired()} returns true.
13433     *
13434     * @return The left padding offset in pixels.
13435     *
13436     * @see #isPaddingOffsetRequired()
13437     *
13438     * @since CURRENT
13439     */
13440    protected int getLeftPaddingOffset() {
13441        return 0;
13442    }
13443
13444    /**
13445     * Amount by which to extend the right fading region. Called only when
13446     * {@link #isPaddingOffsetRequired()} returns true.
13447     *
13448     * @return The right padding offset in pixels.
13449     *
13450     * @see #isPaddingOffsetRequired()
13451     *
13452     * @since CURRENT
13453     */
13454    protected int getRightPaddingOffset() {
13455        return 0;
13456    }
13457
13458    /**
13459     * Amount by which to extend the top fading region. Called only when
13460     * {@link #isPaddingOffsetRequired()} returns true.
13461     *
13462     * @return The top padding offset in pixels.
13463     *
13464     * @see #isPaddingOffsetRequired()
13465     *
13466     * @since CURRENT
13467     */
13468    protected int getTopPaddingOffset() {
13469        return 0;
13470    }
13471
13472    /**
13473     * Amount by which to extend the bottom fading region. Called only when
13474     * {@link #isPaddingOffsetRequired()} returns true.
13475     *
13476     * @return The bottom padding offset in pixels.
13477     *
13478     * @see #isPaddingOffsetRequired()
13479     *
13480     * @since CURRENT
13481     */
13482    protected int getBottomPaddingOffset() {
13483        return 0;
13484    }
13485
13486    /**
13487     * @hide
13488     * @param offsetRequired
13489     */
13490    protected int getFadeTop(boolean offsetRequired) {
13491        int top = mPaddingTop;
13492        if (offsetRequired) top += getTopPaddingOffset();
13493        return top;
13494    }
13495
13496    /**
13497     * @hide
13498     * @param offsetRequired
13499     */
13500    protected int getFadeHeight(boolean offsetRequired) {
13501        int padding = mPaddingTop;
13502        if (offsetRequired) padding += getTopPaddingOffset();
13503        return mBottom - mTop - mPaddingBottom - padding;
13504    }
13505
13506    /**
13507     * <p>Indicates whether this view is attached to a hardware accelerated
13508     * window or not.</p>
13509     *
13510     * <p>Even if this method returns true, it does not mean that every call
13511     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
13512     * accelerated {@link android.graphics.Canvas}. For instance, if this view
13513     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
13514     * window is hardware accelerated,
13515     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
13516     * return false, and this method will return true.</p>
13517     *
13518     * @return True if the view is attached to a window and the window is
13519     *         hardware accelerated; false in any other case.
13520     */
13521    public boolean isHardwareAccelerated() {
13522        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
13523    }
13524
13525    /**
13526     * Sets a rectangular area on this view to which the view will be clipped
13527     * when it is drawn. Setting the value to null will remove the clip bounds
13528     * and the view will draw normally, using its full bounds.
13529     *
13530     * @param clipBounds The rectangular area, in the local coordinates of
13531     * this view, to which future drawing operations will be clipped.
13532     */
13533    public void setClipBounds(Rect clipBounds) {
13534        if (clipBounds != null) {
13535            if (clipBounds.equals(mClipBounds)) {
13536                return;
13537            }
13538            if (mClipBounds == null) {
13539                invalidate();
13540                mClipBounds = new Rect(clipBounds);
13541            } else {
13542                invalidate(Math.min(mClipBounds.left, clipBounds.left),
13543                        Math.min(mClipBounds.top, clipBounds.top),
13544                        Math.max(mClipBounds.right, clipBounds.right),
13545                        Math.max(mClipBounds.bottom, clipBounds.bottom));
13546                mClipBounds.set(clipBounds);
13547            }
13548        } else {
13549            if (mClipBounds != null) {
13550                invalidate();
13551                mClipBounds = null;
13552            }
13553        }
13554    }
13555
13556    /**
13557     * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}.
13558     *
13559     * @return A copy of the current clip bounds if clip bounds are set,
13560     * otherwise null.
13561     */
13562    public Rect getClipBounds() {
13563        return (mClipBounds != null) ? new Rect(mClipBounds) : null;
13564    }
13565
13566    /**
13567     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
13568     * case of an active Animation being run on the view.
13569     */
13570    private boolean drawAnimation(ViewGroup parent, long drawingTime,
13571            Animation a, boolean scalingRequired) {
13572        Transformation invalidationTransform;
13573        final int flags = parent.mGroupFlags;
13574        final boolean initialized = a.isInitialized();
13575        if (!initialized) {
13576            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
13577            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
13578            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
13579            onAnimationStart();
13580        }
13581
13582        final Transformation t = parent.getChildTransformation();
13583        boolean more = a.getTransformation(drawingTime, t, 1f);
13584        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
13585            if (parent.mInvalidationTransformation == null) {
13586                parent.mInvalidationTransformation = new Transformation();
13587            }
13588            invalidationTransform = parent.mInvalidationTransformation;
13589            a.getTransformation(drawingTime, invalidationTransform, 1f);
13590        } else {
13591            invalidationTransform = t;
13592        }
13593
13594        if (more) {
13595            if (!a.willChangeBounds()) {
13596                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
13597                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
13598                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
13599                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
13600                    // The child need to draw an animation, potentially offscreen, so
13601                    // make sure we do not cancel invalidate requests
13602                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
13603                    parent.invalidate(mLeft, mTop, mRight, mBottom);
13604                }
13605            } else {
13606                if (parent.mInvalidateRegion == null) {
13607                    parent.mInvalidateRegion = new RectF();
13608                }
13609                final RectF region = parent.mInvalidateRegion;
13610                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
13611                        invalidationTransform);
13612
13613                // The child need to draw an animation, potentially offscreen, so
13614                // make sure we do not cancel invalidate requests
13615                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
13616
13617                final int left = mLeft + (int) region.left;
13618                final int top = mTop + (int) region.top;
13619                parent.invalidate(left, top, left + (int) (region.width() + .5f),
13620                        top + (int) (region.height() + .5f));
13621            }
13622        }
13623        return more;
13624    }
13625
13626    /**
13627     * This method is called by getDisplayList() when a display list is created or re-rendered.
13628     * It sets or resets the current value of all properties on that display list (resetting is
13629     * necessary when a display list is being re-created, because we need to make sure that
13630     * previously-set transform values
13631     */
13632    void setDisplayListProperties(DisplayList displayList) {
13633        if (displayList != null) {
13634            displayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
13635            displayList.setHasOverlappingRendering(hasOverlappingRendering());
13636            if (mParent instanceof ViewGroup) {
13637                displayList.setClipToBounds(
13638                        (((ViewGroup) mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0);
13639            }
13640            float alpha = 1;
13641            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
13642                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
13643                ViewGroup parentVG = (ViewGroup) mParent;
13644                final Transformation t = parentVG.getChildTransformation();
13645                if (parentVG.getChildStaticTransformation(this, t)) {
13646                    final int transformType = t.getTransformationType();
13647                    if (transformType != Transformation.TYPE_IDENTITY) {
13648                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
13649                            alpha = t.getAlpha();
13650                        }
13651                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
13652                            displayList.setMatrix(t.getMatrix());
13653                        }
13654                    }
13655                }
13656            }
13657            if (mTransformationInfo != null) {
13658                alpha *= mTransformationInfo.mAlpha;
13659                if (alpha < 1) {
13660                    final int multipliedAlpha = (int) (255 * alpha);
13661                    if (onSetAlpha(multipliedAlpha)) {
13662                        alpha = 1;
13663                    }
13664                }
13665                displayList.setTransformationInfo(alpha,
13666                        mTransformationInfo.mTranslationX, mTransformationInfo.mTranslationY,
13667                        mTransformationInfo.mRotation, mTransformationInfo.mRotationX,
13668                        mTransformationInfo.mRotationY, mTransformationInfo.mScaleX,
13669                        mTransformationInfo.mScaleY);
13670                if (mTransformationInfo.mCamera == null) {
13671                    mTransformationInfo.mCamera = new Camera();
13672                    mTransformationInfo.matrix3D = new Matrix();
13673                }
13674                displayList.setCameraDistance(mTransformationInfo.mCamera.getLocationZ());
13675                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == PFLAG_PIVOT_EXPLICITLY_SET) {
13676                    displayList.setPivotX(getPivotX());
13677                    displayList.setPivotY(getPivotY());
13678                }
13679            } else if (alpha < 1) {
13680                displayList.setAlpha(alpha);
13681            }
13682        }
13683    }
13684
13685    /**
13686     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
13687     * This draw() method is an implementation detail and is not intended to be overridden or
13688     * to be called from anywhere else other than ViewGroup.drawChild().
13689     */
13690    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
13691        boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
13692        boolean more = false;
13693        final boolean childHasIdentityMatrix = hasIdentityMatrix();
13694        final int flags = parent.mGroupFlags;
13695
13696        if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) {
13697            parent.getChildTransformation().clear();
13698            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13699        }
13700
13701        Transformation transformToApply = null;
13702        boolean concatMatrix = false;
13703
13704        boolean scalingRequired = false;
13705        boolean caching;
13706        int layerType = getLayerType();
13707
13708        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
13709        if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 ||
13710                (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) {
13711            caching = true;
13712            // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList
13713            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
13714        } else {
13715            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
13716        }
13717
13718        final Animation a = getAnimation();
13719        if (a != null) {
13720            more = drawAnimation(parent, drawingTime, a, scalingRequired);
13721            concatMatrix = a.willChangeTransformationMatrix();
13722            if (concatMatrix) {
13723                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
13724            }
13725            transformToApply = parent.getChildTransformation();
13726        } else {
13727            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) ==
13728                    PFLAG3_VIEW_IS_ANIMATING_TRANSFORM && mDisplayList != null) {
13729                // No longer animating: clear out old animation matrix
13730                mDisplayList.setAnimationMatrix(null);
13731                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
13732            }
13733            if (!useDisplayListProperties &&
13734                    (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
13735                final Transformation t = parent.getChildTransformation();
13736                final boolean hasTransform = parent.getChildStaticTransformation(this, t);
13737                if (hasTransform) {
13738                    final int transformType = t.getTransformationType();
13739                    transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null;
13740                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
13741                }
13742            }
13743        }
13744
13745        concatMatrix |= !childHasIdentityMatrix;
13746
13747        // Sets the flag as early as possible to allow draw() implementations
13748        // to call invalidate() successfully when doing animations
13749        mPrivateFlags |= PFLAG_DRAWN;
13750
13751        if (!concatMatrix &&
13752                (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
13753                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
13754                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
13755                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
13756            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
13757            return more;
13758        }
13759        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
13760
13761        if (hardwareAccelerated) {
13762            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
13763            // retain the flag's value temporarily in the mRecreateDisplayList flag
13764            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED;
13765            mPrivateFlags &= ~PFLAG_INVALIDATED;
13766        }
13767
13768        DisplayList displayList = null;
13769        Bitmap cache = null;
13770        boolean hasDisplayList = false;
13771        if (caching) {
13772            if (!hardwareAccelerated) {
13773                if (layerType != LAYER_TYPE_NONE) {
13774                    layerType = LAYER_TYPE_SOFTWARE;
13775                    buildDrawingCache(true);
13776                }
13777                cache = getDrawingCache(true);
13778            } else {
13779                switch (layerType) {
13780                    case LAYER_TYPE_SOFTWARE:
13781                        if (useDisplayListProperties) {
13782                            hasDisplayList = canHaveDisplayList();
13783                        } else {
13784                            buildDrawingCache(true);
13785                            cache = getDrawingCache(true);
13786                        }
13787                        break;
13788                    case LAYER_TYPE_HARDWARE:
13789                        if (useDisplayListProperties) {
13790                            hasDisplayList = canHaveDisplayList();
13791                        }
13792                        break;
13793                    case LAYER_TYPE_NONE:
13794                        // Delay getting the display list until animation-driven alpha values are
13795                        // set up and possibly passed on to the view
13796                        hasDisplayList = canHaveDisplayList();
13797                        break;
13798                }
13799            }
13800        }
13801        useDisplayListProperties &= hasDisplayList;
13802        if (useDisplayListProperties) {
13803            displayList = getDisplayList();
13804            if (!displayList.isValid()) {
13805                // Uncommon, but possible. If a view is removed from the hierarchy during the call
13806                // to getDisplayList(), the display list will be marked invalid and we should not
13807                // try to use it again.
13808                displayList = null;
13809                hasDisplayList = false;
13810                useDisplayListProperties = false;
13811            }
13812        }
13813
13814        int sx = 0;
13815        int sy = 0;
13816        if (!hasDisplayList) {
13817            computeScroll();
13818            sx = mScrollX;
13819            sy = mScrollY;
13820        }
13821
13822        final boolean hasNoCache = cache == null || hasDisplayList;
13823        final boolean offsetForScroll = cache == null && !hasDisplayList &&
13824                layerType != LAYER_TYPE_HARDWARE;
13825
13826        int restoreTo = -1;
13827        if (!useDisplayListProperties || transformToApply != null) {
13828            restoreTo = canvas.save();
13829        }
13830        if (offsetForScroll) {
13831            canvas.translate(mLeft - sx, mTop - sy);
13832        } else {
13833            if (!useDisplayListProperties) {
13834                canvas.translate(mLeft, mTop);
13835            }
13836            if (scalingRequired) {
13837                if (useDisplayListProperties) {
13838                    // TODO: Might not need this if we put everything inside the DL
13839                    restoreTo = canvas.save();
13840                }
13841                // mAttachInfo cannot be null, otherwise scalingRequired == false
13842                final float scale = 1.0f / mAttachInfo.mApplicationScale;
13843                canvas.scale(scale, scale);
13844            }
13845        }
13846
13847        float alpha = useDisplayListProperties ? 1 : getAlpha();
13848        if (transformToApply != null || alpha < 1 || !hasIdentityMatrix() ||
13849                (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
13850            if (transformToApply != null || !childHasIdentityMatrix) {
13851                int transX = 0;
13852                int transY = 0;
13853
13854                if (offsetForScroll) {
13855                    transX = -sx;
13856                    transY = -sy;
13857                }
13858
13859                if (transformToApply != null) {
13860                    if (concatMatrix) {
13861                        if (useDisplayListProperties) {
13862                            displayList.setAnimationMatrix(transformToApply.getMatrix());
13863                        } else {
13864                            // Undo the scroll translation, apply the transformation matrix,
13865                            // then redo the scroll translate to get the correct result.
13866                            canvas.translate(-transX, -transY);
13867                            canvas.concat(transformToApply.getMatrix());
13868                            canvas.translate(transX, transY);
13869                        }
13870                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13871                    }
13872
13873                    float transformAlpha = transformToApply.getAlpha();
13874                    if (transformAlpha < 1) {
13875                        alpha *= transformAlpha;
13876                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13877                    }
13878                }
13879
13880                if (!childHasIdentityMatrix && !useDisplayListProperties) {
13881                    canvas.translate(-transX, -transY);
13882                    canvas.concat(getMatrix());
13883                    canvas.translate(transX, transY);
13884                }
13885            }
13886
13887            // Deal with alpha if it is or used to be <1
13888            if (alpha < 1 ||
13889                    (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
13890                if (alpha < 1) {
13891                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
13892                } else {
13893                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
13894                }
13895                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13896                if (hasNoCache) {
13897                    final int multipliedAlpha = (int) (255 * alpha);
13898                    if (!onSetAlpha(multipliedAlpha)) {
13899                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
13900                        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 ||
13901                                layerType != LAYER_TYPE_NONE) {
13902                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
13903                        }
13904                        if (useDisplayListProperties) {
13905                            displayList.setAlpha(alpha * getAlpha());
13906                        } else  if (layerType == LAYER_TYPE_NONE) {
13907                            final int scrollX = hasDisplayList ? 0 : sx;
13908                            final int scrollY = hasDisplayList ? 0 : sy;
13909                            canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft,
13910                                    scrollY + mBottom - mTop, multipliedAlpha, layerFlags);
13911                        }
13912                    } else {
13913                        // Alpha is handled by the child directly, clobber the layer's alpha
13914                        mPrivateFlags |= PFLAG_ALPHA_SET;
13915                    }
13916                }
13917            }
13918        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
13919            onSetAlpha(255);
13920            mPrivateFlags &= ~PFLAG_ALPHA_SET;
13921        }
13922
13923        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN &&
13924                !useDisplayListProperties && cache == null) {
13925            if (offsetForScroll) {
13926                canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
13927            } else {
13928                if (!scalingRequired || cache == null) {
13929                    canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
13930                } else {
13931                    canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
13932                }
13933            }
13934        }
13935
13936        if (!useDisplayListProperties && hasDisplayList) {
13937            displayList = getDisplayList();
13938            if (!displayList.isValid()) {
13939                // Uncommon, but possible. If a view is removed from the hierarchy during the call
13940                // to getDisplayList(), the display list will be marked invalid and we should not
13941                // try to use it again.
13942                displayList = null;
13943                hasDisplayList = false;
13944            }
13945        }
13946
13947        if (hasNoCache) {
13948            boolean layerRendered = false;
13949            if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) {
13950                final HardwareLayer layer = getHardwareLayer();
13951                if (layer != null && layer.isValid()) {
13952                    mLayerPaint.setAlpha((int) (alpha * 255));
13953                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
13954                    layerRendered = true;
13955                } else {
13956                    final int scrollX = hasDisplayList ? 0 : sx;
13957                    final int scrollY = hasDisplayList ? 0 : sy;
13958                    canvas.saveLayer(scrollX, scrollY,
13959                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
13960                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
13961                }
13962            }
13963
13964            if (!layerRendered) {
13965                if (!hasDisplayList) {
13966                    // Fast path for layouts with no backgrounds
13967                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13968                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13969                        dispatchDraw(canvas);
13970                    } else {
13971                        draw(canvas);
13972                    }
13973                } else {
13974                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13975                    ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags);
13976                }
13977            }
13978        } else if (cache != null) {
13979            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13980            Paint cachePaint;
13981
13982            if (layerType == LAYER_TYPE_NONE) {
13983                cachePaint = parent.mCachePaint;
13984                if (cachePaint == null) {
13985                    cachePaint = new Paint();
13986                    cachePaint.setDither(false);
13987                    parent.mCachePaint = cachePaint;
13988                }
13989                if (alpha < 1) {
13990                    cachePaint.setAlpha((int) (alpha * 255));
13991                    parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
13992                } else if  ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) {
13993                    cachePaint.setAlpha(255);
13994                    parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
13995                }
13996            } else {
13997                cachePaint = mLayerPaint;
13998                cachePaint.setAlpha((int) (alpha * 255));
13999            }
14000            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
14001        }
14002
14003        if (restoreTo >= 0) {
14004            canvas.restoreToCount(restoreTo);
14005        }
14006
14007        if (a != null && !more) {
14008            if (!hardwareAccelerated && !a.getFillAfter()) {
14009                onSetAlpha(255);
14010            }
14011            parent.finishAnimatingView(this, a);
14012        }
14013
14014        if (more && hardwareAccelerated) {
14015            // invalidation is the trigger to recreate display lists, so if we're using
14016            // display lists to render, force an invalidate to allow the animation to
14017            // continue drawing another frame
14018            parent.invalidate(true);
14019            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
14020                // alpha animations should cause the child to recreate its display list
14021                invalidate(true);
14022            }
14023        }
14024
14025        mRecreateDisplayList = false;
14026
14027        return more;
14028    }
14029
14030    /**
14031     * Manually render this view (and all of its children) to the given Canvas.
14032     * The view must have already done a full layout before this function is
14033     * called.  When implementing a view, implement
14034     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
14035     * If you do need to override this method, call the superclass version.
14036     *
14037     * @param canvas The Canvas to which the View is rendered.
14038     */
14039    public void draw(Canvas canvas) {
14040        if (mClipBounds != null) {
14041            canvas.clipRect(mClipBounds);
14042        }
14043        final int privateFlags = mPrivateFlags;
14044        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
14045                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
14046        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
14047
14048        /*
14049         * Draw traversal performs several drawing steps which must be executed
14050         * in the appropriate order:
14051         *
14052         *      1. Draw the background
14053         *      2. If necessary, save the canvas' layers to prepare for fading
14054         *      3. Draw view's content
14055         *      4. Draw children
14056         *      5. If necessary, draw the fading edges and restore layers
14057         *      6. Draw decorations (scrollbars for instance)
14058         */
14059
14060        // Step 1, draw the background, if needed
14061        int saveCount;
14062
14063        if (!dirtyOpaque) {
14064            final Drawable background = mBackground;
14065            if (background != null) {
14066                final int scrollX = mScrollX;
14067                final int scrollY = mScrollY;
14068
14069                if (mBackgroundSizeChanged) {
14070                    background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
14071                    mBackgroundSizeChanged = false;
14072                }
14073
14074                if ((scrollX | scrollY) == 0) {
14075                    background.draw(canvas);
14076                } else {
14077                    canvas.translate(scrollX, scrollY);
14078                    background.draw(canvas);
14079                    canvas.translate(-scrollX, -scrollY);
14080                }
14081            }
14082        }
14083
14084        // skip step 2 & 5 if possible (common case)
14085        final int viewFlags = mViewFlags;
14086        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
14087        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
14088        if (!verticalEdges && !horizontalEdges) {
14089            // Step 3, draw the content
14090            if (!dirtyOpaque) onDraw(canvas);
14091
14092            // Step 4, draw the children
14093            dispatchDraw(canvas);
14094
14095            // Step 6, draw decorations (scrollbars)
14096            onDrawScrollBars(canvas);
14097
14098            if (mOverlay != null && !mOverlay.isEmpty()) {
14099                mOverlay.getOverlayView().dispatchDraw(canvas);
14100            }
14101
14102            // we're done...
14103            return;
14104        }
14105
14106        /*
14107         * Here we do the full fledged routine...
14108         * (this is an uncommon case where speed matters less,
14109         * this is why we repeat some of the tests that have been
14110         * done above)
14111         */
14112
14113        boolean drawTop = false;
14114        boolean drawBottom = false;
14115        boolean drawLeft = false;
14116        boolean drawRight = false;
14117
14118        float topFadeStrength = 0.0f;
14119        float bottomFadeStrength = 0.0f;
14120        float leftFadeStrength = 0.0f;
14121        float rightFadeStrength = 0.0f;
14122
14123        // Step 2, save the canvas' layers
14124        int paddingLeft = mPaddingLeft;
14125
14126        final boolean offsetRequired = isPaddingOffsetRequired();
14127        if (offsetRequired) {
14128            paddingLeft += getLeftPaddingOffset();
14129        }
14130
14131        int left = mScrollX + paddingLeft;
14132        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
14133        int top = mScrollY + getFadeTop(offsetRequired);
14134        int bottom = top + getFadeHeight(offsetRequired);
14135
14136        if (offsetRequired) {
14137            right += getRightPaddingOffset();
14138            bottom += getBottomPaddingOffset();
14139        }
14140
14141        final ScrollabilityCache scrollabilityCache = mScrollCache;
14142        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
14143        int length = (int) fadeHeight;
14144
14145        // clip the fade length if top and bottom fades overlap
14146        // overlapping fades produce odd-looking artifacts
14147        if (verticalEdges && (top + length > bottom - length)) {
14148            length = (bottom - top) / 2;
14149        }
14150
14151        // also clip horizontal fades if necessary
14152        if (horizontalEdges && (left + length > right - length)) {
14153            length = (right - left) / 2;
14154        }
14155
14156        if (verticalEdges) {
14157            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
14158            drawTop = topFadeStrength * fadeHeight > 1.0f;
14159            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
14160            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
14161        }
14162
14163        if (horizontalEdges) {
14164            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
14165            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
14166            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
14167            drawRight = rightFadeStrength * fadeHeight > 1.0f;
14168        }
14169
14170        saveCount = canvas.getSaveCount();
14171
14172        int solidColor = getSolidColor();
14173        if (solidColor == 0) {
14174            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
14175
14176            if (drawTop) {
14177                canvas.saveLayer(left, top, right, top + length, null, flags);
14178            }
14179
14180            if (drawBottom) {
14181                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
14182            }
14183
14184            if (drawLeft) {
14185                canvas.saveLayer(left, top, left + length, bottom, null, flags);
14186            }
14187
14188            if (drawRight) {
14189                canvas.saveLayer(right - length, top, right, bottom, null, flags);
14190            }
14191        } else {
14192            scrollabilityCache.setFadeColor(solidColor);
14193        }
14194
14195        // Step 3, draw the content
14196        if (!dirtyOpaque) onDraw(canvas);
14197
14198        // Step 4, draw the children
14199        dispatchDraw(canvas);
14200
14201        // Step 5, draw the fade effect and restore layers
14202        final Paint p = scrollabilityCache.paint;
14203        final Matrix matrix = scrollabilityCache.matrix;
14204        final Shader fade = scrollabilityCache.shader;
14205
14206        if (drawTop) {
14207            matrix.setScale(1, fadeHeight * topFadeStrength);
14208            matrix.postTranslate(left, top);
14209            fade.setLocalMatrix(matrix);
14210            canvas.drawRect(left, top, right, top + length, p);
14211        }
14212
14213        if (drawBottom) {
14214            matrix.setScale(1, fadeHeight * bottomFadeStrength);
14215            matrix.postRotate(180);
14216            matrix.postTranslate(left, bottom);
14217            fade.setLocalMatrix(matrix);
14218            canvas.drawRect(left, bottom - length, right, bottom, p);
14219        }
14220
14221        if (drawLeft) {
14222            matrix.setScale(1, fadeHeight * leftFadeStrength);
14223            matrix.postRotate(-90);
14224            matrix.postTranslate(left, top);
14225            fade.setLocalMatrix(matrix);
14226            canvas.drawRect(left, top, left + length, bottom, p);
14227        }
14228
14229        if (drawRight) {
14230            matrix.setScale(1, fadeHeight * rightFadeStrength);
14231            matrix.postRotate(90);
14232            matrix.postTranslate(right, top);
14233            fade.setLocalMatrix(matrix);
14234            canvas.drawRect(right - length, top, right, bottom, p);
14235        }
14236
14237        canvas.restoreToCount(saveCount);
14238
14239        // Step 6, draw decorations (scrollbars)
14240        onDrawScrollBars(canvas);
14241
14242        if (mOverlay != null && !mOverlay.isEmpty()) {
14243            mOverlay.getOverlayView().dispatchDraw(canvas);
14244        }
14245    }
14246
14247    /**
14248     * Returns the overlay for this view, creating it if it does not yet exist.
14249     * Adding drawables to the overlay will cause them to be displayed whenever
14250     * the view itself is redrawn. Objects in the overlay should be actively
14251     * managed: remove them when they should not be displayed anymore. The
14252     * overlay will always have the same size as its host view.
14253     *
14254     * <p>Note: Overlays do not currently work correctly with {@link
14255     * SurfaceView} or {@link TextureView}; contents in overlays for these
14256     * types of views may not display correctly.</p>
14257     *
14258     * @return The ViewOverlay object for this view.
14259     * @see ViewOverlay
14260     */
14261    public ViewOverlay getOverlay() {
14262        if (mOverlay == null) {
14263            mOverlay = new ViewOverlay(mContext, this);
14264        }
14265        return mOverlay;
14266    }
14267
14268    /**
14269     * Override this if your view is known to always be drawn on top of a solid color background,
14270     * and needs to draw fading edges. Returning a non-zero color enables the view system to
14271     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
14272     * should be set to 0xFF.
14273     *
14274     * @see #setVerticalFadingEdgeEnabled(boolean)
14275     * @see #setHorizontalFadingEdgeEnabled(boolean)
14276     *
14277     * @return The known solid color background for this view, or 0 if the color may vary
14278     */
14279    @ViewDebug.ExportedProperty(category = "drawing")
14280    public int getSolidColor() {
14281        return 0;
14282    }
14283
14284    /**
14285     * Build a human readable string representation of the specified view flags.
14286     *
14287     * @param flags the view flags to convert to a string
14288     * @return a String representing the supplied flags
14289     */
14290    private static String printFlags(int flags) {
14291        String output = "";
14292        int numFlags = 0;
14293        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
14294            output += "TAKES_FOCUS";
14295            numFlags++;
14296        }
14297
14298        switch (flags & VISIBILITY_MASK) {
14299        case INVISIBLE:
14300            if (numFlags > 0) {
14301                output += " ";
14302            }
14303            output += "INVISIBLE";
14304            // USELESS HERE numFlags++;
14305            break;
14306        case GONE:
14307            if (numFlags > 0) {
14308                output += " ";
14309            }
14310            output += "GONE";
14311            // USELESS HERE numFlags++;
14312            break;
14313        default:
14314            break;
14315        }
14316        return output;
14317    }
14318
14319    /**
14320     * Build a human readable string representation of the specified private
14321     * view flags.
14322     *
14323     * @param privateFlags the private view flags to convert to a string
14324     * @return a String representing the supplied flags
14325     */
14326    private static String printPrivateFlags(int privateFlags) {
14327        String output = "";
14328        int numFlags = 0;
14329
14330        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
14331            output += "WANTS_FOCUS";
14332            numFlags++;
14333        }
14334
14335        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
14336            if (numFlags > 0) {
14337                output += " ";
14338            }
14339            output += "FOCUSED";
14340            numFlags++;
14341        }
14342
14343        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
14344            if (numFlags > 0) {
14345                output += " ";
14346            }
14347            output += "SELECTED";
14348            numFlags++;
14349        }
14350
14351        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
14352            if (numFlags > 0) {
14353                output += " ";
14354            }
14355            output += "IS_ROOT_NAMESPACE";
14356            numFlags++;
14357        }
14358
14359        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
14360            if (numFlags > 0) {
14361                output += " ";
14362            }
14363            output += "HAS_BOUNDS";
14364            numFlags++;
14365        }
14366
14367        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
14368            if (numFlags > 0) {
14369                output += " ";
14370            }
14371            output += "DRAWN";
14372            // USELESS HERE numFlags++;
14373        }
14374        return output;
14375    }
14376
14377    /**
14378     * <p>Indicates whether or not this view's layout will be requested during
14379     * the next hierarchy layout pass.</p>
14380     *
14381     * @return true if the layout will be forced during next layout pass
14382     */
14383    public boolean isLayoutRequested() {
14384        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
14385    }
14386
14387    /**
14388     * Return true if o is a ViewGroup that is laying out using optical bounds.
14389     * @hide
14390     */
14391    public static boolean isLayoutModeOptical(Object o) {
14392        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
14393    }
14394
14395    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
14396        Insets parentInsets = mParent instanceof View ?
14397                ((View) mParent).getOpticalInsets() : Insets.NONE;
14398        Insets childInsets = getOpticalInsets();
14399        return setFrame(
14400                left   + parentInsets.left - childInsets.left,
14401                top    + parentInsets.top  - childInsets.top,
14402                right  + parentInsets.left + childInsets.right,
14403                bottom + parentInsets.top  + childInsets.bottom);
14404    }
14405
14406    /**
14407     * Assign a size and position to a view and all of its
14408     * descendants
14409     *
14410     * <p>This is the second phase of the layout mechanism.
14411     * (The first is measuring). In this phase, each parent calls
14412     * layout on all of its children to position them.
14413     * This is typically done using the child measurements
14414     * that were stored in the measure pass().</p>
14415     *
14416     * <p>Derived classes should not override this method.
14417     * Derived classes with children should override
14418     * onLayout. In that method, they should
14419     * call layout on each of their children.</p>
14420     *
14421     * @param l Left position, relative to parent
14422     * @param t Top position, relative to parent
14423     * @param r Right position, relative to parent
14424     * @param b Bottom position, relative to parent
14425     */
14426    @SuppressWarnings({"unchecked"})
14427    public void layout(int l, int t, int r, int b) {
14428        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
14429            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
14430            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
14431        }
14432
14433        int oldL = mLeft;
14434        int oldT = mTop;
14435        int oldB = mBottom;
14436        int oldR = mRight;
14437
14438        boolean changed = isLayoutModeOptical(mParent) ?
14439                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
14440
14441        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
14442            onLayout(changed, l, t, r, b);
14443            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
14444
14445            ListenerInfo li = mListenerInfo;
14446            if (li != null && li.mOnLayoutChangeListeners != null) {
14447                ArrayList<OnLayoutChangeListener> listenersCopy =
14448                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
14449                int numListeners = listenersCopy.size();
14450                for (int i = 0; i < numListeners; ++i) {
14451                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
14452                }
14453            }
14454        }
14455
14456        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
14457        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
14458    }
14459
14460    /**
14461     * Called from layout when this view should
14462     * assign a size and position to each of its children.
14463     *
14464     * Derived classes with children should override
14465     * this method and call layout on each of
14466     * their children.
14467     * @param changed This is a new size or position for this view
14468     * @param left Left position, relative to parent
14469     * @param top Top position, relative to parent
14470     * @param right Right position, relative to parent
14471     * @param bottom Bottom position, relative to parent
14472     */
14473    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
14474    }
14475
14476    /**
14477     * Assign a size and position to this view.
14478     *
14479     * This is called from layout.
14480     *
14481     * @param left Left position, relative to parent
14482     * @param top Top position, relative to parent
14483     * @param right Right position, relative to parent
14484     * @param bottom Bottom position, relative to parent
14485     * @return true if the new size and position are different than the
14486     *         previous ones
14487     * {@hide}
14488     */
14489    protected boolean setFrame(int left, int top, int right, int bottom) {
14490        boolean changed = false;
14491
14492        if (DBG) {
14493            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
14494                    + right + "," + bottom + ")");
14495        }
14496
14497        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
14498            changed = true;
14499
14500            // Remember our drawn bit
14501            int drawn = mPrivateFlags & PFLAG_DRAWN;
14502
14503            int oldWidth = mRight - mLeft;
14504            int oldHeight = mBottom - mTop;
14505            int newWidth = right - left;
14506            int newHeight = bottom - top;
14507            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
14508
14509            // Invalidate our old position
14510            invalidate(sizeChanged);
14511
14512            mLeft = left;
14513            mTop = top;
14514            mRight = right;
14515            mBottom = bottom;
14516            if (mDisplayList != null) {
14517                mDisplayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
14518            }
14519
14520            mPrivateFlags |= PFLAG_HAS_BOUNDS;
14521
14522
14523            if (sizeChanged) {
14524                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
14525                    // A change in dimension means an auto-centered pivot point changes, too
14526                    if (mTransformationInfo != null) {
14527                        mTransformationInfo.mMatrixDirty = true;
14528                    }
14529                }
14530                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
14531            }
14532
14533            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
14534                // If we are visible, force the DRAWN bit to on so that
14535                // this invalidate will go through (at least to our parent).
14536                // This is because someone may have invalidated this view
14537                // before this call to setFrame came in, thereby clearing
14538                // the DRAWN bit.
14539                mPrivateFlags |= PFLAG_DRAWN;
14540                invalidate(sizeChanged);
14541                // parent display list may need to be recreated based on a change in the bounds
14542                // of any child
14543                invalidateParentCaches();
14544            }
14545
14546            // Reset drawn bit to original value (invalidate turns it off)
14547            mPrivateFlags |= drawn;
14548
14549            mBackgroundSizeChanged = true;
14550
14551            notifySubtreeAccessibilityStateChangedIfNeeded();
14552        }
14553        return changed;
14554    }
14555
14556    private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
14557        onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
14558        if (mOverlay != null) {
14559            mOverlay.getOverlayView().setRight(newWidth);
14560            mOverlay.getOverlayView().setBottom(newHeight);
14561        }
14562    }
14563
14564    /**
14565     * Finalize inflating a view from XML.  This is called as the last phase
14566     * of inflation, after all child views have been added.
14567     *
14568     * <p>Even if the subclass overrides onFinishInflate, they should always be
14569     * sure to call the super method, so that we get called.
14570     */
14571    protected void onFinishInflate() {
14572    }
14573
14574    /**
14575     * Returns the resources associated with this view.
14576     *
14577     * @return Resources object.
14578     */
14579    public Resources getResources() {
14580        return mResources;
14581    }
14582
14583    /**
14584     * Invalidates the specified Drawable.
14585     *
14586     * @param drawable the drawable to invalidate
14587     */
14588    public void invalidateDrawable(Drawable drawable) {
14589        if (verifyDrawable(drawable)) {
14590            final Rect dirty = drawable.getBounds();
14591            final int scrollX = mScrollX;
14592            final int scrollY = mScrollY;
14593
14594            invalidate(dirty.left + scrollX, dirty.top + scrollY,
14595                    dirty.right + scrollX, dirty.bottom + scrollY);
14596        }
14597    }
14598
14599    /**
14600     * Schedules an action on a drawable to occur at a specified time.
14601     *
14602     * @param who the recipient of the action
14603     * @param what the action to run on the drawable
14604     * @param when the time at which the action must occur. Uses the
14605     *        {@link SystemClock#uptimeMillis} timebase.
14606     */
14607    public void scheduleDrawable(Drawable who, Runnable what, long when) {
14608        if (verifyDrawable(who) && what != null) {
14609            final long delay = when - SystemClock.uptimeMillis();
14610            if (mAttachInfo != null) {
14611                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
14612                        Choreographer.CALLBACK_ANIMATION, what, who,
14613                        Choreographer.subtractFrameDelay(delay));
14614            } else {
14615                ViewRootImpl.getRunQueue().postDelayed(what, delay);
14616            }
14617        }
14618    }
14619
14620    /**
14621     * Cancels a scheduled action on a drawable.
14622     *
14623     * @param who the recipient of the action
14624     * @param what the action to cancel
14625     */
14626    public void unscheduleDrawable(Drawable who, Runnable what) {
14627        if (verifyDrawable(who) && what != null) {
14628            if (mAttachInfo != null) {
14629                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
14630                        Choreographer.CALLBACK_ANIMATION, what, who);
14631            } else {
14632                ViewRootImpl.getRunQueue().removeCallbacks(what);
14633            }
14634        }
14635    }
14636
14637    /**
14638     * Unschedule any events associated with the given Drawable.  This can be
14639     * used when selecting a new Drawable into a view, so that the previous
14640     * one is completely unscheduled.
14641     *
14642     * @param who The Drawable to unschedule.
14643     *
14644     * @see #drawableStateChanged
14645     */
14646    public void unscheduleDrawable(Drawable who) {
14647        if (mAttachInfo != null && who != null) {
14648            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
14649                    Choreographer.CALLBACK_ANIMATION, null, who);
14650        }
14651    }
14652
14653    /**
14654     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
14655     * that the View directionality can and will be resolved before its Drawables.
14656     *
14657     * Will call {@link View#onResolveDrawables} when resolution is done.
14658     *
14659     * @hide
14660     */
14661    protected void resolveDrawables() {
14662        // Drawables resolution may need to happen before resolving the layout direction (which is
14663        // done only during the measure() call).
14664        // If the layout direction is not resolved yet, we cannot resolve the Drawables except in
14665        // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT.
14666        // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or
14667        // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout
14668        // direction to be resolved as its resolved value will be the same as its raw value.
14669        if (!isLayoutDirectionResolved() &&
14670                getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) {
14671            return;
14672        }
14673
14674        final int layoutDirection = isLayoutDirectionResolved() ?
14675                getLayoutDirection() : getRawLayoutDirection();
14676
14677        if (mBackground != null) {
14678            mBackground.setLayoutDirection(layoutDirection);
14679        }
14680        mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
14681        onResolveDrawables(layoutDirection);
14682    }
14683
14684    /**
14685     * Called when layout direction has been resolved.
14686     *
14687     * The default implementation does nothing.
14688     *
14689     * @param layoutDirection The resolved layout direction.
14690     *
14691     * @see #LAYOUT_DIRECTION_LTR
14692     * @see #LAYOUT_DIRECTION_RTL
14693     *
14694     * @hide
14695     */
14696    public void onResolveDrawables(int layoutDirection) {
14697    }
14698
14699    /**
14700     * @hide
14701     */
14702    protected void resetResolvedDrawables() {
14703        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
14704    }
14705
14706    private boolean isDrawablesResolved() {
14707        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
14708    }
14709
14710    /**
14711     * If your view subclass is displaying its own Drawable objects, it should
14712     * override this function and return true for any Drawable it is
14713     * displaying.  This allows animations for those drawables to be
14714     * scheduled.
14715     *
14716     * <p>Be sure to call through to the super class when overriding this
14717     * function.
14718     *
14719     * @param who The Drawable to verify.  Return true if it is one you are
14720     *            displaying, else return the result of calling through to the
14721     *            super class.
14722     *
14723     * @return boolean If true than the Drawable is being displayed in the
14724     *         view; else false and it is not allowed to animate.
14725     *
14726     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
14727     * @see #drawableStateChanged()
14728     */
14729    protected boolean verifyDrawable(Drawable who) {
14730        return who == mBackground;
14731    }
14732
14733    /**
14734     * This function is called whenever the state of the view changes in such
14735     * a way that it impacts the state of drawables being shown.
14736     *
14737     * <p>Be sure to call through to the superclass when overriding this
14738     * function.
14739     *
14740     * @see Drawable#setState(int[])
14741     */
14742    protected void drawableStateChanged() {
14743        Drawable d = mBackground;
14744        if (d != null && d.isStateful()) {
14745            d.setState(getDrawableState());
14746        }
14747    }
14748
14749    /**
14750     * Call this to force a view to update its drawable state. This will cause
14751     * drawableStateChanged to be called on this view. Views that are interested
14752     * in the new state should call getDrawableState.
14753     *
14754     * @see #drawableStateChanged
14755     * @see #getDrawableState
14756     */
14757    public void refreshDrawableState() {
14758        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
14759        drawableStateChanged();
14760
14761        ViewParent parent = mParent;
14762        if (parent != null) {
14763            parent.childDrawableStateChanged(this);
14764        }
14765    }
14766
14767    /**
14768     * Return an array of resource IDs of the drawable states representing the
14769     * current state of the view.
14770     *
14771     * @return The current drawable state
14772     *
14773     * @see Drawable#setState(int[])
14774     * @see #drawableStateChanged()
14775     * @see #onCreateDrawableState(int)
14776     */
14777    public final int[] getDrawableState() {
14778        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
14779            return mDrawableState;
14780        } else {
14781            mDrawableState = onCreateDrawableState(0);
14782            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
14783            return mDrawableState;
14784        }
14785    }
14786
14787    /**
14788     * Generate the new {@link android.graphics.drawable.Drawable} state for
14789     * this view. This is called by the view
14790     * system when the cached Drawable state is determined to be invalid.  To
14791     * retrieve the current state, you should use {@link #getDrawableState}.
14792     *
14793     * @param extraSpace if non-zero, this is the number of extra entries you
14794     * would like in the returned array in which you can place your own
14795     * states.
14796     *
14797     * @return Returns an array holding the current {@link Drawable} state of
14798     * the view.
14799     *
14800     * @see #mergeDrawableStates(int[], int[])
14801     */
14802    protected int[] onCreateDrawableState(int extraSpace) {
14803        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
14804                mParent instanceof View) {
14805            return ((View) mParent).onCreateDrawableState(extraSpace);
14806        }
14807
14808        int[] drawableState;
14809
14810        int privateFlags = mPrivateFlags;
14811
14812        int viewStateIndex = 0;
14813        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
14814        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
14815        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
14816        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
14817        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
14818        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
14819        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
14820                HardwareRenderer.isAvailable()) {
14821            // This is set if HW acceleration is requested, even if the current
14822            // process doesn't allow it.  This is just to allow app preview
14823            // windows to better match their app.
14824            viewStateIndex |= VIEW_STATE_ACCELERATED;
14825        }
14826        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
14827
14828        final int privateFlags2 = mPrivateFlags2;
14829        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
14830        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
14831
14832        drawableState = VIEW_STATE_SETS[viewStateIndex];
14833
14834        //noinspection ConstantIfStatement
14835        if (false) {
14836            Log.i("View", "drawableStateIndex=" + viewStateIndex);
14837            Log.i("View", toString()
14838                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
14839                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
14840                    + " fo=" + hasFocus()
14841                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
14842                    + " wf=" + hasWindowFocus()
14843                    + ": " + Arrays.toString(drawableState));
14844        }
14845
14846        if (extraSpace == 0) {
14847            return drawableState;
14848        }
14849
14850        final int[] fullState;
14851        if (drawableState != null) {
14852            fullState = new int[drawableState.length + extraSpace];
14853            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
14854        } else {
14855            fullState = new int[extraSpace];
14856        }
14857
14858        return fullState;
14859    }
14860
14861    /**
14862     * Merge your own state values in <var>additionalState</var> into the base
14863     * state values <var>baseState</var> that were returned by
14864     * {@link #onCreateDrawableState(int)}.
14865     *
14866     * @param baseState The base state values returned by
14867     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
14868     * own additional state values.
14869     *
14870     * @param additionalState The additional state values you would like
14871     * added to <var>baseState</var>; this array is not modified.
14872     *
14873     * @return As a convenience, the <var>baseState</var> array you originally
14874     * passed into the function is returned.
14875     *
14876     * @see #onCreateDrawableState(int)
14877     */
14878    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
14879        final int N = baseState.length;
14880        int i = N - 1;
14881        while (i >= 0 && baseState[i] == 0) {
14882            i--;
14883        }
14884        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
14885        return baseState;
14886    }
14887
14888    /**
14889     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
14890     * on all Drawable objects associated with this view.
14891     */
14892    public void jumpDrawablesToCurrentState() {
14893        if (mBackground != null) {
14894            mBackground.jumpToCurrentState();
14895        }
14896    }
14897
14898    /**
14899     * Sets the background color for this view.
14900     * @param color the color of the background
14901     */
14902    @RemotableViewMethod
14903    public void setBackgroundColor(int color) {
14904        if (mBackground instanceof ColorDrawable) {
14905            ((ColorDrawable) mBackground.mutate()).setColor(color);
14906            computeOpaqueFlags();
14907            mBackgroundResource = 0;
14908        } else {
14909            setBackground(new ColorDrawable(color));
14910        }
14911    }
14912
14913    /**
14914     * Set the background to a given resource. The resource should refer to
14915     * a Drawable object or 0 to remove the background.
14916     * @param resid The identifier of the resource.
14917     *
14918     * @attr ref android.R.styleable#View_background
14919     */
14920    @RemotableViewMethod
14921    public void setBackgroundResource(int resid) {
14922        if (resid != 0 && resid == mBackgroundResource) {
14923            return;
14924        }
14925
14926        Drawable d= null;
14927        if (resid != 0) {
14928            d = mResources.getDrawable(resid);
14929        }
14930        setBackground(d);
14931
14932        mBackgroundResource = resid;
14933    }
14934
14935    /**
14936     * Set the background to a given Drawable, or remove the background. If the
14937     * background has padding, this View's padding is set to the background's
14938     * padding. However, when a background is removed, this View's padding isn't
14939     * touched. If setting the padding is desired, please use
14940     * {@link #setPadding(int, int, int, int)}.
14941     *
14942     * @param background The Drawable to use as the background, or null to remove the
14943     *        background
14944     */
14945    public void setBackground(Drawable background) {
14946        //noinspection deprecation
14947        setBackgroundDrawable(background);
14948    }
14949
14950    /**
14951     * @deprecated use {@link #setBackground(Drawable)} instead
14952     */
14953    @Deprecated
14954    public void setBackgroundDrawable(Drawable background) {
14955        computeOpaqueFlags();
14956
14957        if (background == mBackground) {
14958            return;
14959        }
14960
14961        boolean requestLayout = false;
14962
14963        mBackgroundResource = 0;
14964
14965        /*
14966         * Regardless of whether we're setting a new background or not, we want
14967         * to clear the previous drawable.
14968         */
14969        if (mBackground != null) {
14970            mBackground.setCallback(null);
14971            unscheduleDrawable(mBackground);
14972        }
14973
14974        if (background != null) {
14975            Rect padding = sThreadLocal.get();
14976            if (padding == null) {
14977                padding = new Rect();
14978                sThreadLocal.set(padding);
14979            }
14980            resetResolvedDrawables();
14981            background.setLayoutDirection(getLayoutDirection());
14982            if (background.getPadding(padding)) {
14983                resetResolvedPadding();
14984                switch (background.getLayoutDirection()) {
14985                    case LAYOUT_DIRECTION_RTL:
14986                        mUserPaddingLeftInitial = padding.right;
14987                        mUserPaddingRightInitial = padding.left;
14988                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
14989                        break;
14990                    case LAYOUT_DIRECTION_LTR:
14991                    default:
14992                        mUserPaddingLeftInitial = padding.left;
14993                        mUserPaddingRightInitial = padding.right;
14994                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
14995                }
14996            }
14997
14998            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
14999            // if it has a different minimum size, we should layout again
15000            if (mBackground == null || mBackground.getMinimumHeight() != background.getMinimumHeight() ||
15001                    mBackground.getMinimumWidth() != background.getMinimumWidth()) {
15002                requestLayout = true;
15003            }
15004
15005            background.setCallback(this);
15006            if (background.isStateful()) {
15007                background.setState(getDrawableState());
15008            }
15009            background.setVisible(getVisibility() == VISIBLE, false);
15010            mBackground = background;
15011
15012            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
15013                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
15014                mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
15015                requestLayout = true;
15016            }
15017        } else {
15018            /* Remove the background */
15019            mBackground = null;
15020
15021            if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) {
15022                /*
15023                 * This view ONLY drew the background before and we're removing
15024                 * the background, so now it won't draw anything
15025                 * (hence we SKIP_DRAW)
15026                 */
15027                mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND;
15028                mPrivateFlags |= PFLAG_SKIP_DRAW;
15029            }
15030
15031            /*
15032             * When the background is set, we try to apply its padding to this
15033             * View. When the background is removed, we don't touch this View's
15034             * padding. This is noted in the Javadocs. Hence, we don't need to
15035             * requestLayout(), the invalidate() below is sufficient.
15036             */
15037
15038            // The old background's minimum size could have affected this
15039            // View's layout, so let's requestLayout
15040            requestLayout = true;
15041        }
15042
15043        computeOpaqueFlags();
15044
15045        if (requestLayout) {
15046            requestLayout();
15047        }
15048
15049        mBackgroundSizeChanged = true;
15050        invalidate(true);
15051    }
15052
15053    /**
15054     * Gets the background drawable
15055     *
15056     * @return The drawable used as the background for this view, if any.
15057     *
15058     * @see #setBackground(Drawable)
15059     *
15060     * @attr ref android.R.styleable#View_background
15061     */
15062    public Drawable getBackground() {
15063        return mBackground;
15064    }
15065
15066    /**
15067     * Sets the padding. The view may add on the space required to display
15068     * the scrollbars, depending on the style and visibility of the scrollbars.
15069     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
15070     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
15071     * from the values set in this call.
15072     *
15073     * @attr ref android.R.styleable#View_padding
15074     * @attr ref android.R.styleable#View_paddingBottom
15075     * @attr ref android.R.styleable#View_paddingLeft
15076     * @attr ref android.R.styleable#View_paddingRight
15077     * @attr ref android.R.styleable#View_paddingTop
15078     * @param left the left padding in pixels
15079     * @param top the top padding in pixels
15080     * @param right the right padding in pixels
15081     * @param bottom the bottom padding in pixels
15082     */
15083    public void setPadding(int left, int top, int right, int bottom) {
15084        resetResolvedPadding();
15085
15086        mUserPaddingStart = UNDEFINED_PADDING;
15087        mUserPaddingEnd = UNDEFINED_PADDING;
15088
15089        mUserPaddingLeftInitial = left;
15090        mUserPaddingRightInitial = right;
15091
15092        internalSetPadding(left, top, right, bottom);
15093    }
15094
15095    /**
15096     * @hide
15097     */
15098    protected void internalSetPadding(int left, int top, int right, int bottom) {
15099        mUserPaddingLeft = left;
15100        mUserPaddingRight = right;
15101        mUserPaddingBottom = bottom;
15102
15103        final int viewFlags = mViewFlags;
15104        boolean changed = false;
15105
15106        // Common case is there are no scroll bars.
15107        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
15108            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
15109                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
15110                        ? 0 : getVerticalScrollbarWidth();
15111                switch (mVerticalScrollbarPosition) {
15112                    case SCROLLBAR_POSITION_DEFAULT:
15113                        if (isLayoutRtl()) {
15114                            left += offset;
15115                        } else {
15116                            right += offset;
15117                        }
15118                        break;
15119                    case SCROLLBAR_POSITION_RIGHT:
15120                        right += offset;
15121                        break;
15122                    case SCROLLBAR_POSITION_LEFT:
15123                        left += offset;
15124                        break;
15125                }
15126            }
15127            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
15128                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
15129                        ? 0 : getHorizontalScrollbarHeight();
15130            }
15131        }
15132
15133        if (mPaddingLeft != left) {
15134            changed = true;
15135            mPaddingLeft = left;
15136        }
15137        if (mPaddingTop != top) {
15138            changed = true;
15139            mPaddingTop = top;
15140        }
15141        if (mPaddingRight != right) {
15142            changed = true;
15143            mPaddingRight = right;
15144        }
15145        if (mPaddingBottom != bottom) {
15146            changed = true;
15147            mPaddingBottom = bottom;
15148        }
15149
15150        if (changed) {
15151            requestLayout();
15152        }
15153    }
15154
15155    /**
15156     * Sets the relative padding. The view may add on the space required to display
15157     * the scrollbars, depending on the style and visibility of the scrollbars.
15158     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
15159     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
15160     * from the values set in this call.
15161     *
15162     * @attr ref android.R.styleable#View_padding
15163     * @attr ref android.R.styleable#View_paddingBottom
15164     * @attr ref android.R.styleable#View_paddingStart
15165     * @attr ref android.R.styleable#View_paddingEnd
15166     * @attr ref android.R.styleable#View_paddingTop
15167     * @param start the start padding in pixels
15168     * @param top the top padding in pixels
15169     * @param end the end padding in pixels
15170     * @param bottom the bottom padding in pixels
15171     */
15172    public void setPaddingRelative(int start, int top, int end, int bottom) {
15173        resetResolvedPadding();
15174
15175        mUserPaddingStart = start;
15176        mUserPaddingEnd = end;
15177
15178        switch(getLayoutDirection()) {
15179            case LAYOUT_DIRECTION_RTL:
15180                mUserPaddingLeftInitial = end;
15181                mUserPaddingRightInitial = start;
15182                internalSetPadding(end, top, start, bottom);
15183                break;
15184            case LAYOUT_DIRECTION_LTR:
15185            default:
15186                mUserPaddingLeftInitial = start;
15187                mUserPaddingRightInitial = end;
15188                internalSetPadding(start, top, end, bottom);
15189        }
15190    }
15191
15192    /**
15193     * Returns the top padding of this view.
15194     *
15195     * @return the top padding in pixels
15196     */
15197    public int getPaddingTop() {
15198        return mPaddingTop;
15199    }
15200
15201    /**
15202     * Returns the bottom padding of this view. If there are inset and enabled
15203     * scrollbars, this value may include the space required to display the
15204     * scrollbars as well.
15205     *
15206     * @return the bottom padding in pixels
15207     */
15208    public int getPaddingBottom() {
15209        return mPaddingBottom;
15210    }
15211
15212    /**
15213     * Returns the left padding of this view. If there are inset and enabled
15214     * scrollbars, this value may include the space required to display the
15215     * scrollbars as well.
15216     *
15217     * @return the left padding in pixels
15218     */
15219    public int getPaddingLeft() {
15220        if (!isPaddingResolved()) {
15221            resolvePadding();
15222        }
15223        return mPaddingLeft;
15224    }
15225
15226    /**
15227     * Returns the start padding of this view depending on its resolved layout direction.
15228     * If there are inset and enabled scrollbars, this value may include the space
15229     * required to display the scrollbars as well.
15230     *
15231     * @return the start padding in pixels
15232     */
15233    public int getPaddingStart() {
15234        if (!isPaddingResolved()) {
15235            resolvePadding();
15236        }
15237        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
15238                mPaddingRight : mPaddingLeft;
15239    }
15240
15241    /**
15242     * Returns the right padding of this view. If there are inset and enabled
15243     * scrollbars, this value may include the space required to display the
15244     * scrollbars as well.
15245     *
15246     * @return the right padding in pixels
15247     */
15248    public int getPaddingRight() {
15249        if (!isPaddingResolved()) {
15250            resolvePadding();
15251        }
15252        return mPaddingRight;
15253    }
15254
15255    /**
15256     * Returns the end padding of this view depending on its resolved layout direction.
15257     * If there are inset and enabled scrollbars, this value may include the space
15258     * required to display the scrollbars as well.
15259     *
15260     * @return the end padding in pixels
15261     */
15262    public int getPaddingEnd() {
15263        if (!isPaddingResolved()) {
15264            resolvePadding();
15265        }
15266        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
15267                mPaddingLeft : mPaddingRight;
15268    }
15269
15270    /**
15271     * Return if the padding as been set thru relative values
15272     * {@link #setPaddingRelative(int, int, int, int)} or thru
15273     * @attr ref android.R.styleable#View_paddingStart or
15274     * @attr ref android.R.styleable#View_paddingEnd
15275     *
15276     * @return true if the padding is relative or false if it is not.
15277     */
15278    public boolean isPaddingRelative() {
15279        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
15280    }
15281
15282    Insets computeOpticalInsets() {
15283        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
15284    }
15285
15286    /**
15287     * @hide
15288     */
15289    public void resetPaddingToInitialValues() {
15290        if (isRtlCompatibilityMode()) {
15291            mPaddingLeft = mUserPaddingLeftInitial;
15292            mPaddingRight = mUserPaddingRightInitial;
15293            return;
15294        }
15295        if (isLayoutRtl()) {
15296            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
15297            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
15298        } else {
15299            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
15300            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
15301        }
15302    }
15303
15304    /**
15305     * @hide
15306     */
15307    public Insets getOpticalInsets() {
15308        if (mLayoutInsets == null) {
15309            mLayoutInsets = computeOpticalInsets();
15310        }
15311        return mLayoutInsets;
15312    }
15313
15314    /**
15315     * Changes the selection state of this view. A view can be selected or not.
15316     * Note that selection is not the same as focus. Views are typically
15317     * selected in the context of an AdapterView like ListView or GridView;
15318     * the selected view is the view that is highlighted.
15319     *
15320     * @param selected true if the view must be selected, false otherwise
15321     */
15322    public void setSelected(boolean selected) {
15323        //noinspection DoubleNegation
15324        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
15325            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
15326            if (!selected) resetPressedState();
15327            invalidate(true);
15328            refreshDrawableState();
15329            dispatchSetSelected(selected);
15330            notifyViewAccessibilityStateChangedIfNeeded();
15331        }
15332    }
15333
15334    /**
15335     * Dispatch setSelected to all of this View's children.
15336     *
15337     * @see #setSelected(boolean)
15338     *
15339     * @param selected The new selected state
15340     */
15341    protected void dispatchSetSelected(boolean selected) {
15342    }
15343
15344    /**
15345     * Indicates the selection state of this view.
15346     *
15347     * @return true if the view is selected, false otherwise
15348     */
15349    @ViewDebug.ExportedProperty
15350    public boolean isSelected() {
15351        return (mPrivateFlags & PFLAG_SELECTED) != 0;
15352    }
15353
15354    /**
15355     * Changes the activated state of this view. A view can be activated or not.
15356     * Note that activation is not the same as selection.  Selection is
15357     * a transient property, representing the view (hierarchy) the user is
15358     * currently interacting with.  Activation is a longer-term state that the
15359     * user can move views in and out of.  For example, in a list view with
15360     * single or multiple selection enabled, the views in the current selection
15361     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
15362     * here.)  The activated state is propagated down to children of the view it
15363     * is set on.
15364     *
15365     * @param activated true if the view must be activated, false otherwise
15366     */
15367    public void setActivated(boolean activated) {
15368        //noinspection DoubleNegation
15369        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
15370            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
15371            invalidate(true);
15372            refreshDrawableState();
15373            dispatchSetActivated(activated);
15374        }
15375    }
15376
15377    /**
15378     * Dispatch setActivated to all of this View's children.
15379     *
15380     * @see #setActivated(boolean)
15381     *
15382     * @param activated The new activated state
15383     */
15384    protected void dispatchSetActivated(boolean activated) {
15385    }
15386
15387    /**
15388     * Indicates the activation state of this view.
15389     *
15390     * @return true if the view is activated, false otherwise
15391     */
15392    @ViewDebug.ExportedProperty
15393    public boolean isActivated() {
15394        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
15395    }
15396
15397    /**
15398     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
15399     * observer can be used to get notifications when global events, like
15400     * layout, happen.
15401     *
15402     * The returned ViewTreeObserver observer is not guaranteed to remain
15403     * valid for the lifetime of this View. If the caller of this method keeps
15404     * a long-lived reference to ViewTreeObserver, it should always check for
15405     * the return value of {@link ViewTreeObserver#isAlive()}.
15406     *
15407     * @return The ViewTreeObserver for this view's hierarchy.
15408     */
15409    public ViewTreeObserver getViewTreeObserver() {
15410        if (mAttachInfo != null) {
15411            return mAttachInfo.mTreeObserver;
15412        }
15413        if (mFloatingTreeObserver == null) {
15414            mFloatingTreeObserver = new ViewTreeObserver();
15415        }
15416        return mFloatingTreeObserver;
15417    }
15418
15419    /**
15420     * <p>Finds the topmost view in the current view hierarchy.</p>
15421     *
15422     * @return the topmost view containing this view
15423     */
15424    public View getRootView() {
15425        if (mAttachInfo != null) {
15426            final View v = mAttachInfo.mRootView;
15427            if (v != null) {
15428                return v;
15429            }
15430        }
15431
15432        View parent = this;
15433
15434        while (parent.mParent != null && parent.mParent instanceof View) {
15435            parent = (View) parent.mParent;
15436        }
15437
15438        return parent;
15439    }
15440
15441    /**
15442     * <p>Computes the coordinates of this view on the screen. The argument
15443     * must be an array of two integers. After the method returns, the array
15444     * contains the x and y location in that order.</p>
15445     *
15446     * @param location an array of two integers in which to hold the coordinates
15447     */
15448    public void getLocationOnScreen(int[] location) {
15449        getLocationInWindow(location);
15450
15451        final AttachInfo info = mAttachInfo;
15452        if (info != null) {
15453            location[0] += info.mWindowLeft;
15454            location[1] += info.mWindowTop;
15455        }
15456    }
15457
15458    /**
15459     * <p>Computes the coordinates of this view in its window. The argument
15460     * must be an array of two integers. After the method returns, the array
15461     * contains the x and y location in that order.</p>
15462     *
15463     * @param location an array of two integers in which to hold the coordinates
15464     */
15465    public void getLocationInWindow(int[] location) {
15466        if (location == null || location.length < 2) {
15467            throw new IllegalArgumentException("location must be an array of two integers");
15468        }
15469
15470        if (mAttachInfo == null) {
15471            // When the view is not attached to a window, this method does not make sense
15472            location[0] = location[1] = 0;
15473            return;
15474        }
15475
15476        float[] position = mAttachInfo.mTmpTransformLocation;
15477        position[0] = position[1] = 0.0f;
15478
15479        if (!hasIdentityMatrix()) {
15480            getMatrix().mapPoints(position);
15481        }
15482
15483        position[0] += mLeft;
15484        position[1] += mTop;
15485
15486        ViewParent viewParent = mParent;
15487        while (viewParent instanceof View) {
15488            final View view = (View) viewParent;
15489
15490            position[0] -= view.mScrollX;
15491            position[1] -= view.mScrollY;
15492
15493            if (!view.hasIdentityMatrix()) {
15494                view.getMatrix().mapPoints(position);
15495            }
15496
15497            position[0] += view.mLeft;
15498            position[1] += view.mTop;
15499
15500            viewParent = view.mParent;
15501         }
15502
15503        if (viewParent instanceof ViewRootImpl) {
15504            // *cough*
15505            final ViewRootImpl vr = (ViewRootImpl) viewParent;
15506            position[1] -= vr.mCurScrollY;
15507        }
15508
15509        location[0] = (int) (position[0] + 0.5f);
15510        location[1] = (int) (position[1] + 0.5f);
15511    }
15512
15513    /**
15514     * {@hide}
15515     * @param id the id of the view to be found
15516     * @return the view of the specified id, null if cannot be found
15517     */
15518    protected View findViewTraversal(int id) {
15519        if (id == mID) {
15520            return this;
15521        }
15522        return null;
15523    }
15524
15525    /**
15526     * {@hide}
15527     * @param tag the tag of the view to be found
15528     * @return the view of specified tag, null if cannot be found
15529     */
15530    protected View findViewWithTagTraversal(Object tag) {
15531        if (tag != null && tag.equals(mTag)) {
15532            return this;
15533        }
15534        return null;
15535    }
15536
15537    /**
15538     * {@hide}
15539     * @param predicate The predicate to evaluate.
15540     * @param childToSkip If not null, ignores this child during the recursive traversal.
15541     * @return The first view that matches the predicate or null.
15542     */
15543    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
15544        if (predicate.apply(this)) {
15545            return this;
15546        }
15547        return null;
15548    }
15549
15550    /**
15551     * Look for a child view with the given id.  If this view has the given
15552     * id, return this view.
15553     *
15554     * @param id The id to search for.
15555     * @return The view that has the given id in the hierarchy or null
15556     */
15557    public final View findViewById(int id) {
15558        if (id < 0) {
15559            return null;
15560        }
15561        return findViewTraversal(id);
15562    }
15563
15564    /**
15565     * Finds a view by its unuque and stable accessibility id.
15566     *
15567     * @param accessibilityId The searched accessibility id.
15568     * @return The found view.
15569     */
15570    final View findViewByAccessibilityId(int accessibilityId) {
15571        if (accessibilityId < 0) {
15572            return null;
15573        }
15574        return findViewByAccessibilityIdTraversal(accessibilityId);
15575    }
15576
15577    /**
15578     * Performs the traversal to find a view by its unuque and stable accessibility id.
15579     *
15580     * <strong>Note:</strong>This method does not stop at the root namespace
15581     * boundary since the user can touch the screen at an arbitrary location
15582     * potentially crossing the root namespace bounday which will send an
15583     * accessibility event to accessibility services and they should be able
15584     * to obtain the event source. Also accessibility ids are guaranteed to be
15585     * unique in the window.
15586     *
15587     * @param accessibilityId The accessibility id.
15588     * @return The found view.
15589     *
15590     * @hide
15591     */
15592    public View findViewByAccessibilityIdTraversal(int accessibilityId) {
15593        if (getAccessibilityViewId() == accessibilityId) {
15594            return this;
15595        }
15596        return null;
15597    }
15598
15599    /**
15600     * Look for a child view with the given tag.  If this view has the given
15601     * tag, return this view.
15602     *
15603     * @param tag The tag to search for, using "tag.equals(getTag())".
15604     * @return The View that has the given tag in the hierarchy or null
15605     */
15606    public final View findViewWithTag(Object tag) {
15607        if (tag == null) {
15608            return null;
15609        }
15610        return findViewWithTagTraversal(tag);
15611    }
15612
15613    /**
15614     * {@hide}
15615     * Look for a child view that matches the specified predicate.
15616     * If this view matches the predicate, return this view.
15617     *
15618     * @param predicate The predicate to evaluate.
15619     * @return The first view that matches the predicate or null.
15620     */
15621    public final View findViewByPredicate(Predicate<View> predicate) {
15622        return findViewByPredicateTraversal(predicate, null);
15623    }
15624
15625    /**
15626     * {@hide}
15627     * Look for a child view that matches the specified predicate,
15628     * starting with the specified view and its descendents and then
15629     * recusively searching the ancestors and siblings of that view
15630     * until this view is reached.
15631     *
15632     * This method is useful in cases where the predicate does not match
15633     * a single unique view (perhaps multiple views use the same id)
15634     * and we are trying to find the view that is "closest" in scope to the
15635     * starting view.
15636     *
15637     * @param start The view to start from.
15638     * @param predicate The predicate to evaluate.
15639     * @return The first view that matches the predicate or null.
15640     */
15641    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
15642        View childToSkip = null;
15643        for (;;) {
15644            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
15645            if (view != null || start == this) {
15646                return view;
15647            }
15648
15649            ViewParent parent = start.getParent();
15650            if (parent == null || !(parent instanceof View)) {
15651                return null;
15652            }
15653
15654            childToSkip = start;
15655            start = (View) parent;
15656        }
15657    }
15658
15659    /**
15660     * Sets the identifier for this view. The identifier does not have to be
15661     * unique in this view's hierarchy. The identifier should be a positive
15662     * number.
15663     *
15664     * @see #NO_ID
15665     * @see #getId()
15666     * @see #findViewById(int)
15667     *
15668     * @param id a number used to identify the view
15669     *
15670     * @attr ref android.R.styleable#View_id
15671     */
15672    public void setId(int id) {
15673        mID = id;
15674        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
15675            mID = generateViewId();
15676        }
15677    }
15678
15679    /**
15680     * {@hide}
15681     *
15682     * @param isRoot true if the view belongs to the root namespace, false
15683     *        otherwise
15684     */
15685    public void setIsRootNamespace(boolean isRoot) {
15686        if (isRoot) {
15687            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
15688        } else {
15689            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
15690        }
15691    }
15692
15693    /**
15694     * {@hide}
15695     *
15696     * @return true if the view belongs to the root namespace, false otherwise
15697     */
15698    public boolean isRootNamespace() {
15699        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
15700    }
15701
15702    /**
15703     * Returns this view's identifier.
15704     *
15705     * @return a positive integer used to identify the view or {@link #NO_ID}
15706     *         if the view has no ID
15707     *
15708     * @see #setId(int)
15709     * @see #findViewById(int)
15710     * @attr ref android.R.styleable#View_id
15711     */
15712    @ViewDebug.CapturedViewProperty
15713    public int getId() {
15714        return mID;
15715    }
15716
15717    /**
15718     * Returns this view's tag.
15719     *
15720     * @return the Object stored in this view as a tag
15721     *
15722     * @see #setTag(Object)
15723     * @see #getTag(int)
15724     */
15725    @ViewDebug.ExportedProperty
15726    public Object getTag() {
15727        return mTag;
15728    }
15729
15730    /**
15731     * Sets the tag associated with this view. A tag can be used to mark
15732     * a view in its hierarchy and does not have to be unique within the
15733     * hierarchy. Tags can also be used to store data within a view without
15734     * resorting to another data structure.
15735     *
15736     * @param tag an Object to tag the view with
15737     *
15738     * @see #getTag()
15739     * @see #setTag(int, Object)
15740     */
15741    public void setTag(final Object tag) {
15742        mTag = tag;
15743    }
15744
15745    /**
15746     * Returns the tag associated with this view and the specified key.
15747     *
15748     * @param key The key identifying the tag
15749     *
15750     * @return the Object stored in this view as a tag
15751     *
15752     * @see #setTag(int, Object)
15753     * @see #getTag()
15754     */
15755    public Object getTag(int key) {
15756        if (mKeyedTags != null) return mKeyedTags.get(key);
15757        return null;
15758    }
15759
15760    /**
15761     * Sets a tag associated with this view and a key. A tag can be used
15762     * to mark a view in its hierarchy and does not have to be unique within
15763     * the hierarchy. Tags can also be used to store data within a view
15764     * without resorting to another data structure.
15765     *
15766     * The specified key should be an id declared in the resources of the
15767     * application to ensure it is unique (see the <a
15768     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
15769     * Keys identified as belonging to
15770     * the Android framework or not associated with any package will cause
15771     * an {@link IllegalArgumentException} to be thrown.
15772     *
15773     * @param key The key identifying the tag
15774     * @param tag An Object to tag the view with
15775     *
15776     * @throws IllegalArgumentException If they specified key is not valid
15777     *
15778     * @see #setTag(Object)
15779     * @see #getTag(int)
15780     */
15781    public void setTag(int key, final Object tag) {
15782        // If the package id is 0x00 or 0x01, it's either an undefined package
15783        // or a framework id
15784        if ((key >>> 24) < 2) {
15785            throw new IllegalArgumentException("The key must be an application-specific "
15786                    + "resource id.");
15787        }
15788
15789        setKeyedTag(key, tag);
15790    }
15791
15792    /**
15793     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
15794     * framework id.
15795     *
15796     * @hide
15797     */
15798    public void setTagInternal(int key, Object tag) {
15799        if ((key >>> 24) != 0x1) {
15800            throw new IllegalArgumentException("The key must be a framework-specific "
15801                    + "resource id.");
15802        }
15803
15804        setKeyedTag(key, tag);
15805    }
15806
15807    private void setKeyedTag(int key, Object tag) {
15808        if (mKeyedTags == null) {
15809            mKeyedTags = new SparseArray<Object>(2);
15810        }
15811
15812        mKeyedTags.put(key, tag);
15813    }
15814
15815    /**
15816     * Prints information about this view in the log output, with the tag
15817     * {@link #VIEW_LOG_TAG}.
15818     *
15819     * @hide
15820     */
15821    public void debug() {
15822        debug(0);
15823    }
15824
15825    /**
15826     * Prints information about this view in the log output, with the tag
15827     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
15828     * indentation defined by the <code>depth</code>.
15829     *
15830     * @param depth the indentation level
15831     *
15832     * @hide
15833     */
15834    protected void debug(int depth) {
15835        String output = debugIndent(depth - 1);
15836
15837        output += "+ " + this;
15838        int id = getId();
15839        if (id != -1) {
15840            output += " (id=" + id + ")";
15841        }
15842        Object tag = getTag();
15843        if (tag != null) {
15844            output += " (tag=" + tag + ")";
15845        }
15846        Log.d(VIEW_LOG_TAG, output);
15847
15848        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
15849            output = debugIndent(depth) + " FOCUSED";
15850            Log.d(VIEW_LOG_TAG, output);
15851        }
15852
15853        output = debugIndent(depth);
15854        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
15855                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
15856                + "} ";
15857        Log.d(VIEW_LOG_TAG, output);
15858
15859        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
15860                || mPaddingBottom != 0) {
15861            output = debugIndent(depth);
15862            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
15863                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
15864            Log.d(VIEW_LOG_TAG, output);
15865        }
15866
15867        output = debugIndent(depth);
15868        output += "mMeasureWidth=" + mMeasuredWidth +
15869                " mMeasureHeight=" + mMeasuredHeight;
15870        Log.d(VIEW_LOG_TAG, output);
15871
15872        output = debugIndent(depth);
15873        if (mLayoutParams == null) {
15874            output += "BAD! no layout params";
15875        } else {
15876            output = mLayoutParams.debug(output);
15877        }
15878        Log.d(VIEW_LOG_TAG, output);
15879
15880        output = debugIndent(depth);
15881        output += "flags={";
15882        output += View.printFlags(mViewFlags);
15883        output += "}";
15884        Log.d(VIEW_LOG_TAG, output);
15885
15886        output = debugIndent(depth);
15887        output += "privateFlags={";
15888        output += View.printPrivateFlags(mPrivateFlags);
15889        output += "}";
15890        Log.d(VIEW_LOG_TAG, output);
15891    }
15892
15893    /**
15894     * Creates a string of whitespaces used for indentation.
15895     *
15896     * @param depth the indentation level
15897     * @return a String containing (depth * 2 + 3) * 2 white spaces
15898     *
15899     * @hide
15900     */
15901    protected static String debugIndent(int depth) {
15902        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
15903        for (int i = 0; i < (depth * 2) + 3; i++) {
15904            spaces.append(' ').append(' ');
15905        }
15906        return spaces.toString();
15907    }
15908
15909    /**
15910     * <p>Return the offset of the widget's text baseline from the widget's top
15911     * boundary. If this widget does not support baseline alignment, this
15912     * method returns -1. </p>
15913     *
15914     * @return the offset of the baseline within the widget's bounds or -1
15915     *         if baseline alignment is not supported
15916     */
15917    @ViewDebug.ExportedProperty(category = "layout")
15918    public int getBaseline() {
15919        return -1;
15920    }
15921
15922    /**
15923     * Returns whether the view hierarchy is currently undergoing a layout pass. This
15924     * information is useful to avoid situations such as calling {@link #requestLayout()} during
15925     * a layout pass.
15926     *
15927     * @return whether the view hierarchy is currently undergoing a layout pass
15928     */
15929    public boolean isInLayout() {
15930        ViewRootImpl viewRoot = getViewRootImpl();
15931        return (viewRoot != null && viewRoot.isInLayout());
15932    }
15933
15934    /**
15935     * Call this when something has changed which has invalidated the
15936     * layout of this view. This will schedule a layout pass of the view
15937     * tree. This should not be called while the view hierarchy is currently in a layout
15938     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
15939     * end of the current layout pass (and then layout will run again) or after the current
15940     * frame is drawn and the next layout occurs.
15941     *
15942     * <p>Subclasses which override this method should call the superclass method to
15943     * handle possible request-during-layout errors correctly.</p>
15944     */
15945    public void requestLayout() {
15946        if (mMeasureCache != null) mMeasureCache.clear();
15947
15948        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
15949            // Only trigger request-during-layout logic if this is the view requesting it,
15950            // not the views in its parent hierarchy
15951            ViewRootImpl viewRoot = getViewRootImpl();
15952            if (viewRoot != null && viewRoot.isInLayout()) {
15953                if (!viewRoot.requestLayoutDuringLayout(this)) {
15954                    return;
15955                }
15956            }
15957            mAttachInfo.mViewRequestingLayout = this;
15958        }
15959
15960        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
15961        mPrivateFlags |= PFLAG_INVALIDATED;
15962
15963        if (mParent != null && !mParent.isLayoutRequested()) {
15964            mParent.requestLayout();
15965        }
15966        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
15967            mAttachInfo.mViewRequestingLayout = null;
15968        }
15969    }
15970
15971    /**
15972     * Forces this view to be laid out during the next layout pass.
15973     * This method does not call requestLayout() or forceLayout()
15974     * on the parent.
15975     */
15976    public void forceLayout() {
15977        if (mMeasureCache != null) mMeasureCache.clear();
15978
15979        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
15980        mPrivateFlags |= PFLAG_INVALIDATED;
15981    }
15982
15983    /**
15984     * <p>
15985     * This is called to find out how big a view should be. The parent
15986     * supplies constraint information in the width and height parameters.
15987     * </p>
15988     *
15989     * <p>
15990     * The actual measurement work of a view is performed in
15991     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
15992     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
15993     * </p>
15994     *
15995     *
15996     * @param widthMeasureSpec Horizontal space requirements as imposed by the
15997     *        parent
15998     * @param heightMeasureSpec Vertical space requirements as imposed by the
15999     *        parent
16000     *
16001     * @see #onMeasure(int, int)
16002     */
16003    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
16004        boolean optical = isLayoutModeOptical(this);
16005        if (optical != isLayoutModeOptical(mParent)) {
16006            Insets insets = getOpticalInsets();
16007            int oWidth  = insets.left + insets.right;
16008            int oHeight = insets.top  + insets.bottom;
16009            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
16010            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
16011        }
16012
16013        // Suppress sign extension for the low bytes
16014        long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
16015        if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
16016
16017        if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ||
16018                widthMeasureSpec != mOldWidthMeasureSpec ||
16019                heightMeasureSpec != mOldHeightMeasureSpec) {
16020
16021            // first clears the measured dimension flag
16022            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
16023
16024            resolveRtlPropertiesIfNeeded();
16025
16026            int cacheIndex = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ? -1 :
16027                    mMeasureCache.indexOfKey(key);
16028            if (cacheIndex < 0) {
16029                // measure ourselves, this should set the measured dimension flag back
16030                onMeasure(widthMeasureSpec, heightMeasureSpec);
16031                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
16032            } else {
16033                long value = mMeasureCache.valueAt(cacheIndex);
16034                // Casting a long to int drops the high 32 bits, no mask needed
16035                setMeasuredDimension((int) (value >> 32), (int) value);
16036                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
16037            }
16038
16039            // flag not set, setMeasuredDimension() was not invoked, we raise
16040            // an exception to warn the developer
16041            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
16042                throw new IllegalStateException("onMeasure() did not set the"
16043                        + " measured dimension by calling"
16044                        + " setMeasuredDimension()");
16045            }
16046
16047            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
16048        }
16049
16050        mOldWidthMeasureSpec = widthMeasureSpec;
16051        mOldHeightMeasureSpec = heightMeasureSpec;
16052
16053        mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
16054                (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
16055    }
16056
16057    /**
16058     * <p>
16059     * Measure the view and its content to determine the measured width and the
16060     * measured height. This method is invoked by {@link #measure(int, int)} and
16061     * should be overriden by subclasses to provide accurate and efficient
16062     * measurement of their contents.
16063     * </p>
16064     *
16065     * <p>
16066     * <strong>CONTRACT:</strong> When overriding this method, you
16067     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
16068     * measured width and height of this view. Failure to do so will trigger an
16069     * <code>IllegalStateException</code>, thrown by
16070     * {@link #measure(int, int)}. Calling the superclass'
16071     * {@link #onMeasure(int, int)} is a valid use.
16072     * </p>
16073     *
16074     * <p>
16075     * The base class implementation of measure defaults to the background size,
16076     * unless a larger size is allowed by the MeasureSpec. Subclasses should
16077     * override {@link #onMeasure(int, int)} to provide better measurements of
16078     * their content.
16079     * </p>
16080     *
16081     * <p>
16082     * If this method is overridden, it is the subclass's responsibility to make
16083     * sure the measured height and width are at least the view's minimum height
16084     * and width ({@link #getSuggestedMinimumHeight()} and
16085     * {@link #getSuggestedMinimumWidth()}).
16086     * </p>
16087     *
16088     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
16089     *                         The requirements are encoded with
16090     *                         {@link android.view.View.MeasureSpec}.
16091     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
16092     *                         The requirements are encoded with
16093     *                         {@link android.view.View.MeasureSpec}.
16094     *
16095     * @see #getMeasuredWidth()
16096     * @see #getMeasuredHeight()
16097     * @see #setMeasuredDimension(int, int)
16098     * @see #getSuggestedMinimumHeight()
16099     * @see #getSuggestedMinimumWidth()
16100     * @see android.view.View.MeasureSpec#getMode(int)
16101     * @see android.view.View.MeasureSpec#getSize(int)
16102     */
16103    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
16104        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
16105                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
16106    }
16107
16108    /**
16109     * <p>This method must be called by {@link #onMeasure(int, int)} to store the
16110     * measured width and measured height. Failing to do so will trigger an
16111     * exception at measurement time.</p>
16112     *
16113     * @param measuredWidth The measured width of this view.  May be a complex
16114     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
16115     * {@link #MEASURED_STATE_TOO_SMALL}.
16116     * @param measuredHeight The measured height of this view.  May be a complex
16117     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
16118     * {@link #MEASURED_STATE_TOO_SMALL}.
16119     */
16120    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
16121        boolean optical = isLayoutModeOptical(this);
16122        if (optical != isLayoutModeOptical(mParent)) {
16123            Insets insets = getOpticalInsets();
16124            int opticalWidth  = insets.left + insets.right;
16125            int opticalHeight = insets.top  + insets.bottom;
16126
16127            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
16128            measuredHeight += optical ? opticalHeight : -opticalHeight;
16129        }
16130        mMeasuredWidth = measuredWidth;
16131        mMeasuredHeight = measuredHeight;
16132
16133        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
16134    }
16135
16136    /**
16137     * Merge two states as returned by {@link #getMeasuredState()}.
16138     * @param curState The current state as returned from a view or the result
16139     * of combining multiple views.
16140     * @param newState The new view state to combine.
16141     * @return Returns a new integer reflecting the combination of the two
16142     * states.
16143     */
16144    public static int combineMeasuredStates(int curState, int newState) {
16145        return curState | newState;
16146    }
16147
16148    /**
16149     * Version of {@link #resolveSizeAndState(int, int, int)}
16150     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
16151     */
16152    public static int resolveSize(int size, int measureSpec) {
16153        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
16154    }
16155
16156    /**
16157     * Utility to reconcile a desired size and state, with constraints imposed
16158     * by a MeasureSpec.  Will take the desired size, unless a different size
16159     * is imposed by the constraints.  The returned value is a compound integer,
16160     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
16161     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
16162     * size is smaller than the size the view wants to be.
16163     *
16164     * @param size How big the view wants to be
16165     * @param measureSpec Constraints imposed by the parent
16166     * @return Size information bit mask as defined by
16167     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
16168     */
16169    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
16170        int result = size;
16171        int specMode = MeasureSpec.getMode(measureSpec);
16172        int specSize =  MeasureSpec.getSize(measureSpec);
16173        switch (specMode) {
16174        case MeasureSpec.UNSPECIFIED:
16175            result = size;
16176            break;
16177        case MeasureSpec.AT_MOST:
16178            if (specSize < size) {
16179                result = specSize | MEASURED_STATE_TOO_SMALL;
16180            } else {
16181                result = size;
16182            }
16183            break;
16184        case MeasureSpec.EXACTLY:
16185            result = specSize;
16186            break;
16187        }
16188        return result | (childMeasuredState&MEASURED_STATE_MASK);
16189    }
16190
16191    /**
16192     * Utility to return a default size. Uses the supplied size if the
16193     * MeasureSpec imposed no constraints. Will get larger if allowed
16194     * by the MeasureSpec.
16195     *
16196     * @param size Default size for this view
16197     * @param measureSpec Constraints imposed by the parent
16198     * @return The size this view should be.
16199     */
16200    public static int getDefaultSize(int size, int measureSpec) {
16201        int result = size;
16202        int specMode = MeasureSpec.getMode(measureSpec);
16203        int specSize = MeasureSpec.getSize(measureSpec);
16204
16205        switch (specMode) {
16206        case MeasureSpec.UNSPECIFIED:
16207            result = size;
16208            break;
16209        case MeasureSpec.AT_MOST:
16210        case MeasureSpec.EXACTLY:
16211            result = specSize;
16212            break;
16213        }
16214        return result;
16215    }
16216
16217    /**
16218     * Returns the suggested minimum height that the view should use. This
16219     * returns the maximum of the view's minimum height
16220     * and the background's minimum height
16221     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
16222     * <p>
16223     * When being used in {@link #onMeasure(int, int)}, the caller should still
16224     * ensure the returned height is within the requirements of the parent.
16225     *
16226     * @return The suggested minimum height of the view.
16227     */
16228    protected int getSuggestedMinimumHeight() {
16229        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
16230
16231    }
16232
16233    /**
16234     * Returns the suggested minimum width that the view should use. This
16235     * returns the maximum of the view's minimum width)
16236     * and the background's minimum width
16237     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
16238     * <p>
16239     * When being used in {@link #onMeasure(int, int)}, the caller should still
16240     * ensure the returned width is within the requirements of the parent.
16241     *
16242     * @return The suggested minimum width of the view.
16243     */
16244    protected int getSuggestedMinimumWidth() {
16245        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
16246    }
16247
16248    /**
16249     * Returns the minimum height of the view.
16250     *
16251     * @return the minimum height the view will try to be.
16252     *
16253     * @see #setMinimumHeight(int)
16254     *
16255     * @attr ref android.R.styleable#View_minHeight
16256     */
16257    public int getMinimumHeight() {
16258        return mMinHeight;
16259    }
16260
16261    /**
16262     * Sets the minimum height of the view. It is not guaranteed the view will
16263     * be able to achieve this minimum height (for example, if its parent layout
16264     * constrains it with less available height).
16265     *
16266     * @param minHeight The minimum height the view will try to be.
16267     *
16268     * @see #getMinimumHeight()
16269     *
16270     * @attr ref android.R.styleable#View_minHeight
16271     */
16272    public void setMinimumHeight(int minHeight) {
16273        mMinHeight = minHeight;
16274        requestLayout();
16275    }
16276
16277    /**
16278     * Returns the minimum width of the view.
16279     *
16280     * @return the minimum width the view will try to be.
16281     *
16282     * @see #setMinimumWidth(int)
16283     *
16284     * @attr ref android.R.styleable#View_minWidth
16285     */
16286    public int getMinimumWidth() {
16287        return mMinWidth;
16288    }
16289
16290    /**
16291     * Sets the minimum width of the view. It is not guaranteed the view will
16292     * be able to achieve this minimum width (for example, if its parent layout
16293     * constrains it with less available width).
16294     *
16295     * @param minWidth The minimum width the view will try to be.
16296     *
16297     * @see #getMinimumWidth()
16298     *
16299     * @attr ref android.R.styleable#View_minWidth
16300     */
16301    public void setMinimumWidth(int minWidth) {
16302        mMinWidth = minWidth;
16303        requestLayout();
16304
16305    }
16306
16307    /**
16308     * Get the animation currently associated with this view.
16309     *
16310     * @return The animation that is currently playing or
16311     *         scheduled to play for this view.
16312     */
16313    public Animation getAnimation() {
16314        return mCurrentAnimation;
16315    }
16316
16317    /**
16318     * Start the specified animation now.
16319     *
16320     * @param animation the animation to start now
16321     */
16322    public void startAnimation(Animation animation) {
16323        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
16324        setAnimation(animation);
16325        invalidateParentCaches();
16326        invalidate(true);
16327    }
16328
16329    /**
16330     * Cancels any animations for this view.
16331     */
16332    public void clearAnimation() {
16333        if (mCurrentAnimation != null) {
16334            mCurrentAnimation.detach();
16335        }
16336        mCurrentAnimation = null;
16337        invalidateParentIfNeeded();
16338    }
16339
16340    /**
16341     * Sets the next animation to play for this view.
16342     * If you want the animation to play immediately, use
16343     * {@link #startAnimation(android.view.animation.Animation)} instead.
16344     * This method provides allows fine-grained
16345     * control over the start time and invalidation, but you
16346     * must make sure that 1) the animation has a start time set, and
16347     * 2) the view's parent (which controls animations on its children)
16348     * will be invalidated when the animation is supposed to
16349     * start.
16350     *
16351     * @param animation The next animation, or null.
16352     */
16353    public void setAnimation(Animation animation) {
16354        mCurrentAnimation = animation;
16355
16356        if (animation != null) {
16357            // If the screen is off assume the animation start time is now instead of
16358            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
16359            // would cause the animation to start when the screen turns back on
16360            if (mAttachInfo != null && !mAttachInfo.mScreenOn &&
16361                    animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
16362                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
16363            }
16364            animation.reset();
16365        }
16366    }
16367
16368    /**
16369     * Invoked by a parent ViewGroup to notify the start of the animation
16370     * currently associated with this view. If you override this method,
16371     * always call super.onAnimationStart();
16372     *
16373     * @see #setAnimation(android.view.animation.Animation)
16374     * @see #getAnimation()
16375     */
16376    protected void onAnimationStart() {
16377        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
16378    }
16379
16380    /**
16381     * Invoked by a parent ViewGroup to notify the end of the animation
16382     * currently associated with this view. If you override this method,
16383     * always call super.onAnimationEnd();
16384     *
16385     * @see #setAnimation(android.view.animation.Animation)
16386     * @see #getAnimation()
16387     */
16388    protected void onAnimationEnd() {
16389        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
16390    }
16391
16392    /**
16393     * Invoked if there is a Transform that involves alpha. Subclass that can
16394     * draw themselves with the specified alpha should return true, and then
16395     * respect that alpha when their onDraw() is called. If this returns false
16396     * then the view may be redirected to draw into an offscreen buffer to
16397     * fulfill the request, which will look fine, but may be slower than if the
16398     * subclass handles it internally. The default implementation returns false.
16399     *
16400     * @param alpha The alpha (0..255) to apply to the view's drawing
16401     * @return true if the view can draw with the specified alpha.
16402     */
16403    protected boolean onSetAlpha(int alpha) {
16404        return false;
16405    }
16406
16407    /**
16408     * This is used by the RootView to perform an optimization when
16409     * the view hierarchy contains one or several SurfaceView.
16410     * SurfaceView is always considered transparent, but its children are not,
16411     * therefore all View objects remove themselves from the global transparent
16412     * region (passed as a parameter to this function).
16413     *
16414     * @param region The transparent region for this ViewAncestor (window).
16415     *
16416     * @return Returns true if the effective visibility of the view at this
16417     * point is opaque, regardless of the transparent region; returns false
16418     * if it is possible for underlying windows to be seen behind the view.
16419     *
16420     * {@hide}
16421     */
16422    public boolean gatherTransparentRegion(Region region) {
16423        final AttachInfo attachInfo = mAttachInfo;
16424        if (region != null && attachInfo != null) {
16425            final int pflags = mPrivateFlags;
16426            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
16427                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
16428                // remove it from the transparent region.
16429                final int[] location = attachInfo.mTransparentLocation;
16430                getLocationInWindow(location);
16431                region.op(location[0], location[1], location[0] + mRight - mLeft,
16432                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
16433            } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) {
16434                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
16435                // exists, so we remove the background drawable's non-transparent
16436                // parts from this transparent region.
16437                applyDrawableToTransparentRegion(mBackground, region);
16438            }
16439        }
16440        return true;
16441    }
16442
16443    /**
16444     * Play a sound effect for this view.
16445     *
16446     * <p>The framework will play sound effects for some built in actions, such as
16447     * clicking, but you may wish to play these effects in your widget,
16448     * for instance, for internal navigation.
16449     *
16450     * <p>The sound effect will only be played if sound effects are enabled by the user, and
16451     * {@link #isSoundEffectsEnabled()} is true.
16452     *
16453     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
16454     */
16455    public void playSoundEffect(int soundConstant) {
16456        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
16457            return;
16458        }
16459        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
16460    }
16461
16462    /**
16463     * BZZZTT!!1!
16464     *
16465     * <p>Provide haptic feedback to the user for this view.
16466     *
16467     * <p>The framework will provide haptic feedback for some built in actions,
16468     * such as long presses, but you may wish to provide feedback for your
16469     * own widget.
16470     *
16471     * <p>The feedback will only be performed if
16472     * {@link #isHapticFeedbackEnabled()} is true.
16473     *
16474     * @param feedbackConstant One of the constants defined in
16475     * {@link HapticFeedbackConstants}
16476     */
16477    public boolean performHapticFeedback(int feedbackConstant) {
16478        return performHapticFeedback(feedbackConstant, 0);
16479    }
16480
16481    /**
16482     * BZZZTT!!1!
16483     *
16484     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
16485     *
16486     * @param feedbackConstant One of the constants defined in
16487     * {@link HapticFeedbackConstants}
16488     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
16489     */
16490    public boolean performHapticFeedback(int feedbackConstant, int flags) {
16491        if (mAttachInfo == null) {
16492            return false;
16493        }
16494        //noinspection SimplifiableIfStatement
16495        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
16496                && !isHapticFeedbackEnabled()) {
16497            return false;
16498        }
16499        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
16500                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
16501    }
16502
16503    /**
16504     * Request that the visibility of the status bar or other screen/window
16505     * decorations be changed.
16506     *
16507     * <p>This method is used to put the over device UI into temporary modes
16508     * where the user's attention is focused more on the application content,
16509     * by dimming or hiding surrounding system affordances.  This is typically
16510     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
16511     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
16512     * to be placed behind the action bar (and with these flags other system
16513     * affordances) so that smooth transitions between hiding and showing them
16514     * can be done.
16515     *
16516     * <p>Two representative examples of the use of system UI visibility is
16517     * implementing a content browsing application (like a magazine reader)
16518     * and a video playing application.
16519     *
16520     * <p>The first code shows a typical implementation of a View in a content
16521     * browsing application.  In this implementation, the application goes
16522     * into a content-oriented mode by hiding the status bar and action bar,
16523     * and putting the navigation elements into lights out mode.  The user can
16524     * then interact with content while in this mode.  Such an application should
16525     * provide an easy way for the user to toggle out of the mode (such as to
16526     * check information in the status bar or access notifications).  In the
16527     * implementation here, this is done simply by tapping on the content.
16528     *
16529     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
16530     *      content}
16531     *
16532     * <p>This second code sample shows a typical implementation of a View
16533     * in a video playing application.  In this situation, while the video is
16534     * playing the application would like to go into a complete full-screen mode,
16535     * to use as much of the display as possible for the video.  When in this state
16536     * the user can not interact with the application; the system intercepts
16537     * touching on the screen to pop the UI out of full screen mode.  See
16538     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
16539     *
16540     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
16541     *      content}
16542     *
16543     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
16544     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
16545     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
16546     * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}.
16547     */
16548    public void setSystemUiVisibility(int visibility) {
16549        if (visibility != mSystemUiVisibility) {
16550            mSystemUiVisibility = visibility;
16551            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
16552                mParent.recomputeViewAttributes(this);
16553            }
16554        }
16555    }
16556
16557    /**
16558     * Returns the last {@link #setSystemUiVisibility(int) that this view has requested.
16559     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
16560     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
16561     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
16562     * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}.
16563     */
16564    public int getSystemUiVisibility() {
16565        return mSystemUiVisibility;
16566    }
16567
16568    /**
16569     * Returns the current system UI visibility that is currently set for
16570     * the entire window.  This is the combination of the
16571     * {@link #setSystemUiVisibility(int)} values supplied by all of the
16572     * views in the window.
16573     */
16574    public int getWindowSystemUiVisibility() {
16575        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
16576    }
16577
16578    /**
16579     * Override to find out when the window's requested system UI visibility
16580     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
16581     * This is different from the callbacks received through
16582     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
16583     * in that this is only telling you about the local request of the window,
16584     * not the actual values applied by the system.
16585     */
16586    public void onWindowSystemUiVisibilityChanged(int visible) {
16587    }
16588
16589    /**
16590     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
16591     * the view hierarchy.
16592     */
16593    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
16594        onWindowSystemUiVisibilityChanged(visible);
16595    }
16596
16597    /**
16598     * Set a listener to receive callbacks when the visibility of the system bar changes.
16599     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
16600     */
16601    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
16602        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
16603        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
16604            mParent.recomputeViewAttributes(this);
16605        }
16606    }
16607
16608    /**
16609     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
16610     * the view hierarchy.
16611     */
16612    public void dispatchSystemUiVisibilityChanged(int visibility) {
16613        ListenerInfo li = mListenerInfo;
16614        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
16615            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
16616                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
16617        }
16618    }
16619
16620    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
16621        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
16622        if (val != mSystemUiVisibility) {
16623            setSystemUiVisibility(val);
16624            return true;
16625        }
16626        return false;
16627    }
16628
16629    /** @hide */
16630    public void setDisabledSystemUiVisibility(int flags) {
16631        if (mAttachInfo != null) {
16632            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
16633                mAttachInfo.mDisabledSystemUiVisibility = flags;
16634                if (mParent != null) {
16635                    mParent.recomputeViewAttributes(this);
16636                }
16637            }
16638        }
16639    }
16640
16641    /**
16642     * Creates an image that the system displays during the drag and drop
16643     * operation. This is called a &quot;drag shadow&quot;. The default implementation
16644     * for a DragShadowBuilder based on a View returns an image that has exactly the same
16645     * appearance as the given View. The default also positions the center of the drag shadow
16646     * directly under the touch point. If no View is provided (the constructor with no parameters
16647     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
16648     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
16649     * default is an invisible drag shadow.
16650     * <p>
16651     * You are not required to use the View you provide to the constructor as the basis of the
16652     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
16653     * anything you want as the drag shadow.
16654     * </p>
16655     * <p>
16656     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
16657     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
16658     *  size and position of the drag shadow. It uses this data to construct a
16659     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
16660     *  so that your application can draw the shadow image in the Canvas.
16661     * </p>
16662     *
16663     * <div class="special reference">
16664     * <h3>Developer Guides</h3>
16665     * <p>For a guide to implementing drag and drop features, read the
16666     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
16667     * </div>
16668     */
16669    public static class DragShadowBuilder {
16670        private final WeakReference<View> mView;
16671
16672        /**
16673         * Constructs a shadow image builder based on a View. By default, the resulting drag
16674         * shadow will have the same appearance and dimensions as the View, with the touch point
16675         * over the center of the View.
16676         * @param view A View. Any View in scope can be used.
16677         */
16678        public DragShadowBuilder(View view) {
16679            mView = new WeakReference<View>(view);
16680        }
16681
16682        /**
16683         * Construct a shadow builder object with no associated View.  This
16684         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
16685         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
16686         * to supply the drag shadow's dimensions and appearance without
16687         * reference to any View object. If they are not overridden, then the result is an
16688         * invisible drag shadow.
16689         */
16690        public DragShadowBuilder() {
16691            mView = new WeakReference<View>(null);
16692        }
16693
16694        /**
16695         * Returns the View object that had been passed to the
16696         * {@link #View.DragShadowBuilder(View)}
16697         * constructor.  If that View parameter was {@code null} or if the
16698         * {@link #View.DragShadowBuilder()}
16699         * constructor was used to instantiate the builder object, this method will return
16700         * null.
16701         *
16702         * @return The View object associate with this builder object.
16703         */
16704        @SuppressWarnings({"JavadocReference"})
16705        final public View getView() {
16706            return mView.get();
16707        }
16708
16709        /**
16710         * Provides the metrics for the shadow image. These include the dimensions of
16711         * the shadow image, and the point within that shadow that should
16712         * be centered under the touch location while dragging.
16713         * <p>
16714         * The default implementation sets the dimensions of the shadow to be the
16715         * same as the dimensions of the View itself and centers the shadow under
16716         * the touch point.
16717         * </p>
16718         *
16719         * @param shadowSize A {@link android.graphics.Point} containing the width and height
16720         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
16721         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
16722         * image.
16723         *
16724         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
16725         * shadow image that should be underneath the touch point during the drag and drop
16726         * operation. Your application must set {@link android.graphics.Point#x} to the
16727         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
16728         */
16729        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
16730            final View view = mView.get();
16731            if (view != null) {
16732                shadowSize.set(view.getWidth(), view.getHeight());
16733                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
16734            } else {
16735                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
16736            }
16737        }
16738
16739        /**
16740         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
16741         * based on the dimensions it received from the
16742         * {@link #onProvideShadowMetrics(Point, Point)} callback.
16743         *
16744         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
16745         */
16746        public void onDrawShadow(Canvas canvas) {
16747            final View view = mView.get();
16748            if (view != null) {
16749                view.draw(canvas);
16750            } else {
16751                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
16752            }
16753        }
16754    }
16755
16756    /**
16757     * Starts a drag and drop operation. When your application calls this method, it passes a
16758     * {@link android.view.View.DragShadowBuilder} object to the system. The
16759     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
16760     * to get metrics for the drag shadow, and then calls the object's
16761     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
16762     * <p>
16763     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
16764     *  drag events to all the View objects in your application that are currently visible. It does
16765     *  this either by calling the View object's drag listener (an implementation of
16766     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
16767     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
16768     *  Both are passed a {@link android.view.DragEvent} object that has a
16769     *  {@link android.view.DragEvent#getAction()} value of
16770     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
16771     * </p>
16772     * <p>
16773     * Your application can invoke startDrag() on any attached View object. The View object does not
16774     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
16775     * be related to the View the user selected for dragging.
16776     * </p>
16777     * @param data A {@link android.content.ClipData} object pointing to the data to be
16778     * transferred by the drag and drop operation.
16779     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
16780     * drag shadow.
16781     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
16782     * drop operation. This Object is put into every DragEvent object sent by the system during the
16783     * current drag.
16784     * <p>
16785     * myLocalState is a lightweight mechanism for the sending information from the dragged View
16786     * to the target Views. For example, it can contain flags that differentiate between a
16787     * a copy operation and a move operation.
16788     * </p>
16789     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
16790     * so the parameter should be set to 0.
16791     * @return {@code true} if the method completes successfully, or
16792     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
16793     * do a drag, and so no drag operation is in progress.
16794     */
16795    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
16796            Object myLocalState, int flags) {
16797        if (ViewDebug.DEBUG_DRAG) {
16798            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
16799        }
16800        boolean okay = false;
16801
16802        Point shadowSize = new Point();
16803        Point shadowTouchPoint = new Point();
16804        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
16805
16806        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
16807                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
16808            throw new IllegalStateException("Drag shadow dimensions must not be negative");
16809        }
16810
16811        if (ViewDebug.DEBUG_DRAG) {
16812            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
16813                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
16814        }
16815        Surface surface = new Surface();
16816        try {
16817            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
16818                    flags, shadowSize.x, shadowSize.y, surface);
16819            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
16820                    + " surface=" + surface);
16821            if (token != null) {
16822                Canvas canvas = surface.lockCanvas(null);
16823                try {
16824                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
16825                    shadowBuilder.onDrawShadow(canvas);
16826                } finally {
16827                    surface.unlockCanvasAndPost(canvas);
16828                }
16829
16830                final ViewRootImpl root = getViewRootImpl();
16831
16832                // Cache the local state object for delivery with DragEvents
16833                root.setLocalDragState(myLocalState);
16834
16835                // repurpose 'shadowSize' for the last touch point
16836                root.getLastTouchPoint(shadowSize);
16837
16838                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
16839                        shadowSize.x, shadowSize.y,
16840                        shadowTouchPoint.x, shadowTouchPoint.y, data);
16841                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
16842
16843                // Off and running!  Release our local surface instance; the drag
16844                // shadow surface is now managed by the system process.
16845                surface.release();
16846            }
16847        } catch (Exception e) {
16848            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
16849            surface.destroy();
16850        }
16851
16852        return okay;
16853    }
16854
16855    /**
16856     * Handles drag events sent by the system following a call to
16857     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
16858     *<p>
16859     * When the system calls this method, it passes a
16860     * {@link android.view.DragEvent} object. A call to
16861     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
16862     * in DragEvent. The method uses these to determine what is happening in the drag and drop
16863     * operation.
16864     * @param event The {@link android.view.DragEvent} sent by the system.
16865     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
16866     * in DragEvent, indicating the type of drag event represented by this object.
16867     * @return {@code true} if the method was successful, otherwise {@code false}.
16868     * <p>
16869     *  The method should return {@code true} in response to an action type of
16870     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
16871     *  operation.
16872     * </p>
16873     * <p>
16874     *  The method should also return {@code true} in response to an action type of
16875     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
16876     *  {@code false} if it didn't.
16877     * </p>
16878     */
16879    public boolean onDragEvent(DragEvent event) {
16880        return false;
16881    }
16882
16883    /**
16884     * Detects if this View is enabled and has a drag event listener.
16885     * If both are true, then it calls the drag event listener with the
16886     * {@link android.view.DragEvent} it received. If the drag event listener returns
16887     * {@code true}, then dispatchDragEvent() returns {@code true}.
16888     * <p>
16889     * For all other cases, the method calls the
16890     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
16891     * method and returns its result.
16892     * </p>
16893     * <p>
16894     * This ensures that a drag event is always consumed, even if the View does not have a drag
16895     * event listener. However, if the View has a listener and the listener returns true, then
16896     * onDragEvent() is not called.
16897     * </p>
16898     */
16899    public boolean dispatchDragEvent(DragEvent event) {
16900        ListenerInfo li = mListenerInfo;
16901        //noinspection SimplifiableIfStatement
16902        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
16903                && li.mOnDragListener.onDrag(this, event)) {
16904            return true;
16905        }
16906        return onDragEvent(event);
16907    }
16908
16909    boolean canAcceptDrag() {
16910        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
16911    }
16912
16913    /**
16914     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
16915     * it is ever exposed at all.
16916     * @hide
16917     */
16918    public void onCloseSystemDialogs(String reason) {
16919    }
16920
16921    /**
16922     * Given a Drawable whose bounds have been set to draw into this view,
16923     * update a Region being computed for
16924     * {@link #gatherTransparentRegion(android.graphics.Region)} so
16925     * that any non-transparent parts of the Drawable are removed from the
16926     * given transparent region.
16927     *
16928     * @param dr The Drawable whose transparency is to be applied to the region.
16929     * @param region A Region holding the current transparency information,
16930     * where any parts of the region that are set are considered to be
16931     * transparent.  On return, this region will be modified to have the
16932     * transparency information reduced by the corresponding parts of the
16933     * Drawable that are not transparent.
16934     * {@hide}
16935     */
16936    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
16937        if (DBG) {
16938            Log.i("View", "Getting transparent region for: " + this);
16939        }
16940        final Region r = dr.getTransparentRegion();
16941        final Rect db = dr.getBounds();
16942        final AttachInfo attachInfo = mAttachInfo;
16943        if (r != null && attachInfo != null) {
16944            final int w = getRight()-getLeft();
16945            final int h = getBottom()-getTop();
16946            if (db.left > 0) {
16947                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
16948                r.op(0, 0, db.left, h, Region.Op.UNION);
16949            }
16950            if (db.right < w) {
16951                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
16952                r.op(db.right, 0, w, h, Region.Op.UNION);
16953            }
16954            if (db.top > 0) {
16955                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
16956                r.op(0, 0, w, db.top, Region.Op.UNION);
16957            }
16958            if (db.bottom < h) {
16959                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
16960                r.op(0, db.bottom, w, h, Region.Op.UNION);
16961            }
16962            final int[] location = attachInfo.mTransparentLocation;
16963            getLocationInWindow(location);
16964            r.translate(location[0], location[1]);
16965            region.op(r, Region.Op.INTERSECT);
16966        } else {
16967            region.op(db, Region.Op.DIFFERENCE);
16968        }
16969    }
16970
16971    private void checkForLongClick(int delayOffset) {
16972        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
16973            mHasPerformedLongPress = false;
16974
16975            if (mPendingCheckForLongPress == null) {
16976                mPendingCheckForLongPress = new CheckForLongPress();
16977            }
16978            mPendingCheckForLongPress.rememberWindowAttachCount();
16979            postDelayed(mPendingCheckForLongPress,
16980                    ViewConfiguration.getLongPressTimeout() - delayOffset);
16981        }
16982    }
16983
16984    /**
16985     * Inflate a view from an XML resource.  This convenience method wraps the {@link
16986     * LayoutInflater} class, which provides a full range of options for view inflation.
16987     *
16988     * @param context The Context object for your activity or application.
16989     * @param resource The resource ID to inflate
16990     * @param root A view group that will be the parent.  Used to properly inflate the
16991     * layout_* parameters.
16992     * @see LayoutInflater
16993     */
16994    public static View inflate(Context context, int resource, ViewGroup root) {
16995        LayoutInflater factory = LayoutInflater.from(context);
16996        return factory.inflate(resource, root);
16997    }
16998
16999    /**
17000     * Scroll the view with standard behavior for scrolling beyond the normal
17001     * content boundaries. Views that call this method should override
17002     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
17003     * results of an over-scroll operation.
17004     *
17005     * Views can use this method to handle any touch or fling-based scrolling.
17006     *
17007     * @param deltaX Change in X in pixels
17008     * @param deltaY Change in Y in pixels
17009     * @param scrollX Current X scroll value in pixels before applying deltaX
17010     * @param scrollY Current Y scroll value in pixels before applying deltaY
17011     * @param scrollRangeX Maximum content scroll range along the X axis
17012     * @param scrollRangeY Maximum content scroll range along the Y axis
17013     * @param maxOverScrollX Number of pixels to overscroll by in either direction
17014     *          along the X axis.
17015     * @param maxOverScrollY Number of pixels to overscroll by in either direction
17016     *          along the Y axis.
17017     * @param isTouchEvent true if this scroll operation is the result of a touch event.
17018     * @return true if scrolling was clamped to an over-scroll boundary along either
17019     *          axis, false otherwise.
17020     */
17021    @SuppressWarnings({"UnusedParameters"})
17022    protected boolean overScrollBy(int deltaX, int deltaY,
17023            int scrollX, int scrollY,
17024            int scrollRangeX, int scrollRangeY,
17025            int maxOverScrollX, int maxOverScrollY,
17026            boolean isTouchEvent) {
17027        final int overScrollMode = mOverScrollMode;
17028        final boolean canScrollHorizontal =
17029                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
17030        final boolean canScrollVertical =
17031                computeVerticalScrollRange() > computeVerticalScrollExtent();
17032        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
17033                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
17034        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
17035                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
17036
17037        int newScrollX = scrollX + deltaX;
17038        if (!overScrollHorizontal) {
17039            maxOverScrollX = 0;
17040        }
17041
17042        int newScrollY = scrollY + deltaY;
17043        if (!overScrollVertical) {
17044            maxOverScrollY = 0;
17045        }
17046
17047        // Clamp values if at the limits and record
17048        final int left = -maxOverScrollX;
17049        final int right = maxOverScrollX + scrollRangeX;
17050        final int top = -maxOverScrollY;
17051        final int bottom = maxOverScrollY + scrollRangeY;
17052
17053        boolean clampedX = false;
17054        if (newScrollX > right) {
17055            newScrollX = right;
17056            clampedX = true;
17057        } else if (newScrollX < left) {
17058            newScrollX = left;
17059            clampedX = true;
17060        }
17061
17062        boolean clampedY = false;
17063        if (newScrollY > bottom) {
17064            newScrollY = bottom;
17065            clampedY = true;
17066        } else if (newScrollY < top) {
17067            newScrollY = top;
17068            clampedY = true;
17069        }
17070
17071        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
17072
17073        return clampedX || clampedY;
17074    }
17075
17076    /**
17077     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
17078     * respond to the results of an over-scroll operation.
17079     *
17080     * @param scrollX New X scroll value in pixels
17081     * @param scrollY New Y scroll value in pixels
17082     * @param clampedX True if scrollX was clamped to an over-scroll boundary
17083     * @param clampedY True if scrollY was clamped to an over-scroll boundary
17084     */
17085    protected void onOverScrolled(int scrollX, int scrollY,
17086            boolean clampedX, boolean clampedY) {
17087        // Intentionally empty.
17088    }
17089
17090    /**
17091     * Returns the over-scroll mode for this view. The result will be
17092     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
17093     * (allow over-scrolling only if the view content is larger than the container),
17094     * or {@link #OVER_SCROLL_NEVER}.
17095     *
17096     * @return This view's over-scroll mode.
17097     */
17098    public int getOverScrollMode() {
17099        return mOverScrollMode;
17100    }
17101
17102    /**
17103     * Set the over-scroll mode for this view. Valid over-scroll modes are
17104     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
17105     * (allow over-scrolling only if the view content is larger than the container),
17106     * or {@link #OVER_SCROLL_NEVER}.
17107     *
17108     * Setting the over-scroll mode of a view will have an effect only if the
17109     * view is capable of scrolling.
17110     *
17111     * @param overScrollMode The new over-scroll mode for this view.
17112     */
17113    public void setOverScrollMode(int overScrollMode) {
17114        if (overScrollMode != OVER_SCROLL_ALWAYS &&
17115                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
17116                overScrollMode != OVER_SCROLL_NEVER) {
17117            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
17118        }
17119        mOverScrollMode = overScrollMode;
17120    }
17121
17122    /**
17123     * Gets a scale factor that determines the distance the view should scroll
17124     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
17125     * @return The vertical scroll scale factor.
17126     * @hide
17127     */
17128    protected float getVerticalScrollFactor() {
17129        if (mVerticalScrollFactor == 0) {
17130            TypedValue outValue = new TypedValue();
17131            if (!mContext.getTheme().resolveAttribute(
17132                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
17133                throw new IllegalStateException(
17134                        "Expected theme to define listPreferredItemHeight.");
17135            }
17136            mVerticalScrollFactor = outValue.getDimension(
17137                    mContext.getResources().getDisplayMetrics());
17138        }
17139        return mVerticalScrollFactor;
17140    }
17141
17142    /**
17143     * Gets a scale factor that determines the distance the view should scroll
17144     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
17145     * @return The horizontal scroll scale factor.
17146     * @hide
17147     */
17148    protected float getHorizontalScrollFactor() {
17149        // TODO: Should use something else.
17150        return getVerticalScrollFactor();
17151    }
17152
17153    /**
17154     * Return the value specifying the text direction or policy that was set with
17155     * {@link #setTextDirection(int)}.
17156     *
17157     * @return the defined text direction. It can be one of:
17158     *
17159     * {@link #TEXT_DIRECTION_INHERIT},
17160     * {@link #TEXT_DIRECTION_FIRST_STRONG}
17161     * {@link #TEXT_DIRECTION_ANY_RTL},
17162     * {@link #TEXT_DIRECTION_LTR},
17163     * {@link #TEXT_DIRECTION_RTL},
17164     * {@link #TEXT_DIRECTION_LOCALE}
17165     *
17166     * @attr ref android.R.styleable#View_textDirection
17167     *
17168     * @hide
17169     */
17170    @ViewDebug.ExportedProperty(category = "text", mapping = {
17171            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
17172            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
17173            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
17174            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
17175            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
17176            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
17177    })
17178    public int getRawTextDirection() {
17179        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
17180    }
17181
17182    /**
17183     * Set the text direction.
17184     *
17185     * @param textDirection the direction to set. Should be one of:
17186     *
17187     * {@link #TEXT_DIRECTION_INHERIT},
17188     * {@link #TEXT_DIRECTION_FIRST_STRONG}
17189     * {@link #TEXT_DIRECTION_ANY_RTL},
17190     * {@link #TEXT_DIRECTION_LTR},
17191     * {@link #TEXT_DIRECTION_RTL},
17192     * {@link #TEXT_DIRECTION_LOCALE}
17193     *
17194     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
17195     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
17196     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
17197     *
17198     * @attr ref android.R.styleable#View_textDirection
17199     */
17200    public void setTextDirection(int textDirection) {
17201        if (getRawTextDirection() != textDirection) {
17202            // Reset the current text direction and the resolved one
17203            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
17204            resetResolvedTextDirection();
17205            // Set the new text direction
17206            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
17207            // Do resolution
17208            resolveTextDirection();
17209            // Notify change
17210            onRtlPropertiesChanged(getLayoutDirection());
17211            // Refresh
17212            requestLayout();
17213            invalidate(true);
17214        }
17215    }
17216
17217    /**
17218     * Return the resolved text direction.
17219     *
17220     * @return the resolved text direction. Returns one of:
17221     *
17222     * {@link #TEXT_DIRECTION_FIRST_STRONG}
17223     * {@link #TEXT_DIRECTION_ANY_RTL},
17224     * {@link #TEXT_DIRECTION_LTR},
17225     * {@link #TEXT_DIRECTION_RTL},
17226     * {@link #TEXT_DIRECTION_LOCALE}
17227     *
17228     * @attr ref android.R.styleable#View_textDirection
17229     */
17230    @ViewDebug.ExportedProperty(category = "text", mapping = {
17231            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
17232            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
17233            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
17234            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
17235            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
17236            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
17237    })
17238    public int getTextDirection() {
17239        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
17240    }
17241
17242    /**
17243     * Resolve the text direction.
17244     *
17245     * @return true if resolution has been done, false otherwise.
17246     *
17247     * @hide
17248     */
17249    public boolean resolveTextDirection() {
17250        // Reset any previous text direction resolution
17251        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
17252
17253        if (hasRtlSupport()) {
17254            // Set resolved text direction flag depending on text direction flag
17255            final int textDirection = getRawTextDirection();
17256            switch(textDirection) {
17257                case TEXT_DIRECTION_INHERIT:
17258                    if (!canResolveTextDirection()) {
17259                        // We cannot do the resolution if there is no parent, so use the default one
17260                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17261                        // Resolution will need to happen again later
17262                        return false;
17263                    }
17264
17265                    // Parent has not yet resolved, so we still return the default
17266                    try {
17267                        if (!mParent.isTextDirectionResolved()) {
17268                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17269                            // Resolution will need to happen again later
17270                            return false;
17271                        }
17272                    } catch (AbstractMethodError e) {
17273                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
17274                                " does not fully implement ViewParent", e);
17275                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED |
17276                                PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17277                        return true;
17278                    }
17279
17280                    // Set current resolved direction to the same value as the parent's one
17281                    int parentResolvedDirection;
17282                    try {
17283                        parentResolvedDirection = mParent.getTextDirection();
17284                    } catch (AbstractMethodError e) {
17285                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
17286                                " does not fully implement ViewParent", e);
17287                        parentResolvedDirection = TEXT_DIRECTION_LTR;
17288                    }
17289                    switch (parentResolvedDirection) {
17290                        case TEXT_DIRECTION_FIRST_STRONG:
17291                        case TEXT_DIRECTION_ANY_RTL:
17292                        case TEXT_DIRECTION_LTR:
17293                        case TEXT_DIRECTION_RTL:
17294                        case TEXT_DIRECTION_LOCALE:
17295                            mPrivateFlags2 |=
17296                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
17297                            break;
17298                        default:
17299                            // Default resolved direction is "first strong" heuristic
17300                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17301                    }
17302                    break;
17303                case TEXT_DIRECTION_FIRST_STRONG:
17304                case TEXT_DIRECTION_ANY_RTL:
17305                case TEXT_DIRECTION_LTR:
17306                case TEXT_DIRECTION_RTL:
17307                case TEXT_DIRECTION_LOCALE:
17308                    // Resolved direction is the same as text direction
17309                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
17310                    break;
17311                default:
17312                    // Default resolved direction is "first strong" heuristic
17313                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17314            }
17315        } else {
17316            // Default resolved direction is "first strong" heuristic
17317            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17318        }
17319
17320        // Set to resolved
17321        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
17322        return true;
17323    }
17324
17325    /**
17326     * Check if text direction resolution can be done.
17327     *
17328     * @return true if text direction resolution can be done otherwise return false.
17329     */
17330    public boolean canResolveTextDirection() {
17331        switch (getRawTextDirection()) {
17332            case TEXT_DIRECTION_INHERIT:
17333                if (mParent != null) {
17334                    try {
17335                        return mParent.canResolveTextDirection();
17336                    } catch (AbstractMethodError e) {
17337                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
17338                                " does not fully implement ViewParent", e);
17339                    }
17340                }
17341                return false;
17342
17343            default:
17344                return true;
17345        }
17346    }
17347
17348    /**
17349     * Reset resolved text direction. Text direction will be resolved during a call to
17350     * {@link #onMeasure(int, int)}.
17351     *
17352     * @hide
17353     */
17354    public void resetResolvedTextDirection() {
17355        // Reset any previous text direction resolution
17356        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
17357        // Set to default value
17358        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17359    }
17360
17361    /**
17362     * @return true if text direction is inherited.
17363     *
17364     * @hide
17365     */
17366    public boolean isTextDirectionInherited() {
17367        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
17368    }
17369
17370    /**
17371     * @return true if text direction is resolved.
17372     */
17373    public boolean isTextDirectionResolved() {
17374        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
17375    }
17376
17377    /**
17378     * Return the value specifying the text alignment or policy that was set with
17379     * {@link #setTextAlignment(int)}.
17380     *
17381     * @return the defined text alignment. It can be one of:
17382     *
17383     * {@link #TEXT_ALIGNMENT_INHERIT},
17384     * {@link #TEXT_ALIGNMENT_GRAVITY},
17385     * {@link #TEXT_ALIGNMENT_CENTER},
17386     * {@link #TEXT_ALIGNMENT_TEXT_START},
17387     * {@link #TEXT_ALIGNMENT_TEXT_END},
17388     * {@link #TEXT_ALIGNMENT_VIEW_START},
17389     * {@link #TEXT_ALIGNMENT_VIEW_END}
17390     *
17391     * @attr ref android.R.styleable#View_textAlignment
17392     *
17393     * @hide
17394     */
17395    @ViewDebug.ExportedProperty(category = "text", mapping = {
17396            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
17397            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
17398            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
17399            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
17400            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
17401            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
17402            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
17403    })
17404    public int getRawTextAlignment() {
17405        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
17406    }
17407
17408    /**
17409     * Set the text alignment.
17410     *
17411     * @param textAlignment The text alignment to set. Should be one of
17412     *
17413     * {@link #TEXT_ALIGNMENT_INHERIT},
17414     * {@link #TEXT_ALIGNMENT_GRAVITY},
17415     * {@link #TEXT_ALIGNMENT_CENTER},
17416     * {@link #TEXT_ALIGNMENT_TEXT_START},
17417     * {@link #TEXT_ALIGNMENT_TEXT_END},
17418     * {@link #TEXT_ALIGNMENT_VIEW_START},
17419     * {@link #TEXT_ALIGNMENT_VIEW_END}
17420     *
17421     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
17422     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
17423     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
17424     *
17425     * @attr ref android.R.styleable#View_textAlignment
17426     */
17427    public void setTextAlignment(int textAlignment) {
17428        if (textAlignment != getRawTextAlignment()) {
17429            // Reset the current and resolved text alignment
17430            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
17431            resetResolvedTextAlignment();
17432            // Set the new text alignment
17433            mPrivateFlags2 |=
17434                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
17435            // Do resolution
17436            resolveTextAlignment();
17437            // Notify change
17438            onRtlPropertiesChanged(getLayoutDirection());
17439            // Refresh
17440            requestLayout();
17441            invalidate(true);
17442        }
17443    }
17444
17445    /**
17446     * Return the resolved text alignment.
17447     *
17448     * @return the resolved text alignment. Returns one of:
17449     *
17450     * {@link #TEXT_ALIGNMENT_GRAVITY},
17451     * {@link #TEXT_ALIGNMENT_CENTER},
17452     * {@link #TEXT_ALIGNMENT_TEXT_START},
17453     * {@link #TEXT_ALIGNMENT_TEXT_END},
17454     * {@link #TEXT_ALIGNMENT_VIEW_START},
17455     * {@link #TEXT_ALIGNMENT_VIEW_END}
17456     *
17457     * @attr ref android.R.styleable#View_textAlignment
17458     */
17459    @ViewDebug.ExportedProperty(category = "text", mapping = {
17460            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
17461            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
17462            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
17463            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
17464            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
17465            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
17466            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
17467    })
17468    public int getTextAlignment() {
17469        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
17470                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
17471    }
17472
17473    /**
17474     * Resolve the text alignment.
17475     *
17476     * @return true if resolution has been done, false otherwise.
17477     *
17478     * @hide
17479     */
17480    public boolean resolveTextAlignment() {
17481        // Reset any previous text alignment resolution
17482        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
17483
17484        if (hasRtlSupport()) {
17485            // Set resolved text alignment flag depending on text alignment flag
17486            final int textAlignment = getRawTextAlignment();
17487            switch (textAlignment) {
17488                case TEXT_ALIGNMENT_INHERIT:
17489                    // Check if we can resolve the text alignment
17490                    if (!canResolveTextAlignment()) {
17491                        // We cannot do the resolution if there is no parent so use the default
17492                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17493                        // Resolution will need to happen again later
17494                        return false;
17495                    }
17496
17497                    // Parent has not yet resolved, so we still return the default
17498                    try {
17499                        if (!mParent.isTextAlignmentResolved()) {
17500                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17501                            // Resolution will need to happen again later
17502                            return false;
17503                        }
17504                    } catch (AbstractMethodError e) {
17505                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
17506                                " does not fully implement ViewParent", e);
17507                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED |
17508                                PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17509                        return true;
17510                    }
17511
17512                    int parentResolvedTextAlignment;
17513                    try {
17514                        parentResolvedTextAlignment = mParent.getTextAlignment();
17515                    } catch (AbstractMethodError e) {
17516                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
17517                                " does not fully implement ViewParent", e);
17518                        parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY;
17519                    }
17520                    switch (parentResolvedTextAlignment) {
17521                        case TEXT_ALIGNMENT_GRAVITY:
17522                        case TEXT_ALIGNMENT_TEXT_START:
17523                        case TEXT_ALIGNMENT_TEXT_END:
17524                        case TEXT_ALIGNMENT_CENTER:
17525                        case TEXT_ALIGNMENT_VIEW_START:
17526                        case TEXT_ALIGNMENT_VIEW_END:
17527                            // Resolved text alignment is the same as the parent resolved
17528                            // text alignment
17529                            mPrivateFlags2 |=
17530                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
17531                            break;
17532                        default:
17533                            // Use default resolved text alignment
17534                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17535                    }
17536                    break;
17537                case TEXT_ALIGNMENT_GRAVITY:
17538                case TEXT_ALIGNMENT_TEXT_START:
17539                case TEXT_ALIGNMENT_TEXT_END:
17540                case TEXT_ALIGNMENT_CENTER:
17541                case TEXT_ALIGNMENT_VIEW_START:
17542                case TEXT_ALIGNMENT_VIEW_END:
17543                    // Resolved text alignment is the same as text alignment
17544                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
17545                    break;
17546                default:
17547                    // Use default resolved text alignment
17548                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17549            }
17550        } else {
17551            // Use default resolved text alignment
17552            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17553        }
17554
17555        // Set the resolved
17556        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
17557        return true;
17558    }
17559
17560    /**
17561     * Check if text alignment resolution can be done.
17562     *
17563     * @return true if text alignment resolution can be done otherwise return false.
17564     */
17565    public boolean canResolveTextAlignment() {
17566        switch (getRawTextAlignment()) {
17567            case TEXT_DIRECTION_INHERIT:
17568                if (mParent != null) {
17569                    try {
17570                        return mParent.canResolveTextAlignment();
17571                    } catch (AbstractMethodError e) {
17572                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
17573                                " does not fully implement ViewParent", e);
17574                    }
17575                }
17576                return false;
17577
17578            default:
17579                return true;
17580        }
17581    }
17582
17583    /**
17584     * Reset resolved text alignment. Text alignment will be resolved during a call to
17585     * {@link #onMeasure(int, int)}.
17586     *
17587     * @hide
17588     */
17589    public void resetResolvedTextAlignment() {
17590        // Reset any previous text alignment resolution
17591        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
17592        // Set to default
17593        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17594    }
17595
17596    /**
17597     * @return true if text alignment is inherited.
17598     *
17599     * @hide
17600     */
17601    public boolean isTextAlignmentInherited() {
17602        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
17603    }
17604
17605    /**
17606     * @return true if text alignment is resolved.
17607     */
17608    public boolean isTextAlignmentResolved() {
17609        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
17610    }
17611
17612    /**
17613     * Generate a value suitable for use in {@link #setId(int)}.
17614     * This value will not collide with ID values generated at build time by aapt for R.id.
17615     *
17616     * @return a generated ID value
17617     */
17618    public static int generateViewId() {
17619        for (;;) {
17620            final int result = sNextGeneratedId.get();
17621            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
17622            int newValue = result + 1;
17623            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
17624            if (sNextGeneratedId.compareAndSet(result, newValue)) {
17625                return result;
17626            }
17627        }
17628    }
17629
17630    //
17631    // Properties
17632    //
17633    /**
17634     * A Property wrapper around the <code>alpha</code> functionality handled by the
17635     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
17636     */
17637    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
17638        @Override
17639        public void setValue(View object, float value) {
17640            object.setAlpha(value);
17641        }
17642
17643        @Override
17644        public Float get(View object) {
17645            return object.getAlpha();
17646        }
17647    };
17648
17649    /**
17650     * A Property wrapper around the <code>translationX</code> functionality handled by the
17651     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
17652     */
17653    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
17654        @Override
17655        public void setValue(View object, float value) {
17656            object.setTranslationX(value);
17657        }
17658
17659                @Override
17660        public Float get(View object) {
17661            return object.getTranslationX();
17662        }
17663    };
17664
17665    /**
17666     * A Property wrapper around the <code>translationY</code> functionality handled by the
17667     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
17668     */
17669    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
17670        @Override
17671        public void setValue(View object, float value) {
17672            object.setTranslationY(value);
17673        }
17674
17675        @Override
17676        public Float get(View object) {
17677            return object.getTranslationY();
17678        }
17679    };
17680
17681    /**
17682     * A Property wrapper around the <code>x</code> functionality handled by the
17683     * {@link View#setX(float)} and {@link View#getX()} methods.
17684     */
17685    public static final Property<View, Float> X = new FloatProperty<View>("x") {
17686        @Override
17687        public void setValue(View object, float value) {
17688            object.setX(value);
17689        }
17690
17691        @Override
17692        public Float get(View object) {
17693            return object.getX();
17694        }
17695    };
17696
17697    /**
17698     * A Property wrapper around the <code>y</code> functionality handled by the
17699     * {@link View#setY(float)} and {@link View#getY()} methods.
17700     */
17701    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
17702        @Override
17703        public void setValue(View object, float value) {
17704            object.setY(value);
17705        }
17706
17707        @Override
17708        public Float get(View object) {
17709            return object.getY();
17710        }
17711    };
17712
17713    /**
17714     * A Property wrapper around the <code>rotation</code> functionality handled by the
17715     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
17716     */
17717    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
17718        @Override
17719        public void setValue(View object, float value) {
17720            object.setRotation(value);
17721        }
17722
17723        @Override
17724        public Float get(View object) {
17725            return object.getRotation();
17726        }
17727    };
17728
17729    /**
17730     * A Property wrapper around the <code>rotationX</code> functionality handled by the
17731     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
17732     */
17733    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
17734        @Override
17735        public void setValue(View object, float value) {
17736            object.setRotationX(value);
17737        }
17738
17739        @Override
17740        public Float get(View object) {
17741            return object.getRotationX();
17742        }
17743    };
17744
17745    /**
17746     * A Property wrapper around the <code>rotationY</code> functionality handled by the
17747     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
17748     */
17749    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
17750        @Override
17751        public void setValue(View object, float value) {
17752            object.setRotationY(value);
17753        }
17754
17755        @Override
17756        public Float get(View object) {
17757            return object.getRotationY();
17758        }
17759    };
17760
17761    /**
17762     * A Property wrapper around the <code>scaleX</code> functionality handled by the
17763     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
17764     */
17765    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
17766        @Override
17767        public void setValue(View object, float value) {
17768            object.setScaleX(value);
17769        }
17770
17771        @Override
17772        public Float get(View object) {
17773            return object.getScaleX();
17774        }
17775    };
17776
17777    /**
17778     * A Property wrapper around the <code>scaleY</code> functionality handled by the
17779     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
17780     */
17781    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
17782        @Override
17783        public void setValue(View object, float value) {
17784            object.setScaleY(value);
17785        }
17786
17787        @Override
17788        public Float get(View object) {
17789            return object.getScaleY();
17790        }
17791    };
17792
17793    /**
17794     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
17795     * Each MeasureSpec represents a requirement for either the width or the height.
17796     * A MeasureSpec is comprised of a size and a mode. There are three possible
17797     * modes:
17798     * <dl>
17799     * <dt>UNSPECIFIED</dt>
17800     * <dd>
17801     * The parent has not imposed any constraint on the child. It can be whatever size
17802     * it wants.
17803     * </dd>
17804     *
17805     * <dt>EXACTLY</dt>
17806     * <dd>
17807     * The parent has determined an exact size for the child. The child is going to be
17808     * given those bounds regardless of how big it wants to be.
17809     * </dd>
17810     *
17811     * <dt>AT_MOST</dt>
17812     * <dd>
17813     * The child can be as large as it wants up to the specified size.
17814     * </dd>
17815     * </dl>
17816     *
17817     * MeasureSpecs are implemented as ints to reduce object allocation. This class
17818     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
17819     */
17820    public static class MeasureSpec {
17821        private static final int MODE_SHIFT = 30;
17822        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
17823
17824        /**
17825         * Measure specification mode: The parent has not imposed any constraint
17826         * on the child. It can be whatever size it wants.
17827         */
17828        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
17829
17830        /**
17831         * Measure specification mode: The parent has determined an exact size
17832         * for the child. The child is going to be given those bounds regardless
17833         * of how big it wants to be.
17834         */
17835        public static final int EXACTLY     = 1 << MODE_SHIFT;
17836
17837        /**
17838         * Measure specification mode: The child can be as large as it wants up
17839         * to the specified size.
17840         */
17841        public static final int AT_MOST     = 2 << MODE_SHIFT;
17842
17843        /**
17844         * Creates a measure specification based on the supplied size and mode.
17845         *
17846         * The mode must always be one of the following:
17847         * <ul>
17848         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
17849         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
17850         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
17851         * </ul>
17852         *
17853         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
17854         * implementation was such that the order of arguments did not matter
17855         * and overflow in either value could impact the resulting MeasureSpec.
17856         * {@link android.widget.RelativeLayout} was affected by this bug.
17857         * Apps targeting API levels greater than 17 will get the fixed, more strict
17858         * behavior.</p>
17859         *
17860         * @param size the size of the measure specification
17861         * @param mode the mode of the measure specification
17862         * @return the measure specification based on size and mode
17863         */
17864        public static int makeMeasureSpec(int size, int mode) {
17865            if (sUseBrokenMakeMeasureSpec) {
17866                return size + mode;
17867            } else {
17868                return (size & ~MODE_MASK) | (mode & MODE_MASK);
17869            }
17870        }
17871
17872        /**
17873         * Extracts the mode from the supplied measure specification.
17874         *
17875         * @param measureSpec the measure specification to extract the mode from
17876         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
17877         *         {@link android.view.View.MeasureSpec#AT_MOST} or
17878         *         {@link android.view.View.MeasureSpec#EXACTLY}
17879         */
17880        public static int getMode(int measureSpec) {
17881            return (measureSpec & MODE_MASK);
17882        }
17883
17884        /**
17885         * Extracts the size from the supplied measure specification.
17886         *
17887         * @param measureSpec the measure specification to extract the size from
17888         * @return the size in pixels defined in the supplied measure specification
17889         */
17890        public static int getSize(int measureSpec) {
17891            return (measureSpec & ~MODE_MASK);
17892        }
17893
17894        static int adjust(int measureSpec, int delta) {
17895            return makeMeasureSpec(getSize(measureSpec + delta), getMode(measureSpec));
17896        }
17897
17898        /**
17899         * Returns a String representation of the specified measure
17900         * specification.
17901         *
17902         * @param measureSpec the measure specification to convert to a String
17903         * @return a String with the following format: "MeasureSpec: MODE SIZE"
17904         */
17905        public static String toString(int measureSpec) {
17906            int mode = getMode(measureSpec);
17907            int size = getSize(measureSpec);
17908
17909            StringBuilder sb = new StringBuilder("MeasureSpec: ");
17910
17911            if (mode == UNSPECIFIED)
17912                sb.append("UNSPECIFIED ");
17913            else if (mode == EXACTLY)
17914                sb.append("EXACTLY ");
17915            else if (mode == AT_MOST)
17916                sb.append("AT_MOST ");
17917            else
17918                sb.append(mode).append(" ");
17919
17920            sb.append(size);
17921            return sb.toString();
17922        }
17923    }
17924
17925    class CheckForLongPress implements Runnable {
17926
17927        private int mOriginalWindowAttachCount;
17928
17929        public void run() {
17930            if (isPressed() && (mParent != null)
17931                    && mOriginalWindowAttachCount == mWindowAttachCount) {
17932                if (performLongClick()) {
17933                    mHasPerformedLongPress = true;
17934                }
17935            }
17936        }
17937
17938        public void rememberWindowAttachCount() {
17939            mOriginalWindowAttachCount = mWindowAttachCount;
17940        }
17941    }
17942
17943    private final class CheckForTap implements Runnable {
17944        public void run() {
17945            mPrivateFlags &= ~PFLAG_PREPRESSED;
17946            setPressed(true);
17947            checkForLongClick(ViewConfiguration.getTapTimeout());
17948        }
17949    }
17950
17951    private final class PerformClick implements Runnable {
17952        public void run() {
17953            performClick();
17954        }
17955    }
17956
17957    /** @hide */
17958    public void hackTurnOffWindowResizeAnim(boolean off) {
17959        mAttachInfo.mTurnOffWindowResizeAnim = off;
17960    }
17961
17962    /**
17963     * This method returns a ViewPropertyAnimator object, which can be used to animate
17964     * specific properties on this View.
17965     *
17966     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
17967     */
17968    public ViewPropertyAnimator animate() {
17969        if (mAnimator == null) {
17970            mAnimator = new ViewPropertyAnimator(this);
17971        }
17972        return mAnimator;
17973    }
17974
17975    /**
17976     * Set the current Scene that this view is in. The current scene is set only
17977     * on the root view of a scene, not for every view in that hierarchy. This
17978     * information is used by Scene to determine whether there is a previous
17979     * scene which should be exited before the new scene is entered.
17980     *
17981     * @param scene The new scene being set on the view
17982     *
17983     * @hide
17984     */
17985    public void setCurrentScene(Scene scene) {
17986        mCurrentScene = scene;
17987    }
17988
17989    /**
17990     * Gets the current {@link Scene} set on this view. A scene is set on a view
17991     * only if that view is the scene root.
17992     *
17993     * @return The current Scene set on this view. A value of null indicates that
17994     * no Scene is current set.
17995     */
17996    public Scene getCurrentScene() {
17997        return mCurrentScene;
17998    }
17999
18000    /**
18001     * Interface definition for a callback to be invoked when a hardware key event is
18002     * dispatched to this view. The callback will be invoked before the key event is
18003     * given to the view. This is only useful for hardware keyboards; a software input
18004     * method has no obligation to trigger this listener.
18005     */
18006    public interface OnKeyListener {
18007        /**
18008         * Called when a hardware key is dispatched to a view. This allows listeners to
18009         * get a chance to respond before the target view.
18010         * <p>Key presses in software keyboards will generally NOT trigger this method,
18011         * although some may elect to do so in some situations. Do not assume a
18012         * software input method has to be key-based; even if it is, it may use key presses
18013         * in a different way than you expect, so there is no way to reliably catch soft
18014         * input key presses.
18015         *
18016         * @param v The view the key has been dispatched to.
18017         * @param keyCode The code for the physical key that was pressed
18018         * @param event The KeyEvent object containing full information about
18019         *        the event.
18020         * @return True if the listener has consumed the event, false otherwise.
18021         */
18022        boolean onKey(View v, int keyCode, KeyEvent event);
18023    }
18024
18025    /**
18026     * Interface definition for a callback to be invoked when a touch event is
18027     * dispatched to this view. The callback will be invoked before the touch
18028     * event is given to the view.
18029     */
18030    public interface OnTouchListener {
18031        /**
18032         * Called when a touch event is dispatched to a view. This allows listeners to
18033         * get a chance to respond before the target view.
18034         *
18035         * @param v The view the touch event has been dispatched to.
18036         * @param event The MotionEvent object containing full information about
18037         *        the event.
18038         * @return True if the listener has consumed the event, false otherwise.
18039         */
18040        boolean onTouch(View v, MotionEvent event);
18041    }
18042
18043    /**
18044     * Interface definition for a callback to be invoked when a hover event is
18045     * dispatched to this view. The callback will be invoked before the hover
18046     * event is given to the view.
18047     */
18048    public interface OnHoverListener {
18049        /**
18050         * Called when a hover event is dispatched to a view. This allows listeners to
18051         * get a chance to respond before the target view.
18052         *
18053         * @param v The view the hover event has been dispatched to.
18054         * @param event The MotionEvent object containing full information about
18055         *        the event.
18056         * @return True if the listener has consumed the event, false otherwise.
18057         */
18058        boolean onHover(View v, MotionEvent event);
18059    }
18060
18061    /**
18062     * Interface definition for a callback to be invoked when a generic motion event is
18063     * dispatched to this view. The callback will be invoked before the generic motion
18064     * event is given to the view.
18065     */
18066    public interface OnGenericMotionListener {
18067        /**
18068         * Called when a generic motion event is dispatched to a view. This allows listeners to
18069         * get a chance to respond before the target view.
18070         *
18071         * @param v The view the generic motion event has been dispatched to.
18072         * @param event The MotionEvent object containing full information about
18073         *        the event.
18074         * @return True if the listener has consumed the event, false otherwise.
18075         */
18076        boolean onGenericMotion(View v, MotionEvent event);
18077    }
18078
18079    /**
18080     * Interface definition for a callback to be invoked when a view has been clicked and held.
18081     */
18082    public interface OnLongClickListener {
18083        /**
18084         * Called when a view has been clicked and held.
18085         *
18086         * @param v The view that was clicked and held.
18087         *
18088         * @return true if the callback consumed the long click, false otherwise.
18089         */
18090        boolean onLongClick(View v);
18091    }
18092
18093    /**
18094     * Interface definition for a callback to be invoked when a drag is being dispatched
18095     * to this view.  The callback will be invoked before the hosting view's own
18096     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
18097     * onDrag(event) behavior, it should return 'false' from this callback.
18098     *
18099     * <div class="special reference">
18100     * <h3>Developer Guides</h3>
18101     * <p>For a guide to implementing drag and drop features, read the
18102     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
18103     * </div>
18104     */
18105    public interface OnDragListener {
18106        /**
18107         * Called when a drag event is dispatched to a view. This allows listeners
18108         * to get a chance to override base View behavior.
18109         *
18110         * @param v The View that received the drag event.
18111         * @param event The {@link android.view.DragEvent} object for the drag event.
18112         * @return {@code true} if the drag event was handled successfully, or {@code false}
18113         * if the drag event was not handled. Note that {@code false} will trigger the View
18114         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
18115         */
18116        boolean onDrag(View v, DragEvent event);
18117    }
18118
18119    /**
18120     * Interface definition for a callback to be invoked when the focus state of
18121     * a view changed.
18122     */
18123    public interface OnFocusChangeListener {
18124        /**
18125         * Called when the focus state of a view has changed.
18126         *
18127         * @param v The view whose state has changed.
18128         * @param hasFocus The new focus state of v.
18129         */
18130        void onFocusChange(View v, boolean hasFocus);
18131    }
18132
18133    /**
18134     * Interface definition for a callback to be invoked when a view is clicked.
18135     */
18136    public interface OnClickListener {
18137        /**
18138         * Called when a view has been clicked.
18139         *
18140         * @param v The view that was clicked.
18141         */
18142        void onClick(View v);
18143    }
18144
18145    /**
18146     * Interface definition for a callback to be invoked when the context menu
18147     * for this view is being built.
18148     */
18149    public interface OnCreateContextMenuListener {
18150        /**
18151         * Called when the context menu for this view is being built. It is not
18152         * safe to hold onto the menu after this method returns.
18153         *
18154         * @param menu The context menu that is being built
18155         * @param v The view for which the context menu is being built
18156         * @param menuInfo Extra information about the item for which the
18157         *            context menu should be shown. This information will vary
18158         *            depending on the class of v.
18159         */
18160        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
18161    }
18162
18163    /**
18164     * Interface definition for a callback to be invoked when the status bar changes
18165     * visibility.  This reports <strong>global</strong> changes to the system UI
18166     * state, not what the application is requesting.
18167     *
18168     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
18169     */
18170    public interface OnSystemUiVisibilityChangeListener {
18171        /**
18172         * Called when the status bar changes visibility because of a call to
18173         * {@link View#setSystemUiVisibility(int)}.
18174         *
18175         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
18176         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
18177         * This tells you the <strong>global</strong> state of these UI visibility
18178         * flags, not what your app is currently applying.
18179         */
18180        public void onSystemUiVisibilityChange(int visibility);
18181    }
18182
18183    /**
18184     * Interface definition for a callback to be invoked when this view is attached
18185     * or detached from its window.
18186     */
18187    public interface OnAttachStateChangeListener {
18188        /**
18189         * Called when the view is attached to a window.
18190         * @param v The view that was attached
18191         */
18192        public void onViewAttachedToWindow(View v);
18193        /**
18194         * Called when the view is detached from a window.
18195         * @param v The view that was detached
18196         */
18197        public void onViewDetachedFromWindow(View v);
18198    }
18199
18200    private final class UnsetPressedState implements Runnable {
18201        public void run() {
18202            setPressed(false);
18203        }
18204    }
18205
18206    /**
18207     * Base class for derived classes that want to save and restore their own
18208     * state in {@link android.view.View#onSaveInstanceState()}.
18209     */
18210    public static class BaseSavedState extends AbsSavedState {
18211        /**
18212         * Constructor used when reading from a parcel. Reads the state of the superclass.
18213         *
18214         * @param source
18215         */
18216        public BaseSavedState(Parcel source) {
18217            super(source);
18218        }
18219
18220        /**
18221         * Constructor called by derived classes when creating their SavedState objects
18222         *
18223         * @param superState The state of the superclass of this view
18224         */
18225        public BaseSavedState(Parcelable superState) {
18226            super(superState);
18227        }
18228
18229        public static final Parcelable.Creator<BaseSavedState> CREATOR =
18230                new Parcelable.Creator<BaseSavedState>() {
18231            public BaseSavedState createFromParcel(Parcel in) {
18232                return new BaseSavedState(in);
18233            }
18234
18235            public BaseSavedState[] newArray(int size) {
18236                return new BaseSavedState[size];
18237            }
18238        };
18239    }
18240
18241    /**
18242     * A set of information given to a view when it is attached to its parent
18243     * window.
18244     */
18245    static class AttachInfo {
18246        interface Callbacks {
18247            void playSoundEffect(int effectId);
18248            boolean performHapticFeedback(int effectId, boolean always);
18249        }
18250
18251        /**
18252         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
18253         * to a Handler. This class contains the target (View) to invalidate and
18254         * the coordinates of the dirty rectangle.
18255         *
18256         * For performance purposes, this class also implements a pool of up to
18257         * POOL_LIMIT objects that get reused. This reduces memory allocations
18258         * whenever possible.
18259         */
18260        static class InvalidateInfo {
18261            private static final int POOL_LIMIT = 10;
18262
18263            private static final SynchronizedPool<InvalidateInfo> sPool =
18264                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
18265
18266            View target;
18267
18268            int left;
18269            int top;
18270            int right;
18271            int bottom;
18272
18273            public static InvalidateInfo obtain() {
18274                InvalidateInfo instance = sPool.acquire();
18275                return (instance != null) ? instance : new InvalidateInfo();
18276            }
18277
18278            public void recycle() {
18279                target = null;
18280                sPool.release(this);
18281            }
18282        }
18283
18284        final IWindowSession mSession;
18285
18286        final IWindow mWindow;
18287
18288        final IBinder mWindowToken;
18289
18290        final Display mDisplay;
18291
18292        final Callbacks mRootCallbacks;
18293
18294        HardwareCanvas mHardwareCanvas;
18295
18296        IWindowId mIWindowId;
18297        WindowId mWindowId;
18298
18299        /**
18300         * The top view of the hierarchy.
18301         */
18302        View mRootView;
18303
18304        IBinder mPanelParentWindowToken;
18305        Surface mSurface;
18306
18307        boolean mHardwareAccelerated;
18308        boolean mHardwareAccelerationRequested;
18309        HardwareRenderer mHardwareRenderer;
18310
18311        boolean mScreenOn;
18312
18313        /**
18314         * Scale factor used by the compatibility mode
18315         */
18316        float mApplicationScale;
18317
18318        /**
18319         * Indicates whether the application is in compatibility mode
18320         */
18321        boolean mScalingRequired;
18322
18323        /**
18324         * If set, ViewRootImpl doesn't use its lame animation for when the window resizes.
18325         */
18326        boolean mTurnOffWindowResizeAnim;
18327
18328        /**
18329         * Left position of this view's window
18330         */
18331        int mWindowLeft;
18332
18333        /**
18334         * Top position of this view's window
18335         */
18336        int mWindowTop;
18337
18338        /**
18339         * Indicates whether views need to use 32-bit drawing caches
18340         */
18341        boolean mUse32BitDrawingCache;
18342
18343        /**
18344         * For windows that are full-screen but using insets to layout inside
18345         * of the screen areas, these are the current insets to appear inside
18346         * the overscan area of the display.
18347         */
18348        final Rect mOverscanInsets = new Rect();
18349
18350        /**
18351         * For windows that are full-screen but using insets to layout inside
18352         * of the screen decorations, these are the current insets for the
18353         * content of the window.
18354         */
18355        final Rect mContentInsets = new Rect();
18356
18357        /**
18358         * For windows that are full-screen but using insets to layout inside
18359         * of the screen decorations, these are the current insets for the
18360         * actual visible parts of the window.
18361         */
18362        final Rect mVisibleInsets = new Rect();
18363
18364        /**
18365         * The internal insets given by this window.  This value is
18366         * supplied by the client (through
18367         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
18368         * be given to the window manager when changed to be used in laying
18369         * out windows behind it.
18370         */
18371        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
18372                = new ViewTreeObserver.InternalInsetsInfo();
18373
18374        /**
18375         * All views in the window's hierarchy that serve as scroll containers,
18376         * used to determine if the window can be resized or must be panned
18377         * to adjust for a soft input area.
18378         */
18379        final ArrayList<View> mScrollContainers = new ArrayList<View>();
18380
18381        final KeyEvent.DispatcherState mKeyDispatchState
18382                = new KeyEvent.DispatcherState();
18383
18384        /**
18385         * Indicates whether the view's window currently has the focus.
18386         */
18387        boolean mHasWindowFocus;
18388
18389        /**
18390         * The current visibility of the window.
18391         */
18392        int mWindowVisibility;
18393
18394        /**
18395         * Indicates the time at which drawing started to occur.
18396         */
18397        long mDrawingTime;
18398
18399        /**
18400         * Indicates whether or not ignoring the DIRTY_MASK flags.
18401         */
18402        boolean mIgnoreDirtyState;
18403
18404        /**
18405         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
18406         * to avoid clearing that flag prematurely.
18407         */
18408        boolean mSetIgnoreDirtyState = false;
18409
18410        /**
18411         * Indicates whether the view's window is currently in touch mode.
18412         */
18413        boolean mInTouchMode;
18414
18415        /**
18416         * Indicates that ViewAncestor should trigger a global layout change
18417         * the next time it performs a traversal
18418         */
18419        boolean mRecomputeGlobalAttributes;
18420
18421        /**
18422         * Always report new attributes at next traversal.
18423         */
18424        boolean mForceReportNewAttributes;
18425
18426        /**
18427         * Set during a traveral if any views want to keep the screen on.
18428         */
18429        boolean mKeepScreenOn;
18430
18431        /**
18432         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
18433         */
18434        int mSystemUiVisibility;
18435
18436        /**
18437         * Hack to force certain system UI visibility flags to be cleared.
18438         */
18439        int mDisabledSystemUiVisibility;
18440
18441        /**
18442         * Last global system UI visibility reported by the window manager.
18443         */
18444        int mGlobalSystemUiVisibility;
18445
18446        /**
18447         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
18448         * attached.
18449         */
18450        boolean mHasSystemUiListeners;
18451
18452        /**
18453         * Set if the window has requested to extend into the overscan region
18454         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
18455         */
18456        boolean mOverscanRequested;
18457
18458        /**
18459         * Set if the visibility of any views has changed.
18460         */
18461        boolean mViewVisibilityChanged;
18462
18463        /**
18464         * Set to true if a view has been scrolled.
18465         */
18466        boolean mViewScrollChanged;
18467
18468        /**
18469         * Global to the view hierarchy used as a temporary for dealing with
18470         * x/y points in the transparent region computations.
18471         */
18472        final int[] mTransparentLocation = new int[2];
18473
18474        /**
18475         * Global to the view hierarchy used as a temporary for dealing with
18476         * x/y points in the ViewGroup.invalidateChild implementation.
18477         */
18478        final int[] mInvalidateChildLocation = new int[2];
18479
18480
18481        /**
18482         * Global to the view hierarchy used as a temporary for dealing with
18483         * x/y location when view is transformed.
18484         */
18485        final float[] mTmpTransformLocation = new float[2];
18486
18487        /**
18488         * The view tree observer used to dispatch global events like
18489         * layout, pre-draw, touch mode change, etc.
18490         */
18491        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
18492
18493        /**
18494         * A Canvas used by the view hierarchy to perform bitmap caching.
18495         */
18496        Canvas mCanvas;
18497
18498        /**
18499         * The view root impl.
18500         */
18501        final ViewRootImpl mViewRootImpl;
18502
18503        /**
18504         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
18505         * handler can be used to pump events in the UI events queue.
18506         */
18507        final Handler mHandler;
18508
18509        /**
18510         * Temporary for use in computing invalidate rectangles while
18511         * calling up the hierarchy.
18512         */
18513        final Rect mTmpInvalRect = new Rect();
18514
18515        /**
18516         * Temporary for use in computing hit areas with transformed views
18517         */
18518        final RectF mTmpTransformRect = new RectF();
18519
18520        /**
18521         * Temporary for use in transforming invalidation rect
18522         */
18523        final Matrix mTmpMatrix = new Matrix();
18524
18525        /**
18526         * Temporary for use in transforming invalidation rect
18527         */
18528        final Transformation mTmpTransformation = new Transformation();
18529
18530        /**
18531         * Temporary list for use in collecting focusable descendents of a view.
18532         */
18533        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
18534
18535        /**
18536         * The id of the window for accessibility purposes.
18537         */
18538        int mAccessibilityWindowId = View.NO_ID;
18539
18540        /**
18541         * Flags related to accessibility processing.
18542         *
18543         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
18544         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
18545         */
18546        int mAccessibilityFetchFlags;
18547
18548        /**
18549         * The drawable for highlighting accessibility focus.
18550         */
18551        Drawable mAccessibilityFocusDrawable;
18552
18553        /**
18554         * Show where the margins, bounds and layout bounds are for each view.
18555         */
18556        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
18557
18558        /**
18559         * Point used to compute visible regions.
18560         */
18561        final Point mPoint = new Point();
18562
18563        /**
18564         * Used to track which View originated a requestLayout() call, used when
18565         * requestLayout() is called during layout.
18566         */
18567        View mViewRequestingLayout;
18568
18569        /**
18570         * Creates a new set of attachment information with the specified
18571         * events handler and thread.
18572         *
18573         * @param handler the events handler the view must use
18574         */
18575        AttachInfo(IWindowSession session, IWindow window, Display display,
18576                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
18577            mSession = session;
18578            mWindow = window;
18579            mWindowToken = window.asBinder();
18580            mDisplay = display;
18581            mViewRootImpl = viewRootImpl;
18582            mHandler = handler;
18583            mRootCallbacks = effectPlayer;
18584        }
18585    }
18586
18587    /**
18588     * <p>ScrollabilityCache holds various fields used by a View when scrolling
18589     * is supported. This avoids keeping too many unused fields in most
18590     * instances of View.</p>
18591     */
18592    private static class ScrollabilityCache implements Runnable {
18593
18594        /**
18595         * Scrollbars are not visible
18596         */
18597        public static final int OFF = 0;
18598
18599        /**
18600         * Scrollbars are visible
18601         */
18602        public static final int ON = 1;
18603
18604        /**
18605         * Scrollbars are fading away
18606         */
18607        public static final int FADING = 2;
18608
18609        public boolean fadeScrollBars;
18610
18611        public int fadingEdgeLength;
18612        public int scrollBarDefaultDelayBeforeFade;
18613        public int scrollBarFadeDuration;
18614
18615        public int scrollBarSize;
18616        public ScrollBarDrawable scrollBar;
18617        public float[] interpolatorValues;
18618        public View host;
18619
18620        public final Paint paint;
18621        public final Matrix matrix;
18622        public Shader shader;
18623
18624        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
18625
18626        private static final float[] OPAQUE = { 255 };
18627        private static final float[] TRANSPARENT = { 0.0f };
18628
18629        /**
18630         * When fading should start. This time moves into the future every time
18631         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
18632         */
18633        public long fadeStartTime;
18634
18635
18636        /**
18637         * The current state of the scrollbars: ON, OFF, or FADING
18638         */
18639        public int state = OFF;
18640
18641        private int mLastColor;
18642
18643        public ScrollabilityCache(ViewConfiguration configuration, View host) {
18644            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
18645            scrollBarSize = configuration.getScaledScrollBarSize();
18646            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
18647            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
18648
18649            paint = new Paint();
18650            matrix = new Matrix();
18651            // use use a height of 1, and then wack the matrix each time we
18652            // actually use it.
18653            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
18654            paint.setShader(shader);
18655            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
18656
18657            this.host = host;
18658        }
18659
18660        public void setFadeColor(int color) {
18661            if (color != mLastColor) {
18662                mLastColor = color;
18663
18664                if (color != 0) {
18665                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
18666                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
18667                    paint.setShader(shader);
18668                    // Restore the default transfer mode (src_over)
18669                    paint.setXfermode(null);
18670                } else {
18671                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
18672                    paint.setShader(shader);
18673                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
18674                }
18675            }
18676        }
18677
18678        public void run() {
18679            long now = AnimationUtils.currentAnimationTimeMillis();
18680            if (now >= fadeStartTime) {
18681
18682                // the animation fades the scrollbars out by changing
18683                // the opacity (alpha) from fully opaque to fully
18684                // transparent
18685                int nextFrame = (int) now;
18686                int framesCount = 0;
18687
18688                Interpolator interpolator = scrollBarInterpolator;
18689
18690                // Start opaque
18691                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
18692
18693                // End transparent
18694                nextFrame += scrollBarFadeDuration;
18695                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
18696
18697                state = FADING;
18698
18699                // Kick off the fade animation
18700                host.invalidate(true);
18701            }
18702        }
18703    }
18704
18705    /**
18706     * Resuable callback for sending
18707     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
18708     */
18709    private class SendViewScrolledAccessibilityEvent implements Runnable {
18710        public volatile boolean mIsPending;
18711
18712        public void run() {
18713            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
18714            mIsPending = false;
18715        }
18716    }
18717
18718    /**
18719     * <p>
18720     * This class represents a delegate that can be registered in a {@link View}
18721     * to enhance accessibility support via composition rather via inheritance.
18722     * It is specifically targeted to widget developers that extend basic View
18723     * classes i.e. classes in package android.view, that would like their
18724     * applications to be backwards compatible.
18725     * </p>
18726     * <div class="special reference">
18727     * <h3>Developer Guides</h3>
18728     * <p>For more information about making applications accessible, read the
18729     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
18730     * developer guide.</p>
18731     * </div>
18732     * <p>
18733     * A scenario in which a developer would like to use an accessibility delegate
18734     * is overriding a method introduced in a later API version then the minimal API
18735     * version supported by the application. For example, the method
18736     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
18737     * in API version 4 when the accessibility APIs were first introduced. If a
18738     * developer would like his application to run on API version 4 devices (assuming
18739     * all other APIs used by the application are version 4 or lower) and take advantage
18740     * of this method, instead of overriding the method which would break the application's
18741     * backwards compatibility, he can override the corresponding method in this
18742     * delegate and register the delegate in the target View if the API version of
18743     * the system is high enough i.e. the API version is same or higher to the API
18744     * version that introduced
18745     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
18746     * </p>
18747     * <p>
18748     * Here is an example implementation:
18749     * </p>
18750     * <code><pre><p>
18751     * if (Build.VERSION.SDK_INT >= 14) {
18752     *     // If the API version is equal of higher than the version in
18753     *     // which onInitializeAccessibilityNodeInfo was introduced we
18754     *     // register a delegate with a customized implementation.
18755     *     View view = findViewById(R.id.view_id);
18756     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
18757     *         public void onInitializeAccessibilityNodeInfo(View host,
18758     *                 AccessibilityNodeInfo info) {
18759     *             // Let the default implementation populate the info.
18760     *             super.onInitializeAccessibilityNodeInfo(host, info);
18761     *             // Set some other information.
18762     *             info.setEnabled(host.isEnabled());
18763     *         }
18764     *     });
18765     * }
18766     * </code></pre></p>
18767     * <p>
18768     * This delegate contains methods that correspond to the accessibility methods
18769     * in View. If a delegate has been specified the implementation in View hands
18770     * off handling to the corresponding method in this delegate. The default
18771     * implementation the delegate methods behaves exactly as the corresponding
18772     * method in View for the case of no accessibility delegate been set. Hence,
18773     * to customize the behavior of a View method, clients can override only the
18774     * corresponding delegate method without altering the behavior of the rest
18775     * accessibility related methods of the host view.
18776     * </p>
18777     */
18778    public static class AccessibilityDelegate {
18779
18780        /**
18781         * Sends an accessibility event of the given type. If accessibility is not
18782         * enabled this method has no effect.
18783         * <p>
18784         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
18785         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
18786         * been set.
18787         * </p>
18788         *
18789         * @param host The View hosting the delegate.
18790         * @param eventType The type of the event to send.
18791         *
18792         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
18793         */
18794        public void sendAccessibilityEvent(View host, int eventType) {
18795            host.sendAccessibilityEventInternal(eventType);
18796        }
18797
18798        /**
18799         * Performs the specified accessibility action on the view. For
18800         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
18801         * <p>
18802         * The default implementation behaves as
18803         * {@link View#performAccessibilityAction(int, Bundle)
18804         *  View#performAccessibilityAction(int, Bundle)} for the case of
18805         *  no accessibility delegate been set.
18806         * </p>
18807         *
18808         * @param action The action to perform.
18809         * @return Whether the action was performed.
18810         *
18811         * @see View#performAccessibilityAction(int, Bundle)
18812         *      View#performAccessibilityAction(int, Bundle)
18813         */
18814        public boolean performAccessibilityAction(View host, int action, Bundle args) {
18815            return host.performAccessibilityActionInternal(action, args);
18816        }
18817
18818        /**
18819         * Sends an accessibility event. This method behaves exactly as
18820         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
18821         * empty {@link AccessibilityEvent} and does not perform a check whether
18822         * accessibility is enabled.
18823         * <p>
18824         * The default implementation behaves as
18825         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
18826         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
18827         * the case of no accessibility delegate been set.
18828         * </p>
18829         *
18830         * @param host The View hosting the delegate.
18831         * @param event The event to send.
18832         *
18833         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
18834         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
18835         */
18836        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
18837            host.sendAccessibilityEventUncheckedInternal(event);
18838        }
18839
18840        /**
18841         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
18842         * to its children for adding their text content to the event.
18843         * <p>
18844         * The default implementation behaves as
18845         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
18846         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
18847         * the case of no accessibility delegate been set.
18848         * </p>
18849         *
18850         * @param host The View hosting the delegate.
18851         * @param event The event.
18852         * @return True if the event population was completed.
18853         *
18854         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
18855         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
18856         */
18857        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
18858            return host.dispatchPopulateAccessibilityEventInternal(event);
18859        }
18860
18861        /**
18862         * Gives a chance to the host View to populate the accessibility event with its
18863         * text content.
18864         * <p>
18865         * The default implementation behaves as
18866         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
18867         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
18868         * the case of no accessibility delegate been set.
18869         * </p>
18870         *
18871         * @param host The View hosting the delegate.
18872         * @param event The accessibility event which to populate.
18873         *
18874         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
18875         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
18876         */
18877        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
18878            host.onPopulateAccessibilityEventInternal(event);
18879        }
18880
18881        /**
18882         * Initializes an {@link AccessibilityEvent} with information about the
18883         * the host View which is the event source.
18884         * <p>
18885         * The default implementation behaves as
18886         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
18887         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
18888         * the case of no accessibility delegate been set.
18889         * </p>
18890         *
18891         * @param host The View hosting the delegate.
18892         * @param event The event to initialize.
18893         *
18894         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
18895         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
18896         */
18897        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
18898            host.onInitializeAccessibilityEventInternal(event);
18899        }
18900
18901        /**
18902         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
18903         * <p>
18904         * The default implementation behaves as
18905         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
18906         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
18907         * the case of no accessibility delegate been set.
18908         * </p>
18909         *
18910         * @param host The View hosting the delegate.
18911         * @param info The instance to initialize.
18912         *
18913         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
18914         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
18915         */
18916        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
18917            host.onInitializeAccessibilityNodeInfoInternal(info);
18918        }
18919
18920        /**
18921         * Called when a child of the host View has requested sending an
18922         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
18923         * to augment the event.
18924         * <p>
18925         * The default implementation behaves as
18926         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
18927         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
18928         * the case of no accessibility delegate been set.
18929         * </p>
18930         *
18931         * @param host The View hosting the delegate.
18932         * @param child The child which requests sending the event.
18933         * @param event The event to be sent.
18934         * @return True if the event should be sent
18935         *
18936         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
18937         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
18938         */
18939        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
18940                AccessibilityEvent event) {
18941            return host.onRequestSendAccessibilityEventInternal(child, event);
18942        }
18943
18944        /**
18945         * Gets the provider for managing a virtual view hierarchy rooted at this View
18946         * and reported to {@link android.accessibilityservice.AccessibilityService}s
18947         * that explore the window content.
18948         * <p>
18949         * The default implementation behaves as
18950         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
18951         * the case of no accessibility delegate been set.
18952         * </p>
18953         *
18954         * @return The provider.
18955         *
18956         * @see AccessibilityNodeProvider
18957         */
18958        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
18959            return null;
18960        }
18961
18962        /**
18963         * Returns an {@link AccessibilityNodeInfo} representing the host view from the
18964         * point of view of an {@link android.accessibilityservice.AccessibilityService}.
18965         * This method is responsible for obtaining an accessibility node info from a
18966         * pool of reusable instances and calling
18967         * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host
18968         * view to initialize the former.
18969         * <p>
18970         * <strong>Note:</strong> The client is responsible for recycling the obtained
18971         * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object
18972         * creation.
18973         * </p>
18974         * <p>
18975         * The default implementation behaves as
18976         * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for
18977         * the case of no accessibility delegate been set.
18978         * </p>
18979         * @return A populated {@link AccessibilityNodeInfo}.
18980         *
18981         * @see AccessibilityNodeInfo
18982         *
18983         * @hide
18984         */
18985        public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) {
18986            return host.createAccessibilityNodeInfoInternal();
18987        }
18988    }
18989
18990    private class MatchIdPredicate implements Predicate<View> {
18991        public int mId;
18992
18993        @Override
18994        public boolean apply(View view) {
18995            return (view.mID == mId);
18996        }
18997    }
18998
18999    private class MatchLabelForPredicate implements Predicate<View> {
19000        private int mLabeledId;
19001
19002        @Override
19003        public boolean apply(View view) {
19004            return (view.mLabelForId == mLabeledId);
19005        }
19006    }
19007
19008    private class SendViewStateChangedAccessibilityEvent implements Runnable {
19009        private boolean mPosted;
19010        private long mLastEventTimeMillis;
19011
19012        public void run() {
19013            mPosted = false;
19014            mLastEventTimeMillis = SystemClock.uptimeMillis();
19015            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
19016                AccessibilityEvent event = AccessibilityEvent.obtain();
19017                event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
19018                event.setContentChangeType(AccessibilityEvent.CONTENT_CHANGE_TYPE_NODE);
19019                sendAccessibilityEventUnchecked(event);
19020            }
19021        }
19022
19023        public void runOrPost() {
19024            if (mPosted) {
19025                return;
19026            }
19027            final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
19028            final long minEventIntevalMillis =
19029                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
19030            if (timeSinceLastMillis >= minEventIntevalMillis) {
19031                removeCallbacks(this);
19032                run();
19033            } else {
19034                postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
19035                mPosted = true;
19036            }
19037        }
19038    }
19039
19040    /**
19041     * Dump all private flags in readable format, useful for documentation and
19042     * sanity checking.
19043     */
19044    private static void dumpFlags() {
19045        final HashMap<String, String> found = Maps.newHashMap();
19046        try {
19047            for (Field field : View.class.getDeclaredFields()) {
19048                final int modifiers = field.getModifiers();
19049                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
19050                    if (field.getType().equals(int.class)) {
19051                        final int value = field.getInt(null);
19052                        dumpFlag(found, field.getName(), value);
19053                    } else if (field.getType().equals(int[].class)) {
19054                        final int[] values = (int[]) field.get(null);
19055                        for (int i = 0; i < values.length; i++) {
19056                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
19057                        }
19058                    }
19059                }
19060            }
19061        } catch (IllegalAccessException e) {
19062            throw new RuntimeException(e);
19063        }
19064
19065        final ArrayList<String> keys = Lists.newArrayList();
19066        keys.addAll(found.keySet());
19067        Collections.sort(keys);
19068        for (String key : keys) {
19069            Log.d(VIEW_LOG_TAG, found.get(key));
19070        }
19071    }
19072
19073    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
19074        // Sort flags by prefix, then by bits, always keeping unique keys
19075        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
19076        final int prefix = name.indexOf('_');
19077        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
19078        final String output = bits + " " + name;
19079        found.put(key, output);
19080    }
19081}
19082