View.java revision 25b0c3096131e532e57f5aac48769430dca42c75
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.Log;
55import android.util.LongSparseLongArray;
56import android.util.Pools.SynchronizedPool;
57import android.util.Property;
58import android.util.SparseArray;
59import android.util.TypedValue;
60import android.view.ContextMenu.ContextMenuInfo;
61import android.view.AccessibilityIterators.TextSegmentIterator;
62import android.view.AccessibilityIterators.CharacterTextSegmentIterator;
63import android.view.AccessibilityIterators.WordTextSegmentIterator;
64import android.view.AccessibilityIterators.ParagraphTextSegmentIterator;
65import android.view.accessibility.AccessibilityEvent;
66import android.view.accessibility.AccessibilityEventSource;
67import android.view.accessibility.AccessibilityManager;
68import android.view.accessibility.AccessibilityNodeInfo;
69import android.view.accessibility.AccessibilityNodeProvider;
70import android.view.animation.Animation;
71import android.view.animation.AnimationUtils;
72import android.view.animation.Transformation;
73import android.view.inputmethod.EditorInfo;
74import android.view.inputmethod.InputConnection;
75import android.view.inputmethod.InputMethodManager;
76import android.view.transition.Scene;
77import android.widget.ScrollBarDrawable;
78
79import static android.os.Build.VERSION_CODES.*;
80import static java.lang.Math.max;
81
82import com.android.internal.R;
83import com.android.internal.util.Predicate;
84import com.android.internal.view.menu.MenuBuilder;
85import com.google.android.collect.Lists;
86import com.google.android.collect.Maps;
87
88import java.lang.ref.WeakReference;
89import java.lang.reflect.Field;
90import java.lang.reflect.InvocationTargetException;
91import java.lang.reflect.Method;
92import java.lang.reflect.Modifier;
93import java.util.ArrayList;
94import java.util.Arrays;
95import java.util.Collections;
96import java.util.HashMap;
97import java.util.Locale;
98import java.util.concurrent.CopyOnWriteArrayList;
99import java.util.concurrent.atomic.AtomicInteger;
100
101/**
102 * <p>
103 * This class represents the basic building block for user interface components. A View
104 * occupies a rectangular area on the screen and is responsible for drawing and
105 * event handling. View is the base class for <em>widgets</em>, which are
106 * used to create interactive UI components (buttons, text fields, etc.). The
107 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
108 * are invisible containers that hold other Views (or other ViewGroups) and define
109 * their layout properties.
110 * </p>
111 *
112 * <div class="special reference">
113 * <h3>Developer Guides</h3>
114 * <p>For information about using this class to develop your application's user interface,
115 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
116 * </div>
117 *
118 * <a name="Using"></a>
119 * <h3>Using Views</h3>
120 * <p>
121 * All of the views in a window are arranged in a single tree. You can add views
122 * either from code or by specifying a tree of views in one or more XML layout
123 * files. There are many specialized subclasses of views that act as controls or
124 * are capable of displaying text, images, or other content.
125 * </p>
126 * <p>
127 * Once you have created a tree of views, there are typically a few types of
128 * common operations you may wish to perform:
129 * <ul>
130 * <li><strong>Set properties:</strong> for example setting the text of a
131 * {@link android.widget.TextView}. The available properties and the methods
132 * that set them will vary among the different subclasses of views. Note that
133 * properties that are known at build time can be set in the XML layout
134 * files.</li>
135 * <li><strong>Set focus:</strong> The framework will handled moving focus in
136 * response to user input. To force focus to a specific view, call
137 * {@link #requestFocus}.</li>
138 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
139 * that will be notified when something interesting happens to the view. For
140 * example, all views will let you set a listener to be notified when the view
141 * gains or loses focus. You can register such a listener using
142 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
143 * Other view subclasses offer more specialized listeners. For example, a Button
144 * exposes a listener to notify clients when the button is clicked.</li>
145 * <li><strong>Set visibility:</strong> You can hide or show views using
146 * {@link #setVisibility(int)}.</li>
147 * </ul>
148 * </p>
149 * <p><em>
150 * Note: The Android framework is responsible for measuring, laying out and
151 * drawing views. You should not call methods that perform these actions on
152 * views yourself unless you are actually implementing a
153 * {@link android.view.ViewGroup}.
154 * </em></p>
155 *
156 * <a name="Lifecycle"></a>
157 * <h3>Implementing a Custom View</h3>
158 *
159 * <p>
160 * To implement a custom view, you will usually begin by providing overrides for
161 * some of the standard methods that the framework calls on all views. You do
162 * not need to override all of these methods. In fact, you can start by just
163 * overriding {@link #onDraw(android.graphics.Canvas)}.
164 * <table border="2" width="85%" align="center" cellpadding="5">
165 *     <thead>
166 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
167 *     </thead>
168 *
169 *     <tbody>
170 *     <tr>
171 *         <td rowspan="2">Creation</td>
172 *         <td>Constructors</td>
173 *         <td>There is a form of the constructor that are called when the view
174 *         is created from code and a form that is called when the view is
175 *         inflated from a layout file. The second form should parse and apply
176 *         any attributes defined in the layout file.
177 *         </td>
178 *     </tr>
179 *     <tr>
180 *         <td><code>{@link #onFinishInflate()}</code></td>
181 *         <td>Called after a view and all of its children has been inflated
182 *         from XML.</td>
183 *     </tr>
184 *
185 *     <tr>
186 *         <td rowspan="3">Layout</td>
187 *         <td><code>{@link #onMeasure(int, int)}</code></td>
188 *         <td>Called to determine the size requirements for this view and all
189 *         of its children.
190 *         </td>
191 *     </tr>
192 *     <tr>
193 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
194 *         <td>Called when this view should assign a size and position to all
195 *         of its children.
196 *         </td>
197 *     </tr>
198 *     <tr>
199 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
200 *         <td>Called when the size of this view has changed.
201 *         </td>
202 *     </tr>
203 *
204 *     <tr>
205 *         <td>Drawing</td>
206 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
207 *         <td>Called when the view should render its content.
208 *         </td>
209 *     </tr>
210 *
211 *     <tr>
212 *         <td rowspan="4">Event processing</td>
213 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
214 *         <td>Called when a new hardware key event occurs.
215 *         </td>
216 *     </tr>
217 *     <tr>
218 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
219 *         <td>Called when a hardware key up event occurs.
220 *         </td>
221 *     </tr>
222 *     <tr>
223 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
224 *         <td>Called when a trackball motion event occurs.
225 *         </td>
226 *     </tr>
227 *     <tr>
228 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
229 *         <td>Called when a touch screen motion event occurs.
230 *         </td>
231 *     </tr>
232 *
233 *     <tr>
234 *         <td rowspan="2">Focus</td>
235 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
236 *         <td>Called when the view gains or loses focus.
237 *         </td>
238 *     </tr>
239 *
240 *     <tr>
241 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
242 *         <td>Called when the window containing the view gains or loses focus.
243 *         </td>
244 *     </tr>
245 *
246 *     <tr>
247 *         <td rowspan="3">Attaching</td>
248 *         <td><code>{@link #onAttachedToWindow()}</code></td>
249 *         <td>Called when the view is attached to a window.
250 *         </td>
251 *     </tr>
252 *
253 *     <tr>
254 *         <td><code>{@link #onDetachedFromWindow}</code></td>
255 *         <td>Called when the view is detached from its window.
256 *         </td>
257 *     </tr>
258 *
259 *     <tr>
260 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
261 *         <td>Called when the visibility of the window containing the view
262 *         has changed.
263 *         </td>
264 *     </tr>
265 *     </tbody>
266 *
267 * </table>
268 * </p>
269 *
270 * <a name="IDs"></a>
271 * <h3>IDs</h3>
272 * Views may have an integer id associated with them. These ids are typically
273 * assigned in the layout XML files, and are used to find specific views within
274 * the view tree. A common pattern is to:
275 * <ul>
276 * <li>Define a Button in the layout file and assign it a unique ID.
277 * <pre>
278 * &lt;Button
279 *     android:id="@+id/my_button"
280 *     android:layout_width="wrap_content"
281 *     android:layout_height="wrap_content"
282 *     android:text="@string/my_button_text"/&gt;
283 * </pre></li>
284 * <li>From the onCreate method of an Activity, find the Button
285 * <pre class="prettyprint">
286 *      Button myButton = (Button) findViewById(R.id.my_button);
287 * </pre></li>
288 * </ul>
289 * <p>
290 * View IDs need not be unique throughout the tree, but it is good practice to
291 * ensure that they are at least unique within the part of the tree you are
292 * searching.
293 * </p>
294 *
295 * <a name="Position"></a>
296 * <h3>Position</h3>
297 * <p>
298 * The geometry of a view is that of a rectangle. A view has a location,
299 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
300 * two dimensions, expressed as a width and a height. The unit for location
301 * and dimensions is the pixel.
302 * </p>
303 *
304 * <p>
305 * It is possible to retrieve the location of a view by invoking the methods
306 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
307 * coordinate of the rectangle representing the view. The latter returns the
308 * top, or Y, coordinate of the rectangle representing the view. These methods
309 * both return the location of the view relative to its parent. For instance,
310 * when getLeft() returns 20, that means the view is located 20 pixels to the
311 * right of the left edge of its direct parent.
312 * </p>
313 *
314 * <p>
315 * In addition, several convenience methods are offered to avoid unnecessary
316 * computations, namely {@link #getRight()} and {@link #getBottom()}.
317 * These methods return the coordinates of the right and bottom edges of the
318 * rectangle representing the view. For instance, calling {@link #getRight()}
319 * is similar to the following computation: <code>getLeft() + getWidth()</code>
320 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
321 * </p>
322 *
323 * <a name="SizePaddingMargins"></a>
324 * <h3>Size, padding and margins</h3>
325 * <p>
326 * The size of a view is expressed with a width and a height. A view actually
327 * possess two pairs of width and height values.
328 * </p>
329 *
330 * <p>
331 * The first pair is known as <em>measured width</em> and
332 * <em>measured height</em>. These dimensions define how big a view wants to be
333 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
334 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
335 * and {@link #getMeasuredHeight()}.
336 * </p>
337 *
338 * <p>
339 * The second pair is simply known as <em>width</em> and <em>height</em>, or
340 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
341 * dimensions define the actual size of the view on screen, at drawing time and
342 * after layout. These values may, but do not have to, be different from the
343 * measured width and height. The width and height can be obtained by calling
344 * {@link #getWidth()} and {@link #getHeight()}.
345 * </p>
346 *
347 * <p>
348 * To measure its dimensions, a view takes into account its padding. The padding
349 * is expressed in pixels for the left, top, right and bottom parts of the view.
350 * Padding can be used to offset the content of the view by a specific amount of
351 * pixels. For instance, a left padding of 2 will push the view's content by
352 * 2 pixels to the right of the left edge. Padding can be set using the
353 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)}
354 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()},
355 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()},
356 * {@link #getPaddingEnd()}.
357 * </p>
358 *
359 * <p>
360 * Even though a view can define a padding, it does not provide any support for
361 * margins. However, view groups provide such a support. Refer to
362 * {@link android.view.ViewGroup} and
363 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
364 * </p>
365 *
366 * <a name="Layout"></a>
367 * <h3>Layout</h3>
368 * <p>
369 * Layout is a two pass process: a measure pass and a layout pass. The measuring
370 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
371 * of the view tree. Each view pushes dimension specifications down the tree
372 * during the recursion. At the end of the measure pass, every view has stored
373 * its measurements. The second pass happens in
374 * {@link #layout(int,int,int,int)} and is also top-down. During
375 * this pass each parent is responsible for positioning all of its children
376 * using the sizes computed in the measure pass.
377 * </p>
378 *
379 * <p>
380 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
381 * {@link #getMeasuredHeight()} values must be set, along with those for all of
382 * that view's descendants. A view's measured width and measured height values
383 * must respect the constraints imposed by the view's parents. This guarantees
384 * that at the end of the measure pass, all parents accept all of their
385 * children's measurements. A parent view may call measure() more than once on
386 * its children. For example, the parent may measure each child once with
387 * unspecified dimensions to find out how big they want to be, then call
388 * measure() on them again with actual numbers if the sum of all the children's
389 * unconstrained sizes is too big or too small.
390 * </p>
391 *
392 * <p>
393 * The measure pass uses two classes to communicate dimensions. The
394 * {@link MeasureSpec} class is used by views to tell their parents how they
395 * want to be measured and positioned. The base LayoutParams class just
396 * describes how big the view wants to be for both width and height. For each
397 * dimension, it can specify one of:
398 * <ul>
399 * <li> an exact number
400 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
401 * (minus padding)
402 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
403 * enclose its content (plus padding).
404 * </ul>
405 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
406 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
407 * an X and Y value.
408 * </p>
409 *
410 * <p>
411 * MeasureSpecs are used to push requirements down the tree from parent to
412 * child. A MeasureSpec can be in one of three modes:
413 * <ul>
414 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
415 * of a child view. For example, a LinearLayout may call measure() on its child
416 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
417 * tall the child view wants to be given a width of 240 pixels.
418 * <li>EXACTLY: This is used by the parent to impose an exact size on the
419 * child. The child must use this size, and guarantee that all of its
420 * descendants will fit within this size.
421 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
422 * child. The child must gurantee that it and all of its descendants will fit
423 * within this size.
424 * </ul>
425 * </p>
426 *
427 * <p>
428 * To intiate a layout, call {@link #requestLayout}. This method is typically
429 * called by a view on itself when it believes that is can no longer fit within
430 * its current bounds.
431 * </p>
432 *
433 * <a name="Drawing"></a>
434 * <h3>Drawing</h3>
435 * <p>
436 * Drawing is handled by walking the tree and rendering each view that
437 * intersects the invalid region. Because the tree is traversed in-order,
438 * this means that parents will draw before (i.e., behind) their children, with
439 * siblings drawn in the order they appear in the tree.
440 * If you set a background drawable for a View, then the View will draw it for you
441 * before calling back to its <code>onDraw()</code> method.
442 * </p>
443 *
444 * <p>
445 * Note that the framework will not draw views that are not in the invalid region.
446 * </p>
447 *
448 * <p>
449 * To force a view to draw, call {@link #invalidate()}.
450 * </p>
451 *
452 * <a name="EventHandlingThreading"></a>
453 * <h3>Event Handling and Threading</h3>
454 * <p>
455 * The basic cycle of a view is as follows:
456 * <ol>
457 * <li>An event comes in and is dispatched to the appropriate view. The view
458 * handles the event and notifies any listeners.</li>
459 * <li>If in the course of processing the event, the view's bounds may need
460 * to be changed, the view will call {@link #requestLayout()}.</li>
461 * <li>Similarly, if in the course of processing the event the view's appearance
462 * may need to be changed, the view will call {@link #invalidate()}.</li>
463 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
464 * the framework will take care of measuring, laying out, and drawing the tree
465 * as appropriate.</li>
466 * </ol>
467 * </p>
468 *
469 * <p><em>Note: The entire view tree is single threaded. You must always be on
470 * the UI thread when calling any method on any view.</em>
471 * If you are doing work on other threads and want to update the state of a view
472 * from that thread, you should use a {@link Handler}.
473 * </p>
474 *
475 * <a name="FocusHandling"></a>
476 * <h3>Focus Handling</h3>
477 * <p>
478 * The framework will handle routine focus movement in response to user input.
479 * This includes changing the focus as views are removed or hidden, or as new
480 * views become available. Views indicate their willingness to take focus
481 * through the {@link #isFocusable} method. To change whether a view can take
482 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
483 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
484 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
485 * </p>
486 * <p>
487 * Focus movement is based on an algorithm which finds the nearest neighbor in a
488 * given direction. In rare cases, the default algorithm may not match the
489 * intended behavior of the developer. In these situations, you can provide
490 * explicit overrides by using these XML attributes in the layout file:
491 * <pre>
492 * nextFocusDown
493 * nextFocusLeft
494 * nextFocusRight
495 * nextFocusUp
496 * </pre>
497 * </p>
498 *
499 *
500 * <p>
501 * To get a particular view to take focus, call {@link #requestFocus()}.
502 * </p>
503 *
504 * <a name="TouchMode"></a>
505 * <h3>Touch Mode</h3>
506 * <p>
507 * When a user is navigating a user interface via directional keys such as a D-pad, it is
508 * necessary to give focus to actionable items such as buttons so the user can see
509 * what will take input.  If the device has touch capabilities, however, and the user
510 * begins interacting with the interface by touching it, it is no longer necessary to
511 * always highlight, or give focus to, a particular view.  This motivates a mode
512 * for interaction named 'touch mode'.
513 * </p>
514 * <p>
515 * For a touch capable device, once the user touches the screen, the device
516 * will enter touch mode.  From this point onward, only views for which
517 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
518 * Other views that are touchable, like buttons, will not take focus when touched; they will
519 * only fire the on click listeners.
520 * </p>
521 * <p>
522 * Any time a user hits a directional key, such as a D-pad direction, the view device will
523 * exit touch mode, and find a view to take focus, so that the user may resume interacting
524 * with the user interface without touching the screen again.
525 * </p>
526 * <p>
527 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
528 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
529 * </p>
530 *
531 * <a name="Scrolling"></a>
532 * <h3>Scrolling</h3>
533 * <p>
534 * The framework provides basic support for views that wish to internally
535 * scroll their content. This includes keeping track of the X and Y scroll
536 * offset as well as mechanisms for drawing scrollbars. See
537 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
538 * {@link #awakenScrollBars()} for more details.
539 * </p>
540 *
541 * <a name="Tags"></a>
542 * <h3>Tags</h3>
543 * <p>
544 * Unlike IDs, tags are not used to identify views. Tags are essentially an
545 * extra piece of information that can be associated with a view. They are most
546 * often used as a convenience to store data related to views in the views
547 * themselves rather than by putting them in a separate structure.
548 * </p>
549 *
550 * <a name="Properties"></a>
551 * <h3>Properties</h3>
552 * <p>
553 * The View class exposes an {@link #ALPHA} property, as well as several transform-related
554 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are
555 * available both in the {@link Property} form as well as in similarly-named setter/getter
556 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can
557 * be used to set persistent state associated with these rendering-related properties on the view.
558 * The properties and methods can also be used in conjunction with
559 * {@link android.animation.Animator Animator}-based animations, described more in the
560 * <a href="#Animation">Animation</a> section.
561 * </p>
562 *
563 * <a name="Animation"></a>
564 * <h3>Animation</h3>
565 * <p>
566 * Starting with Android 3.0, the preferred way of animating views is to use the
567 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based
568 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and
569 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0
570 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only
571 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class
572 * makes animating these View properties particularly easy and efficient.
573 * </p>
574 * <p>
575 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered.
576 * You can attach an {@link Animation} object to a view using
577 * {@link #setAnimation(Animation)} or
578 * {@link #startAnimation(Animation)}. The animation can alter the scale,
579 * rotation, translation and alpha of a view over time. If the animation is
580 * attached to a view that has children, the animation will affect the entire
581 * subtree rooted by that node. When an animation is started, the framework will
582 * take care of redrawing the appropriate views until the animation completes.
583 * </p>
584 *
585 * <a name="Security"></a>
586 * <h3>Security</h3>
587 * <p>
588 * Sometimes it is essential that an application be able to verify that an action
589 * is being performed with the full knowledge and consent of the user, such as
590 * granting a permission request, making a purchase or clicking on an advertisement.
591 * Unfortunately, a malicious application could try to spoof the user into
592 * performing these actions, unaware, by concealing the intended purpose of the view.
593 * As a remedy, the framework offers a touch filtering mechanism that can be used to
594 * improve the security of views that provide access to sensitive functionality.
595 * </p><p>
596 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
597 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
598 * will discard touches that are received whenever the view's window is obscured by
599 * another visible window.  As a result, the view will not receive touches whenever a
600 * toast, dialog or other window appears above the view's window.
601 * </p><p>
602 * For more fine-grained control over security, consider overriding the
603 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
604 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
605 * </p>
606 *
607 * @attr ref android.R.styleable#View_alpha
608 * @attr ref android.R.styleable#View_background
609 * @attr ref android.R.styleable#View_clickable
610 * @attr ref android.R.styleable#View_contentDescription
611 * @attr ref android.R.styleable#View_drawingCacheQuality
612 * @attr ref android.R.styleable#View_duplicateParentState
613 * @attr ref android.R.styleable#View_id
614 * @attr ref android.R.styleable#View_requiresFadingEdge
615 * @attr ref android.R.styleable#View_fadeScrollbars
616 * @attr ref android.R.styleable#View_fadingEdgeLength
617 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
618 * @attr ref android.R.styleable#View_fitsSystemWindows
619 * @attr ref android.R.styleable#View_isScrollContainer
620 * @attr ref android.R.styleable#View_focusable
621 * @attr ref android.R.styleable#View_focusableInTouchMode
622 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
623 * @attr ref android.R.styleable#View_keepScreenOn
624 * @attr ref android.R.styleable#View_layerType
625 * @attr ref android.R.styleable#View_layoutDirection
626 * @attr ref android.R.styleable#View_longClickable
627 * @attr ref android.R.styleable#View_minHeight
628 * @attr ref android.R.styleable#View_minWidth
629 * @attr ref android.R.styleable#View_nextFocusDown
630 * @attr ref android.R.styleable#View_nextFocusLeft
631 * @attr ref android.R.styleable#View_nextFocusRight
632 * @attr ref android.R.styleable#View_nextFocusUp
633 * @attr ref android.R.styleable#View_onClick
634 * @attr ref android.R.styleable#View_padding
635 * @attr ref android.R.styleable#View_paddingBottom
636 * @attr ref android.R.styleable#View_paddingLeft
637 * @attr ref android.R.styleable#View_paddingRight
638 * @attr ref android.R.styleable#View_paddingTop
639 * @attr ref android.R.styleable#View_paddingStart
640 * @attr ref android.R.styleable#View_paddingEnd
641 * @attr ref android.R.styleable#View_saveEnabled
642 * @attr ref android.R.styleable#View_rotation
643 * @attr ref android.R.styleable#View_rotationX
644 * @attr ref android.R.styleable#View_rotationY
645 * @attr ref android.R.styleable#View_scaleX
646 * @attr ref android.R.styleable#View_scaleY
647 * @attr ref android.R.styleable#View_scrollX
648 * @attr ref android.R.styleable#View_scrollY
649 * @attr ref android.R.styleable#View_scrollbarSize
650 * @attr ref android.R.styleable#View_scrollbarStyle
651 * @attr ref android.R.styleable#View_scrollbars
652 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
653 * @attr ref android.R.styleable#View_scrollbarFadeDuration
654 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
655 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
656 * @attr ref android.R.styleable#View_scrollbarThumbVertical
657 * @attr ref android.R.styleable#View_scrollbarTrackVertical
658 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
659 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
660 * @attr ref android.R.styleable#View_soundEffectsEnabled
661 * @attr ref android.R.styleable#View_tag
662 * @attr ref android.R.styleable#View_textAlignment
663 * @attr ref android.R.styleable#View_textDirection
664 * @attr ref android.R.styleable#View_transformPivotX
665 * @attr ref android.R.styleable#View_transformPivotY
666 * @attr ref android.R.styleable#View_translationX
667 * @attr ref android.R.styleable#View_translationY
668 * @attr ref android.R.styleable#View_visibility
669 *
670 * @see android.view.ViewGroup
671 */
672public class View implements Drawable.Callback, KeyEvent.Callback,
673        AccessibilityEventSource {
674    private static final boolean DBG = false;
675
676    /**
677     * The logging tag used by this class with android.util.Log.
678     */
679    protected static final String VIEW_LOG_TAG = "View";
680
681    /**
682     * When set to true, apps will draw debugging information about their layouts.
683     *
684     * @hide
685     */
686    public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout";
687
688    /**
689     * Used to mark a View that has no ID.
690     */
691    public static final int NO_ID = -1;
692
693    private static boolean sUseBrokenMakeMeasureSpec = false;
694
695    /**
696     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
697     * calling setFlags.
698     */
699    private static final int NOT_FOCUSABLE = 0x00000000;
700
701    /**
702     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
703     * setFlags.
704     */
705    private static final int FOCUSABLE = 0x00000001;
706
707    /**
708     * Mask for use with setFlags indicating bits used for focus.
709     */
710    private static final int FOCUSABLE_MASK = 0x00000001;
711
712    /**
713     * This view will adjust its padding to fit sytem windows (e.g. status bar)
714     */
715    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
716
717    /**
718     * This view is visible.
719     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
720     * android:visibility}.
721     */
722    public static final int VISIBLE = 0x00000000;
723
724    /**
725     * This view is invisible, but it still takes up space for layout purposes.
726     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
727     * android:visibility}.
728     */
729    public static final int INVISIBLE = 0x00000004;
730
731    /**
732     * This view is invisible, and it doesn't take any space for layout
733     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
734     * android:visibility}.
735     */
736    public static final int GONE = 0x00000008;
737
738    /**
739     * Mask for use with setFlags indicating bits used for visibility.
740     * {@hide}
741     */
742    static final int VISIBILITY_MASK = 0x0000000C;
743
744    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
745
746    /**
747     * This view is enabled. Interpretation varies by subclass.
748     * Use with ENABLED_MASK when calling setFlags.
749     * {@hide}
750     */
751    static final int ENABLED = 0x00000000;
752
753    /**
754     * This view is disabled. Interpretation varies by subclass.
755     * Use with ENABLED_MASK when calling setFlags.
756     * {@hide}
757     */
758    static final int DISABLED = 0x00000020;
759
760   /**
761    * Mask for use with setFlags indicating bits used for indicating whether
762    * this view is enabled
763    * {@hide}
764    */
765    static final int ENABLED_MASK = 0x00000020;
766
767    /**
768     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
769     * called and further optimizations will be performed. It is okay to have
770     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
771     * {@hide}
772     */
773    static final int WILL_NOT_DRAW = 0x00000080;
774
775    /**
776     * Mask for use with setFlags indicating bits used for indicating whether
777     * this view is will draw
778     * {@hide}
779     */
780    static final int DRAW_MASK = 0x00000080;
781
782    /**
783     * <p>This view doesn't show scrollbars.</p>
784     * {@hide}
785     */
786    static final int SCROLLBARS_NONE = 0x00000000;
787
788    /**
789     * <p>This view shows horizontal scrollbars.</p>
790     * {@hide}
791     */
792    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
793
794    /**
795     * <p>This view shows vertical scrollbars.</p>
796     * {@hide}
797     */
798    static final int SCROLLBARS_VERTICAL = 0x00000200;
799
800    /**
801     * <p>Mask for use with setFlags indicating bits used for indicating which
802     * scrollbars are enabled.</p>
803     * {@hide}
804     */
805    static final int SCROLLBARS_MASK = 0x00000300;
806
807    /**
808     * Indicates that the view should filter touches when its window is obscured.
809     * Refer to the class comments for more information about this security feature.
810     * {@hide}
811     */
812    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
813
814    /**
815     * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
816     * that they are optional and should be skipped if the window has
817     * requested system UI flags that ignore those insets for layout.
818     */
819    static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
820
821    /**
822     * <p>This view doesn't show fading edges.</p>
823     * {@hide}
824     */
825    static final int FADING_EDGE_NONE = 0x00000000;
826
827    /**
828     * <p>This view shows horizontal fading edges.</p>
829     * {@hide}
830     */
831    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
832
833    /**
834     * <p>This view shows vertical fading edges.</p>
835     * {@hide}
836     */
837    static final int FADING_EDGE_VERTICAL = 0x00002000;
838
839    /**
840     * <p>Mask for use with setFlags indicating bits used for indicating which
841     * fading edges are enabled.</p>
842     * {@hide}
843     */
844    static final int FADING_EDGE_MASK = 0x00003000;
845
846    /**
847     * <p>Indicates this view can be clicked. When clickable, a View reacts
848     * to clicks by notifying the OnClickListener.<p>
849     * {@hide}
850     */
851    static final int CLICKABLE = 0x00004000;
852
853    /**
854     * <p>Indicates this view is caching its drawing into a bitmap.</p>
855     * {@hide}
856     */
857    static final int DRAWING_CACHE_ENABLED = 0x00008000;
858
859    /**
860     * <p>Indicates that no icicle should be saved for this view.<p>
861     * {@hide}
862     */
863    static final int SAVE_DISABLED = 0x000010000;
864
865    /**
866     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
867     * property.</p>
868     * {@hide}
869     */
870    static final int SAVE_DISABLED_MASK = 0x000010000;
871
872    /**
873     * <p>Indicates that no drawing cache should ever be created for this view.<p>
874     * {@hide}
875     */
876    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
877
878    /**
879     * <p>Indicates this view can take / keep focus when int touch mode.</p>
880     * {@hide}
881     */
882    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
883
884    /**
885     * <p>Enables low quality mode for the drawing cache.</p>
886     */
887    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
888
889    /**
890     * <p>Enables high quality mode for the drawing cache.</p>
891     */
892    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
893
894    /**
895     * <p>Enables automatic quality mode for the drawing cache.</p>
896     */
897    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
898
899    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
900            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
901    };
902
903    /**
904     * <p>Mask for use with setFlags indicating bits used for the cache
905     * quality property.</p>
906     * {@hide}
907     */
908    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
909
910    /**
911     * <p>
912     * Indicates this view can be long clicked. When long clickable, a View
913     * reacts to long clicks by notifying the OnLongClickListener or showing a
914     * context menu.
915     * </p>
916     * {@hide}
917     */
918    static final int LONG_CLICKABLE = 0x00200000;
919
920    /**
921     * <p>Indicates that this view gets its drawable states from its direct parent
922     * and ignores its original internal states.</p>
923     *
924     * @hide
925     */
926    static final int DUPLICATE_PARENT_STATE = 0x00400000;
927
928    /**
929     * The scrollbar style to display the scrollbars inside the content area,
930     * without increasing the padding. The scrollbars will be overlaid with
931     * translucency on the view's content.
932     */
933    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
934
935    /**
936     * The scrollbar style to display the scrollbars inside the padded area,
937     * increasing the padding of the view. The scrollbars will not overlap the
938     * content area of the view.
939     */
940    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
941
942    /**
943     * The scrollbar style to display the scrollbars at the edge of the view,
944     * without increasing the padding. The scrollbars will be overlaid with
945     * translucency.
946     */
947    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
948
949    /**
950     * The scrollbar style to display the scrollbars at the edge of the view,
951     * increasing the padding of the view. The scrollbars will only overlap the
952     * background, if any.
953     */
954    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
955
956    /**
957     * Mask to check if the scrollbar style is overlay or inset.
958     * {@hide}
959     */
960    static final int SCROLLBARS_INSET_MASK = 0x01000000;
961
962    /**
963     * Mask to check if the scrollbar style is inside or outside.
964     * {@hide}
965     */
966    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
967
968    /**
969     * Mask for scrollbar style.
970     * {@hide}
971     */
972    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
973
974    /**
975     * View flag indicating that the screen should remain on while the
976     * window containing this view is visible to the user.  This effectively
977     * takes care of automatically setting the WindowManager's
978     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
979     */
980    public static final int KEEP_SCREEN_ON = 0x04000000;
981
982    /**
983     * View flag indicating whether this view should have sound effects enabled
984     * for events such as clicking and touching.
985     */
986    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
987
988    /**
989     * View flag indicating whether this view should have haptic feedback
990     * enabled for events such as long presses.
991     */
992    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
993
994    /**
995     * <p>Indicates that the view hierarchy should stop saving state when
996     * it reaches this view.  If state saving is initiated immediately at
997     * the view, it will be allowed.
998     * {@hide}
999     */
1000    static final int PARENT_SAVE_DISABLED = 0x20000000;
1001
1002    /**
1003     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
1004     * {@hide}
1005     */
1006    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
1007
1008    /**
1009     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1010     * should add all focusable Views regardless if they are focusable in touch mode.
1011     */
1012    public static final int FOCUSABLES_ALL = 0x00000000;
1013
1014    /**
1015     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1016     * should add only Views focusable in touch mode.
1017     */
1018    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1019
1020    /**
1021     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1022     * item.
1023     */
1024    public static final int FOCUS_BACKWARD = 0x00000001;
1025
1026    /**
1027     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1028     * item.
1029     */
1030    public static final int FOCUS_FORWARD = 0x00000002;
1031
1032    /**
1033     * Use with {@link #focusSearch(int)}. Move focus to the left.
1034     */
1035    public static final int FOCUS_LEFT = 0x00000011;
1036
1037    /**
1038     * Use with {@link #focusSearch(int)}. Move focus up.
1039     */
1040    public static final int FOCUS_UP = 0x00000021;
1041
1042    /**
1043     * Use with {@link #focusSearch(int)}. Move focus to the right.
1044     */
1045    public static final int FOCUS_RIGHT = 0x00000042;
1046
1047    /**
1048     * Use with {@link #focusSearch(int)}. Move focus down.
1049     */
1050    public static final int FOCUS_DOWN = 0x00000082;
1051
1052    /**
1053     * Bits of {@link #getMeasuredWidthAndState()} and
1054     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1055     */
1056    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1057
1058    /**
1059     * Bits of {@link #getMeasuredWidthAndState()} and
1060     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1061     */
1062    public static final int MEASURED_STATE_MASK = 0xff000000;
1063
1064    /**
1065     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1066     * for functions that combine both width and height into a single int,
1067     * such as {@link #getMeasuredState()} and the childState argument of
1068     * {@link #resolveSizeAndState(int, int, int)}.
1069     */
1070    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1071
1072    /**
1073     * Bit of {@link #getMeasuredWidthAndState()} and
1074     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1075     * is smaller that the space the view would like to have.
1076     */
1077    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1078
1079    /**
1080     * Base View state sets
1081     */
1082    // Singles
1083    /**
1084     * Indicates the view has no states set. States are used with
1085     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1086     * view depending on its state.
1087     *
1088     * @see android.graphics.drawable.Drawable
1089     * @see #getDrawableState()
1090     */
1091    protected static final int[] EMPTY_STATE_SET;
1092    /**
1093     * Indicates the view is enabled. States are used with
1094     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1095     * view depending on its state.
1096     *
1097     * @see android.graphics.drawable.Drawable
1098     * @see #getDrawableState()
1099     */
1100    protected static final int[] ENABLED_STATE_SET;
1101    /**
1102     * Indicates the view is focused. States are used with
1103     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1104     * view depending on its state.
1105     *
1106     * @see android.graphics.drawable.Drawable
1107     * @see #getDrawableState()
1108     */
1109    protected static final int[] FOCUSED_STATE_SET;
1110    /**
1111     * Indicates the view is selected. States are used with
1112     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1113     * view depending on its state.
1114     *
1115     * @see android.graphics.drawable.Drawable
1116     * @see #getDrawableState()
1117     */
1118    protected static final int[] SELECTED_STATE_SET;
1119    /**
1120     * Indicates the view is pressed. States are used with
1121     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1122     * view depending on its state.
1123     *
1124     * @see android.graphics.drawable.Drawable
1125     * @see #getDrawableState()
1126     */
1127    protected static final int[] PRESSED_STATE_SET;
1128    /**
1129     * Indicates the view's window has focus. States are used with
1130     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1131     * view depending on its state.
1132     *
1133     * @see android.graphics.drawable.Drawable
1134     * @see #getDrawableState()
1135     */
1136    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1137    // Doubles
1138    /**
1139     * Indicates the view is enabled and has the focus.
1140     *
1141     * @see #ENABLED_STATE_SET
1142     * @see #FOCUSED_STATE_SET
1143     */
1144    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1145    /**
1146     * Indicates the view is enabled and selected.
1147     *
1148     * @see #ENABLED_STATE_SET
1149     * @see #SELECTED_STATE_SET
1150     */
1151    protected static final int[] ENABLED_SELECTED_STATE_SET;
1152    /**
1153     * Indicates the view is enabled and that its window has focus.
1154     *
1155     * @see #ENABLED_STATE_SET
1156     * @see #WINDOW_FOCUSED_STATE_SET
1157     */
1158    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1159    /**
1160     * Indicates the view is focused and selected.
1161     *
1162     * @see #FOCUSED_STATE_SET
1163     * @see #SELECTED_STATE_SET
1164     */
1165    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1166    /**
1167     * Indicates the view has the focus and that its window has the focus.
1168     *
1169     * @see #FOCUSED_STATE_SET
1170     * @see #WINDOW_FOCUSED_STATE_SET
1171     */
1172    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1173    /**
1174     * Indicates the view is selected and that its window has the focus.
1175     *
1176     * @see #SELECTED_STATE_SET
1177     * @see #WINDOW_FOCUSED_STATE_SET
1178     */
1179    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1180    // Triples
1181    /**
1182     * Indicates the view is enabled, focused and selected.
1183     *
1184     * @see #ENABLED_STATE_SET
1185     * @see #FOCUSED_STATE_SET
1186     * @see #SELECTED_STATE_SET
1187     */
1188    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1189    /**
1190     * Indicates the view is enabled, focused and its window has the focus.
1191     *
1192     * @see #ENABLED_STATE_SET
1193     * @see #FOCUSED_STATE_SET
1194     * @see #WINDOW_FOCUSED_STATE_SET
1195     */
1196    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1197    /**
1198     * Indicates the view is enabled, selected and its window has the focus.
1199     *
1200     * @see #ENABLED_STATE_SET
1201     * @see #SELECTED_STATE_SET
1202     * @see #WINDOW_FOCUSED_STATE_SET
1203     */
1204    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1205    /**
1206     * Indicates the view is focused, selected and its window has the focus.
1207     *
1208     * @see #FOCUSED_STATE_SET
1209     * @see #SELECTED_STATE_SET
1210     * @see #WINDOW_FOCUSED_STATE_SET
1211     */
1212    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1213    /**
1214     * Indicates the view is enabled, focused, selected and its window
1215     * has the focus.
1216     *
1217     * @see #ENABLED_STATE_SET
1218     * @see #FOCUSED_STATE_SET
1219     * @see #SELECTED_STATE_SET
1220     * @see #WINDOW_FOCUSED_STATE_SET
1221     */
1222    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1223    /**
1224     * Indicates the view is pressed and its window has the focus.
1225     *
1226     * @see #PRESSED_STATE_SET
1227     * @see #WINDOW_FOCUSED_STATE_SET
1228     */
1229    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1230    /**
1231     * Indicates the view is pressed and selected.
1232     *
1233     * @see #PRESSED_STATE_SET
1234     * @see #SELECTED_STATE_SET
1235     */
1236    protected static final int[] PRESSED_SELECTED_STATE_SET;
1237    /**
1238     * Indicates the view is pressed, selected and its window has the focus.
1239     *
1240     * @see #PRESSED_STATE_SET
1241     * @see #SELECTED_STATE_SET
1242     * @see #WINDOW_FOCUSED_STATE_SET
1243     */
1244    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1245    /**
1246     * Indicates the view is pressed and focused.
1247     *
1248     * @see #PRESSED_STATE_SET
1249     * @see #FOCUSED_STATE_SET
1250     */
1251    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1252    /**
1253     * Indicates the view is pressed, focused and its window has the focus.
1254     *
1255     * @see #PRESSED_STATE_SET
1256     * @see #FOCUSED_STATE_SET
1257     * @see #WINDOW_FOCUSED_STATE_SET
1258     */
1259    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1260    /**
1261     * Indicates the view is pressed, focused and selected.
1262     *
1263     * @see #PRESSED_STATE_SET
1264     * @see #SELECTED_STATE_SET
1265     * @see #FOCUSED_STATE_SET
1266     */
1267    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1268    /**
1269     * Indicates the view is pressed, focused, selected and its window has the focus.
1270     *
1271     * @see #PRESSED_STATE_SET
1272     * @see #FOCUSED_STATE_SET
1273     * @see #SELECTED_STATE_SET
1274     * @see #WINDOW_FOCUSED_STATE_SET
1275     */
1276    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1277    /**
1278     * Indicates the view is pressed and enabled.
1279     *
1280     * @see #PRESSED_STATE_SET
1281     * @see #ENABLED_STATE_SET
1282     */
1283    protected static final int[] PRESSED_ENABLED_STATE_SET;
1284    /**
1285     * Indicates the view is pressed, enabled and its window has the focus.
1286     *
1287     * @see #PRESSED_STATE_SET
1288     * @see #ENABLED_STATE_SET
1289     * @see #WINDOW_FOCUSED_STATE_SET
1290     */
1291    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1292    /**
1293     * Indicates the view is pressed, enabled and selected.
1294     *
1295     * @see #PRESSED_STATE_SET
1296     * @see #ENABLED_STATE_SET
1297     * @see #SELECTED_STATE_SET
1298     */
1299    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1300    /**
1301     * Indicates the view is pressed, enabled, selected and its window has the
1302     * focus.
1303     *
1304     * @see #PRESSED_STATE_SET
1305     * @see #ENABLED_STATE_SET
1306     * @see #SELECTED_STATE_SET
1307     * @see #WINDOW_FOCUSED_STATE_SET
1308     */
1309    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1310    /**
1311     * Indicates the view is pressed, enabled and focused.
1312     *
1313     * @see #PRESSED_STATE_SET
1314     * @see #ENABLED_STATE_SET
1315     * @see #FOCUSED_STATE_SET
1316     */
1317    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1318    /**
1319     * Indicates the view is pressed, enabled, focused and its window has the
1320     * focus.
1321     *
1322     * @see #PRESSED_STATE_SET
1323     * @see #ENABLED_STATE_SET
1324     * @see #FOCUSED_STATE_SET
1325     * @see #WINDOW_FOCUSED_STATE_SET
1326     */
1327    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1328    /**
1329     * Indicates the view is pressed, enabled, focused and selected.
1330     *
1331     * @see #PRESSED_STATE_SET
1332     * @see #ENABLED_STATE_SET
1333     * @see #SELECTED_STATE_SET
1334     * @see #FOCUSED_STATE_SET
1335     */
1336    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1337    /**
1338     * Indicates the view is pressed, enabled, focused, selected and its window
1339     * has the focus.
1340     *
1341     * @see #PRESSED_STATE_SET
1342     * @see #ENABLED_STATE_SET
1343     * @see #SELECTED_STATE_SET
1344     * @see #FOCUSED_STATE_SET
1345     * @see #WINDOW_FOCUSED_STATE_SET
1346     */
1347    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1348
1349    /**
1350     * The order here is very important to {@link #getDrawableState()}
1351     */
1352    private static final int[][] VIEW_STATE_SETS;
1353
1354    static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1355    static final int VIEW_STATE_SELECTED = 1 << 1;
1356    static final int VIEW_STATE_FOCUSED = 1 << 2;
1357    static final int VIEW_STATE_ENABLED = 1 << 3;
1358    static final int VIEW_STATE_PRESSED = 1 << 4;
1359    static final int VIEW_STATE_ACTIVATED = 1 << 5;
1360    static final int VIEW_STATE_ACCELERATED = 1 << 6;
1361    static final int VIEW_STATE_HOVERED = 1 << 7;
1362    static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8;
1363    static final int VIEW_STATE_DRAG_HOVERED = 1 << 9;
1364
1365    static final int[] VIEW_STATE_IDS = new int[] {
1366        R.attr.state_window_focused,    VIEW_STATE_WINDOW_FOCUSED,
1367        R.attr.state_selected,          VIEW_STATE_SELECTED,
1368        R.attr.state_focused,           VIEW_STATE_FOCUSED,
1369        R.attr.state_enabled,           VIEW_STATE_ENABLED,
1370        R.attr.state_pressed,           VIEW_STATE_PRESSED,
1371        R.attr.state_activated,         VIEW_STATE_ACTIVATED,
1372        R.attr.state_accelerated,       VIEW_STATE_ACCELERATED,
1373        R.attr.state_hovered,           VIEW_STATE_HOVERED,
1374        R.attr.state_drag_can_accept,   VIEW_STATE_DRAG_CAN_ACCEPT,
1375        R.attr.state_drag_hovered,      VIEW_STATE_DRAG_HOVERED
1376    };
1377
1378    static {
1379        if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1380            throw new IllegalStateException(
1381                    "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1382        }
1383        int[] orderedIds = new int[VIEW_STATE_IDS.length];
1384        for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
1385            int viewState = R.styleable.ViewDrawableStates[i];
1386            for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
1387                if (VIEW_STATE_IDS[j] == viewState) {
1388                    orderedIds[i * 2] = viewState;
1389                    orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
1390                }
1391            }
1392        }
1393        final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1394        VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1395        for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
1396            int numBits = Integer.bitCount(i);
1397            int[] set = new int[numBits];
1398            int pos = 0;
1399            for (int j = 0; j < orderedIds.length; j += 2) {
1400                if ((i & orderedIds[j+1]) != 0) {
1401                    set[pos++] = orderedIds[j];
1402                }
1403            }
1404            VIEW_STATE_SETS[i] = set;
1405        }
1406
1407        EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1408        WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1409        SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1410        SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1411                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1412        FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1413        FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1414                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1415        FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1416                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1417        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1418                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1419                | VIEW_STATE_FOCUSED];
1420        ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1421        ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1422                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1423        ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1424                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1425        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1426                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1427                | VIEW_STATE_ENABLED];
1428        ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1429                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1430        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1431                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1432                | VIEW_STATE_ENABLED];
1433        ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1434                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1435                | VIEW_STATE_ENABLED];
1436        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1437                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1438                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1439
1440        PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1441        PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1442                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1443        PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1444                VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1445        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1446                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1447                | VIEW_STATE_PRESSED];
1448        PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1449                VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1450        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1451                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1452                | VIEW_STATE_PRESSED];
1453        PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1454                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1455                | VIEW_STATE_PRESSED];
1456        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1457                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1458                | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1459        PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1460                VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1461        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1462                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1463                | VIEW_STATE_PRESSED];
1464        PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1465                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1466                | VIEW_STATE_PRESSED];
1467        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1468                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1469                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1470        PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1471                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1472                | VIEW_STATE_PRESSED];
1473        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1474                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1475                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1476        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1477                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1478                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1479        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1480                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1481                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1482                | VIEW_STATE_PRESSED];
1483    }
1484
1485    /**
1486     * Accessibility event types that are dispatched for text population.
1487     */
1488    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1489            AccessibilityEvent.TYPE_VIEW_CLICKED
1490            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1491            | AccessibilityEvent.TYPE_VIEW_SELECTED
1492            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1493            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1494            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1495            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1496            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1497            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
1498            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
1499            | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY;
1500
1501    /**
1502     * Temporary Rect currently for use in setBackground().  This will probably
1503     * be extended in the future to hold our own class with more than just
1504     * a Rect. :)
1505     */
1506    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1507
1508    /**
1509     * Map used to store views' tags.
1510     */
1511    private SparseArray<Object> mKeyedTags;
1512
1513    /**
1514     * The next available accessibility id.
1515     */
1516    private static int sNextAccessibilityViewId;
1517
1518    /**
1519     * The animation currently associated with this view.
1520     * @hide
1521     */
1522    protected Animation mCurrentAnimation = null;
1523
1524    /**
1525     * Width as measured during measure pass.
1526     * {@hide}
1527     */
1528    @ViewDebug.ExportedProperty(category = "measurement")
1529    int mMeasuredWidth;
1530
1531    /**
1532     * Height as measured during measure pass.
1533     * {@hide}
1534     */
1535    @ViewDebug.ExportedProperty(category = "measurement")
1536    int mMeasuredHeight;
1537
1538    /**
1539     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1540     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1541     * its display list. This flag, used only when hw accelerated, allows us to clear the
1542     * flag while retaining this information until it's needed (at getDisplayList() time and
1543     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1544     *
1545     * {@hide}
1546     */
1547    boolean mRecreateDisplayList = false;
1548
1549    /**
1550     * The view's identifier.
1551     * {@hide}
1552     *
1553     * @see #setId(int)
1554     * @see #getId()
1555     */
1556    @ViewDebug.ExportedProperty(resolveId = true)
1557    int mID = NO_ID;
1558
1559    /**
1560     * The stable ID of this view for accessibility purposes.
1561     */
1562    int mAccessibilityViewId = NO_ID;
1563
1564    private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
1565
1566    SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent;
1567
1568    /**
1569     * The view's tag.
1570     * {@hide}
1571     *
1572     * @see #setTag(Object)
1573     * @see #getTag()
1574     */
1575    protected Object mTag;
1576
1577    private Scene mCurrentScene = null;
1578
1579    // for mPrivateFlags:
1580    /** {@hide} */
1581    static final int PFLAG_WANTS_FOCUS                 = 0x00000001;
1582    /** {@hide} */
1583    static final int PFLAG_FOCUSED                     = 0x00000002;
1584    /** {@hide} */
1585    static final int PFLAG_SELECTED                    = 0x00000004;
1586    /** {@hide} */
1587    static final int PFLAG_IS_ROOT_NAMESPACE           = 0x00000008;
1588    /** {@hide} */
1589    static final int PFLAG_HAS_BOUNDS                  = 0x00000010;
1590    /** {@hide} */
1591    static final int PFLAG_DRAWN                       = 0x00000020;
1592    /**
1593     * When this flag is set, this view is running an animation on behalf of its
1594     * children and should therefore not cancel invalidate requests, even if they
1595     * lie outside of this view's bounds.
1596     *
1597     * {@hide}
1598     */
1599    static final int PFLAG_DRAW_ANIMATION              = 0x00000040;
1600    /** {@hide} */
1601    static final int PFLAG_SKIP_DRAW                   = 0x00000080;
1602    /** {@hide} */
1603    static final int PFLAG_ONLY_DRAWS_BACKGROUND       = 0x00000100;
1604    /** {@hide} */
1605    static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1606    /** {@hide} */
1607    static final int PFLAG_DRAWABLE_STATE_DIRTY        = 0x00000400;
1608    /** {@hide} */
1609    static final int PFLAG_MEASURED_DIMENSION_SET      = 0x00000800;
1610    /** {@hide} */
1611    static final int PFLAG_FORCE_LAYOUT                = 0x00001000;
1612    /** {@hide} */
1613    static final int PFLAG_LAYOUT_REQUIRED             = 0x00002000;
1614
1615    private static final int PFLAG_PRESSED             = 0x00004000;
1616
1617    /** {@hide} */
1618    static final int PFLAG_DRAWING_CACHE_VALID         = 0x00008000;
1619    /**
1620     * Flag used to indicate that this view should be drawn once more (and only once
1621     * more) after its animation has completed.
1622     * {@hide}
1623     */
1624    static final int PFLAG_ANIMATION_STARTED           = 0x00010000;
1625
1626    private static final int PFLAG_SAVE_STATE_CALLED   = 0x00020000;
1627
1628    /**
1629     * Indicates that the View returned true when onSetAlpha() was called and that
1630     * the alpha must be restored.
1631     * {@hide}
1632     */
1633    static final int PFLAG_ALPHA_SET                   = 0x00040000;
1634
1635    /**
1636     * Set by {@link #setScrollContainer(boolean)}.
1637     */
1638    static final int PFLAG_SCROLL_CONTAINER            = 0x00080000;
1639
1640    /**
1641     * Set by {@link #setScrollContainer(boolean)}.
1642     */
1643    static final int PFLAG_SCROLL_CONTAINER_ADDED      = 0x00100000;
1644
1645    /**
1646     * View flag indicating whether this view was invalidated (fully or partially.)
1647     *
1648     * @hide
1649     */
1650    static final int PFLAG_DIRTY                       = 0x00200000;
1651
1652    /**
1653     * View flag indicating whether this view was invalidated by an opaque
1654     * invalidate request.
1655     *
1656     * @hide
1657     */
1658    static final int PFLAG_DIRTY_OPAQUE                = 0x00400000;
1659
1660    /**
1661     * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}.
1662     *
1663     * @hide
1664     */
1665    static final int PFLAG_DIRTY_MASK                  = 0x00600000;
1666
1667    /**
1668     * Indicates whether the background is opaque.
1669     *
1670     * @hide
1671     */
1672    static final int PFLAG_OPAQUE_BACKGROUND           = 0x00800000;
1673
1674    /**
1675     * Indicates whether the scrollbars are opaque.
1676     *
1677     * @hide
1678     */
1679    static final int PFLAG_OPAQUE_SCROLLBARS           = 0x01000000;
1680
1681    /**
1682     * Indicates whether the view is opaque.
1683     *
1684     * @hide
1685     */
1686    static final int PFLAG_OPAQUE_MASK                 = 0x01800000;
1687
1688    /**
1689     * Indicates a prepressed state;
1690     * the short time between ACTION_DOWN and recognizing
1691     * a 'real' press. Prepressed is used to recognize quick taps
1692     * even when they are shorter than ViewConfiguration.getTapTimeout().
1693     *
1694     * @hide
1695     */
1696    private static final int PFLAG_PREPRESSED          = 0x02000000;
1697
1698    /**
1699     * Indicates whether the view is temporarily detached.
1700     *
1701     * @hide
1702     */
1703    static final int PFLAG_CANCEL_NEXT_UP_EVENT        = 0x04000000;
1704
1705    /**
1706     * Indicates that we should awaken scroll bars once attached
1707     *
1708     * @hide
1709     */
1710    private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1711
1712    /**
1713     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1714     * @hide
1715     */
1716    private static final int PFLAG_HOVERED             = 0x10000000;
1717
1718    /**
1719     * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1720     * for transform operations
1721     *
1722     * @hide
1723     */
1724    private static final int PFLAG_PIVOT_EXPLICITLY_SET = 0x20000000;
1725
1726    /** {@hide} */
1727    static final int PFLAG_ACTIVATED                   = 0x40000000;
1728
1729    /**
1730     * Indicates that this view was specifically invalidated, not just dirtied because some
1731     * child view was invalidated. The flag is used to determine when we need to recreate
1732     * a view's display list (as opposed to just returning a reference to its existing
1733     * display list).
1734     *
1735     * @hide
1736     */
1737    static final int PFLAG_INVALIDATED                 = 0x80000000;
1738
1739    /**
1740     * Masks for mPrivateFlags2, as generated by dumpFlags():
1741     *
1742     * -------|-------|-------|-------|
1743     *                                  PFLAG2_TEXT_ALIGNMENT_FLAGS[0]
1744     *                                  PFLAG2_TEXT_DIRECTION_FLAGS[0]
1745     *                                1 PFLAG2_DRAG_CAN_ACCEPT
1746     *                               1  PFLAG2_DRAG_HOVERED
1747     *                               1  PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT
1748     *                              11  PFLAG2_TEXT_DIRECTION_MASK_SHIFT
1749     *                             1 1  PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT
1750     *                             11   PFLAG2_LAYOUT_DIRECTION_MASK
1751     *                             11 1 PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
1752     *                            1     PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL
1753     *                            1   1 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT
1754     *                            1 1   PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT
1755     *                           1      PFLAG2_LAYOUT_DIRECTION_RESOLVED
1756     *                           11     PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK
1757     *                          1       PFLAG2_TEXT_DIRECTION_FLAGS[1]
1758     *                         1        PFLAG2_TEXT_DIRECTION_FLAGS[2]
1759     *                         11       PFLAG2_TEXT_DIRECTION_FLAGS[3]
1760     *                        1         PFLAG2_TEXT_DIRECTION_FLAGS[4]
1761     *                        1 1       PFLAG2_TEXT_DIRECTION_FLAGS[5]
1762     *                        111       PFLAG2_TEXT_DIRECTION_MASK
1763     *                       1          PFLAG2_TEXT_DIRECTION_RESOLVED
1764     *                      1           PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT
1765     *                    111           PFLAG2_TEXT_DIRECTION_RESOLVED_MASK
1766     *                   1              PFLAG2_TEXT_ALIGNMENT_FLAGS[1]
1767     *                  1               PFLAG2_TEXT_ALIGNMENT_FLAGS[2]
1768     *                  11              PFLAG2_TEXT_ALIGNMENT_FLAGS[3]
1769     *                 1                PFLAG2_TEXT_ALIGNMENT_FLAGS[4]
1770     *                 1 1              PFLAG2_TEXT_ALIGNMENT_FLAGS[5]
1771     *                 11               PFLAG2_TEXT_ALIGNMENT_FLAGS[6]
1772     *                 111              PFLAG2_TEXT_ALIGNMENT_MASK
1773     *                1                 PFLAG2_TEXT_ALIGNMENT_RESOLVED
1774     *               1                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT
1775     *             111                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK
1776     *           11                     PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK
1777     *          1                       PFLAG2_HAS_TRANSIENT_STATE
1778     *      1                           PFLAG2_ACCESSIBILITY_FOCUSED
1779     *     1                            PFLAG2_ACCESSIBILITY_STATE_CHANGED
1780     *    1                             PFLAG2_VIEW_QUICK_REJECTED
1781     *   1                              PFLAG2_PADDING_RESOLVED
1782     * -------|-------|-------|-------|
1783     */
1784
1785    /**
1786     * Indicates that this view has reported that it can accept the current drag's content.
1787     * Cleared when the drag operation concludes.
1788     * @hide
1789     */
1790    static final int PFLAG2_DRAG_CAN_ACCEPT            = 0x00000001;
1791
1792    /**
1793     * Indicates that this view is currently directly under the drag location in a
1794     * drag-and-drop operation involving content that it can accept.  Cleared when
1795     * the drag exits the view, or when the drag operation concludes.
1796     * @hide
1797     */
1798    static final int PFLAG2_DRAG_HOVERED               = 0x00000002;
1799
1800    /**
1801     * Horizontal layout direction of this view is from Left to Right.
1802     * Use with {@link #setLayoutDirection}.
1803     */
1804    public static final int LAYOUT_DIRECTION_LTR = 0;
1805
1806    /**
1807     * Horizontal layout direction of this view is from Right to Left.
1808     * Use with {@link #setLayoutDirection}.
1809     */
1810    public static final int LAYOUT_DIRECTION_RTL = 1;
1811
1812    /**
1813     * Horizontal layout direction of this view is inherited from its parent.
1814     * Use with {@link #setLayoutDirection}.
1815     */
1816    public static final int LAYOUT_DIRECTION_INHERIT = 2;
1817
1818    /**
1819     * Horizontal layout direction of this view is from deduced from the default language
1820     * script for the locale. Use with {@link #setLayoutDirection}.
1821     */
1822    public static final int LAYOUT_DIRECTION_LOCALE = 3;
1823
1824    /**
1825     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1826     * @hide
1827     */
1828    static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2;
1829
1830    /**
1831     * Mask for use with private flags indicating bits used for horizontal layout direction.
1832     * @hide
1833     */
1834    static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1835
1836    /**
1837     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
1838     * right-to-left direction.
1839     * @hide
1840     */
1841    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1842
1843    /**
1844     * Indicates whether the view horizontal layout direction has been resolved.
1845     * @hide
1846     */
1847    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1848
1849    /**
1850     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
1851     * @hide
1852     */
1853    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C
1854            << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1855
1856    /*
1857     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
1858     * flag value.
1859     * @hide
1860     */
1861    private static final int[] LAYOUT_DIRECTION_FLAGS = {
1862            LAYOUT_DIRECTION_LTR,
1863            LAYOUT_DIRECTION_RTL,
1864            LAYOUT_DIRECTION_INHERIT,
1865            LAYOUT_DIRECTION_LOCALE
1866    };
1867
1868    /**
1869     * Default horizontal layout direction.
1870     */
1871    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
1872
1873    /**
1874     * Default horizontal layout direction.
1875     * @hide
1876     */
1877    static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR;
1878
1879    /**
1880     * Indicates that the view is tracking some sort of transient state
1881     * that the app should not need to be aware of, but that the framework
1882     * should take special care to preserve.
1883     *
1884     * @hide
1885     */
1886    static final int PFLAG2_HAS_TRANSIENT_STATE = 0x1 << 22;
1887
1888    /**
1889     * Text direction is inherited thru {@link ViewGroup}
1890     */
1891    public static final int TEXT_DIRECTION_INHERIT = 0;
1892
1893    /**
1894     * Text direction is using "first strong algorithm". The first strong directional character
1895     * determines the paragraph direction. If there is no strong directional character, the
1896     * paragraph direction is the view's resolved layout direction.
1897     */
1898    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
1899
1900    /**
1901     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
1902     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
1903     * If there are neither, the paragraph direction is the view's resolved layout direction.
1904     */
1905    public static final int TEXT_DIRECTION_ANY_RTL = 2;
1906
1907    /**
1908     * Text direction is forced to LTR.
1909     */
1910    public static final int TEXT_DIRECTION_LTR = 3;
1911
1912    /**
1913     * Text direction is forced to RTL.
1914     */
1915    public static final int TEXT_DIRECTION_RTL = 4;
1916
1917    /**
1918     * Text direction is coming from the system Locale.
1919     */
1920    public static final int TEXT_DIRECTION_LOCALE = 5;
1921
1922    /**
1923     * Default text direction is inherited
1924     */
1925    private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
1926
1927    /**
1928     * Default resolved text direction
1929     * @hide
1930     */
1931    static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG;
1932
1933    /**
1934     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
1935     * @hide
1936     */
1937    static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6;
1938
1939    /**
1940     * Mask for use with private flags indicating bits used for text direction.
1941     * @hide
1942     */
1943    static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007
1944            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
1945
1946    /**
1947     * Array of text direction flags for mapping attribute "textDirection" to correct
1948     * flag value.
1949     * @hide
1950     */
1951    private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = {
1952            TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1953            TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1954            TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1955            TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1956            TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1957            TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT
1958    };
1959
1960    /**
1961     * Indicates whether the view text direction has been resolved.
1962     * @hide
1963     */
1964    static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008
1965            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
1966
1967    /**
1968     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1969     * @hide
1970     */
1971    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
1972
1973    /**
1974     * Mask for use with private flags indicating bits used for resolved text direction.
1975     * @hide
1976     */
1977    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007
1978            << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
1979
1980    /**
1981     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
1982     * @hide
1983     */
1984    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT =
1985            TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
1986
1987    /*
1988     * Default text alignment. The text alignment of this View is inherited from its parent.
1989     * Use with {@link #setTextAlignment(int)}
1990     */
1991    public static final int TEXT_ALIGNMENT_INHERIT = 0;
1992
1993    /**
1994     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
1995     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
1996     *
1997     * Use with {@link #setTextAlignment(int)}
1998     */
1999    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
2000
2001    /**
2002     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
2003     *
2004     * Use with {@link #setTextAlignment(int)}
2005     */
2006    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
2007
2008    /**
2009     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
2010     *
2011     * Use with {@link #setTextAlignment(int)}
2012     */
2013    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
2014
2015    /**
2016     * Center the paragraph, e.g. ALIGN_CENTER.
2017     *
2018     * Use with {@link #setTextAlignment(int)}
2019     */
2020    public static final int TEXT_ALIGNMENT_CENTER = 4;
2021
2022    /**
2023     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
2024     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
2025     *
2026     * Use with {@link #setTextAlignment(int)}
2027     */
2028    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
2029
2030    /**
2031     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
2032     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
2033     *
2034     * Use with {@link #setTextAlignment(int)}
2035     */
2036    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
2037
2038    /**
2039     * Default text alignment is inherited
2040     */
2041    private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2042
2043    /**
2044     * Default resolved text alignment
2045     * @hide
2046     */
2047    static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2048
2049    /**
2050      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2051      * @hide
2052      */
2053    static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13;
2054
2055    /**
2056      * Mask for use with private flags indicating bits used for text alignment.
2057      * @hide
2058      */
2059    static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2060
2061    /**
2062     * Array of text direction flags for mapping attribute "textAlignment" to correct
2063     * flag value.
2064     * @hide
2065     */
2066    private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = {
2067            TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2068            TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2069            TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2070            TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2071            TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2072            TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2073            TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
2074    };
2075
2076    /**
2077     * Indicates whether the view text alignment has been resolved.
2078     * @hide
2079     */
2080    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2081
2082    /**
2083     * Bit shift to get the resolved text alignment.
2084     * @hide
2085     */
2086    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2087
2088    /**
2089     * Mask for use with private flags indicating bits used for text alignment.
2090     * @hide
2091     */
2092    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007
2093            << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2094
2095    /**
2096     * Indicates whether if the view text alignment has been resolved to gravity
2097     */
2098    private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2099            TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2100
2101    // Accessiblity constants for mPrivateFlags2
2102
2103    /**
2104     * Shift for the bits in {@link #mPrivateFlags2} related to the
2105     * "importantForAccessibility" attribute.
2106     */
2107    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2108
2109    /**
2110     * Automatically determine whether a view is important for accessibility.
2111     */
2112    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2113
2114    /**
2115     * The view is important for accessibility.
2116     */
2117    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2118
2119    /**
2120     * The view is not important for accessibility.
2121     */
2122    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2123
2124    /**
2125     * The default whether the view is important for accessibility.
2126     */
2127    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2128
2129    /**
2130     * Mask for obtainig the bits which specify how to determine
2131     * whether a view is important for accessibility.
2132     */
2133    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2134        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO)
2135        << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2136
2137    /**
2138     * Flag indicating whether a view has accessibility focus.
2139     */
2140    static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000;
2141
2142    /**
2143     * Flag whether the accessibility state of the subtree rooted at this view changed.
2144     */
2145    static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000;
2146
2147    /**
2148     * Flag indicating whether a view failed the quickReject() check in draw(). This condition
2149     * is used to check whether later changes to the view's transform should invalidate the
2150     * view to force the quickReject test to run again.
2151     */
2152    static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000;
2153
2154    /**
2155     * Flag indicating that start/end padding has been resolved into left/right padding
2156     * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()}
2157     * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved
2158     * during measurement. In some special cases this is required such as when an adapter-based
2159     * view measures prospective children without attaching them to a window.
2160     */
2161    static final int PFLAG2_PADDING_RESOLVED = 0x20000000;
2162
2163    /**
2164     * Flag indicating that the start/end drawables has been resolved into left/right ones.
2165     */
2166    static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000;
2167
2168    /**
2169     * Group of bits indicating that RTL properties resolution is done.
2170     */
2171    static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED |
2172            PFLAG2_TEXT_DIRECTION_RESOLVED |
2173            PFLAG2_TEXT_ALIGNMENT_RESOLVED |
2174            PFLAG2_PADDING_RESOLVED |
2175            PFLAG2_DRAWABLE_RESOLVED;
2176
2177    // There are a couple of flags left in mPrivateFlags2
2178
2179    /* End of masks for mPrivateFlags2 */
2180
2181    /* Masks for mPrivateFlags3 */
2182
2183    /**
2184     * Flag indicating that view has a transform animation set on it. This is used to track whether
2185     * an animation is cleared between successive frames, in order to tell the associated
2186     * DisplayList to clear its animation matrix.
2187     */
2188    static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1;
2189
2190    /**
2191     * Flag indicating that view has an alpha animation set on it. This is used to track whether an
2192     * animation is cleared between successive frames, in order to tell the associated
2193     * DisplayList to restore its alpha value.
2194     */
2195    static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2;
2196
2197    /**
2198     * Flag indicating that the view has been through at least one layout since it
2199     * was last attached to a window.
2200     */
2201    static final int PFLAG3_IS_LAID_OUT = 0x4;
2202
2203    /**
2204     * Flag indicating that a call to measure() was skipped and should be done
2205     * instead when layout() is invoked.
2206     */
2207    static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8;
2208
2209
2210    /* End of masks for mPrivateFlags3 */
2211
2212    static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED;
2213
2214    /**
2215     * Always allow a user to over-scroll this view, provided it is a
2216     * view that can scroll.
2217     *
2218     * @see #getOverScrollMode()
2219     * @see #setOverScrollMode(int)
2220     */
2221    public static final int OVER_SCROLL_ALWAYS = 0;
2222
2223    /**
2224     * Allow a user to over-scroll this view only if the content is large
2225     * enough to meaningfully scroll, provided it is a view that can scroll.
2226     *
2227     * @see #getOverScrollMode()
2228     * @see #setOverScrollMode(int)
2229     */
2230    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2231
2232    /**
2233     * Never allow a user to over-scroll this view.
2234     *
2235     * @see #getOverScrollMode()
2236     * @see #setOverScrollMode(int)
2237     */
2238    public static final int OVER_SCROLL_NEVER = 2;
2239
2240    /**
2241     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2242     * requested the system UI (status bar) to be visible (the default).
2243     *
2244     * @see #setSystemUiVisibility(int)
2245     */
2246    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2247
2248    /**
2249     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2250     * system UI to enter an unobtrusive "low profile" mode.
2251     *
2252     * <p>This is for use in games, book readers, video players, or any other
2253     * "immersive" application where the usual system chrome is deemed too distracting.
2254     *
2255     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2256     *
2257     * @see #setSystemUiVisibility(int)
2258     */
2259    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2260
2261    /**
2262     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2263     * system navigation be temporarily hidden.
2264     *
2265     * <p>This is an even less obtrusive state than that called for by
2266     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2267     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2268     * those to disappear. This is useful (in conjunction with the
2269     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2270     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2271     * window flags) for displaying content using every last pixel on the display.
2272     *
2273     * <p>There is a limitation: because navigation controls are so important, the least user
2274     * interaction will cause them to reappear immediately.  When this happens, both
2275     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2276     * so that both elements reappear at the same time.
2277     *
2278     * @see #setSystemUiVisibility(int)
2279     */
2280    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2281
2282    /**
2283     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2284     * into the normal fullscreen mode so that its content can take over the screen
2285     * while still allowing the user to interact with the application.
2286     *
2287     * <p>This has the same visual effect as
2288     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2289     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2290     * meaning that non-critical screen decorations (such as the status bar) will be
2291     * hidden while the user is in the View's window, focusing the experience on
2292     * that content.  Unlike the window flag, if you are using ActionBar in
2293     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2294     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2295     * hide the action bar.
2296     *
2297     * <p>This approach to going fullscreen is best used over the window flag when
2298     * it is a transient state -- that is, the application does this at certain
2299     * points in its user interaction where it wants to allow the user to focus
2300     * on content, but not as a continuous state.  For situations where the application
2301     * would like to simply stay full screen the entire time (such as a game that
2302     * wants to take over the screen), the
2303     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2304     * is usually a better approach.  The state set here will be removed by the system
2305     * in various situations (such as the user moving to another application) like
2306     * the other system UI states.
2307     *
2308     * <p>When using this flag, the application should provide some easy facility
2309     * for the user to go out of it.  A common example would be in an e-book
2310     * reader, where tapping on the screen brings back whatever screen and UI
2311     * decorations that had been hidden while the user was immersed in reading
2312     * the book.
2313     *
2314     * @see #setSystemUiVisibility(int)
2315     */
2316    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2317
2318    /**
2319     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2320     * flags, we would like a stable view of the content insets given to
2321     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2322     * will always represent the worst case that the application can expect
2323     * as a continuous state.  In the stock Android UI this is the space for
2324     * the system bar, nav bar, and status bar, but not more transient elements
2325     * such as an input method.
2326     *
2327     * The stable layout your UI sees is based on the system UI modes you can
2328     * switch to.  That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
2329     * then you will get a stable layout for changes of the
2330     * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
2331     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
2332     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
2333     * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
2334     * with a stable layout.  (Note that you should avoid using
2335     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
2336     *
2337     * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN}
2338     * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
2339     * then a hidden status bar will be considered a "stable" state for purposes
2340     * here.  This allows your UI to continually hide the status bar, while still
2341     * using the system UI flags to hide the action bar while still retaining
2342     * a stable layout.  Note that changing the window fullscreen flag will never
2343     * provide a stable layout for a clean transition.
2344     *
2345     * <p>If you are using ActionBar in
2346     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2347     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2348     * insets it adds to those given to the application.
2349     */
2350    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2351
2352    /**
2353     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2354     * to be layed out as if it has requested
2355     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2356     * allows it to avoid artifacts when switching in and out of that mode, at
2357     * the expense that some of its user interface may be covered by screen
2358     * decorations when they are shown.  You can perform layout of your inner
2359     * UI elements to account for the navigation system UI through the
2360     * {@link #fitSystemWindows(Rect)} method.
2361     */
2362    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2363
2364    /**
2365     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2366     * to be layed out as if it has requested
2367     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2368     * allows it to avoid artifacts when switching in and out of that mode, at
2369     * the expense that some of its user interface may be covered by screen
2370     * decorations when they are shown.  You can perform layout of your inner
2371     * UI elements to account for non-fullscreen system UI through the
2372     * {@link #fitSystemWindows(Rect)} method.
2373     */
2374    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2375
2376    /**
2377     * Flag for {@link #setSystemUiVisibility(int)}: View would like to receive touch events
2378     * when hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the
2379     * navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} instead of having the system
2380     * clear these flags upon interaction.  The system may compensate by temporarily overlaying
2381     * transparent system ui while also delivering the event.
2382     */
2383    public static final int SYSTEM_UI_FLAG_ALLOW_OVERLAY = 0x00000800;
2384
2385    /**
2386     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2387     */
2388    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2389
2390    /**
2391     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2392     */
2393    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2394
2395    /**
2396     * @hide
2397     *
2398     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2399     * out of the public fields to keep the undefined bits out of the developer's way.
2400     *
2401     * Flag to make the status bar not expandable.  Unless you also
2402     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
2403     */
2404    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
2405
2406    /**
2407     * @hide
2408     *
2409     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2410     * out of the public fields to keep the undefined bits out of the developer's way.
2411     *
2412     * Flag to hide notification icons and scrolling ticker text.
2413     */
2414    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
2415
2416    /**
2417     * @hide
2418     *
2419     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2420     * out of the public fields to keep the undefined bits out of the developer's way.
2421     *
2422     * Flag to disable incoming notification alerts.  This will not block
2423     * icons, but it will block sound, vibrating and other visual or aural notifications.
2424     */
2425    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
2426
2427    /**
2428     * @hide
2429     *
2430     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2431     * out of the public fields to keep the undefined bits out of the developer's way.
2432     *
2433     * Flag to hide only the scrolling ticker.  Note that
2434     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
2435     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
2436     */
2437    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
2438
2439    /**
2440     * @hide
2441     *
2442     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2443     * out of the public fields to keep the undefined bits out of the developer's way.
2444     *
2445     * Flag to hide the center system info area.
2446     */
2447    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
2448
2449    /**
2450     * @hide
2451     *
2452     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2453     * out of the public fields to keep the undefined bits out of the developer's way.
2454     *
2455     * Flag to hide only the home button.  Don't use this
2456     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2457     */
2458    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
2459
2460    /**
2461     * @hide
2462     *
2463     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2464     * out of the public fields to keep the undefined bits out of the developer's way.
2465     *
2466     * Flag to hide only the back button. Don't use this
2467     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2468     */
2469    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
2470
2471    /**
2472     * @hide
2473     *
2474     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2475     * out of the public fields to keep the undefined bits out of the developer's way.
2476     *
2477     * Flag to hide only the clock.  You might use this if your activity has
2478     * its own clock making the status bar's clock redundant.
2479     */
2480    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
2481
2482    /**
2483     * @hide
2484     *
2485     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2486     * out of the public fields to keep the undefined bits out of the developer's way.
2487     *
2488     * Flag to hide only the recent apps button. Don't use this
2489     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2490     */
2491    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
2492
2493    /**
2494     * @hide
2495     *
2496     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2497     * out of the public fields to keep the undefined bits out of the developer's way.
2498     *
2499     * Flag to disable the global search gesture. Don't use this
2500     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2501     */
2502    public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000;
2503
2504    /**
2505     * @hide
2506     *
2507     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2508     * out of the public fields to keep the undefined bits out of the developer's way.
2509     *
2510     * Flag to specify that the status bar should temporarily overlay underlying content
2511     * that is otherwise assuming the status bar is hidden.  The status bar may
2512     * have some degree of transparency while in this temporary overlay mode.
2513     */
2514    public static final int STATUS_BAR_OVERLAY = 0x04000000;
2515
2516    /**
2517     * @hide
2518     *
2519     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2520     * out of the public fields to keep the undefined bits out of the developer's way.
2521     *
2522     * Flag to specify that the navigation bar should temporarily overlay underlying content
2523     * that is otherwise assuming the navigation bar is hidden.  The navigation bar mayu
2524     * have some degree of transparency while in this temporary overlay mode.
2525     */
2526    public static final int NAVIGATION_BAR_OVERLAY = 0x08000000;
2527
2528    /**
2529     * @hide
2530     */
2531    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF;
2532
2533    /**
2534     * These are the system UI flags that can be cleared by events outside
2535     * of an application.  Currently this is just the ability to tap on the
2536     * screen while hiding the navigation bar to have it return.
2537     * @hide
2538     */
2539    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
2540            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
2541            | SYSTEM_UI_FLAG_FULLSCREEN;
2542
2543    /**
2544     * Flags that can impact the layout in relation to system UI.
2545     */
2546    public static final int SYSTEM_UI_LAYOUT_FLAGS =
2547            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
2548            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
2549
2550    /**
2551     * Find views that render the specified text.
2552     *
2553     * @see #findViewsWithText(ArrayList, CharSequence, int)
2554     */
2555    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
2556
2557    /**
2558     * Find find views that contain the specified content description.
2559     *
2560     * @see #findViewsWithText(ArrayList, CharSequence, int)
2561     */
2562    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
2563
2564    /**
2565     * Find views that contain {@link AccessibilityNodeProvider}. Such
2566     * a View is a root of virtual view hierarchy and may contain the searched
2567     * text. If this flag is set Views with providers are automatically
2568     * added and it is a responsibility of the client to call the APIs of
2569     * the provider to determine whether the virtual tree rooted at this View
2570     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
2571     * represeting the virtual views with this text.
2572     *
2573     * @see #findViewsWithText(ArrayList, CharSequence, int)
2574     *
2575     * @hide
2576     */
2577    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
2578
2579    /**
2580     * The undefined cursor position.
2581     *
2582     * @hide
2583     */
2584    public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1;
2585
2586    /**
2587     * Indicates that the screen has changed state and is now off.
2588     *
2589     * @see #onScreenStateChanged(int)
2590     */
2591    public static final int SCREEN_STATE_OFF = 0x0;
2592
2593    /**
2594     * Indicates that the screen has changed state and is now on.
2595     *
2596     * @see #onScreenStateChanged(int)
2597     */
2598    public static final int SCREEN_STATE_ON = 0x1;
2599
2600    /**
2601     * Controls the over-scroll mode for this view.
2602     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
2603     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
2604     * and {@link #OVER_SCROLL_NEVER}.
2605     */
2606    private int mOverScrollMode;
2607
2608    /**
2609     * The parent this view is attached to.
2610     * {@hide}
2611     *
2612     * @see #getParent()
2613     */
2614    protected ViewParent mParent;
2615
2616    /**
2617     * {@hide}
2618     */
2619    AttachInfo mAttachInfo;
2620
2621    /**
2622     * {@hide}
2623     */
2624    @ViewDebug.ExportedProperty(flagMapping = {
2625        @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT,
2626                name = "FORCE_LAYOUT"),
2627        @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED,
2628                name = "LAYOUT_REQUIRED"),
2629        @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID,
2630            name = "DRAWING_CACHE_INVALID", outputIf = false),
2631        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true),
2632        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false),
2633        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
2634        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY")
2635    })
2636    int mPrivateFlags;
2637    int mPrivateFlags2;
2638    int mPrivateFlags3;
2639
2640    /**
2641     * This view's request for the visibility of the status bar.
2642     * @hide
2643     */
2644    @ViewDebug.ExportedProperty(flagMapping = {
2645        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
2646                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
2647                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
2648        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2649                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2650                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
2651        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
2652                                equals = SYSTEM_UI_FLAG_VISIBLE,
2653                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
2654    })
2655    int mSystemUiVisibility;
2656
2657    /**
2658     * Reference count for transient state.
2659     * @see #setHasTransientState(boolean)
2660     */
2661    int mTransientStateCount = 0;
2662
2663    /**
2664     * Count of how many windows this view has been attached to.
2665     */
2666    int mWindowAttachCount;
2667
2668    /**
2669     * The layout parameters associated with this view and used by the parent
2670     * {@link android.view.ViewGroup} to determine how this view should be
2671     * laid out.
2672     * {@hide}
2673     */
2674    protected ViewGroup.LayoutParams mLayoutParams;
2675
2676    /**
2677     * The view flags hold various views states.
2678     * {@hide}
2679     */
2680    @ViewDebug.ExportedProperty
2681    int mViewFlags;
2682
2683    static class TransformationInfo {
2684        /**
2685         * The transform matrix for the View. This transform is calculated internally
2686         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2687         * is used by default. Do *not* use this variable directly; instead call
2688         * getMatrix(), which will automatically recalculate the matrix if necessary
2689         * to get the correct matrix based on the latest rotation and scale properties.
2690         */
2691        private final Matrix mMatrix = new Matrix();
2692
2693        /**
2694         * The transform matrix for the View. This transform is calculated internally
2695         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2696         * is used by default. Do *not* use this variable directly; instead call
2697         * getInverseMatrix(), which will automatically recalculate the matrix if necessary
2698         * to get the correct matrix based on the latest rotation and scale properties.
2699         */
2700        private Matrix mInverseMatrix;
2701
2702        /**
2703         * An internal variable that tracks whether we need to recalculate the
2704         * transform matrix, based on whether the rotation or scaleX/Y properties
2705         * have changed since the matrix was last calculated.
2706         */
2707        boolean mMatrixDirty = false;
2708
2709        /**
2710         * An internal variable that tracks whether we need to recalculate the
2711         * transform matrix, based on whether the rotation or scaleX/Y properties
2712         * have changed since the matrix was last calculated.
2713         */
2714        private boolean mInverseMatrixDirty = true;
2715
2716        /**
2717         * A variable that tracks whether we need to recalculate the
2718         * transform matrix, based on whether the rotation or scaleX/Y properties
2719         * have changed since the matrix was last calculated. This variable
2720         * is only valid after a call to updateMatrix() or to a function that
2721         * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
2722         */
2723        private boolean mMatrixIsIdentity = true;
2724
2725        /**
2726         * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
2727         */
2728        private Camera mCamera = null;
2729
2730        /**
2731         * This matrix is used when computing the matrix for 3D rotations.
2732         */
2733        private Matrix matrix3D = null;
2734
2735        /**
2736         * These prev values are used to recalculate a centered pivot point when necessary. The
2737         * pivot point is only used in matrix operations (when rotation, scale, or translation are
2738         * set), so thes values are only used then as well.
2739         */
2740        private int mPrevWidth = -1;
2741        private int mPrevHeight = -1;
2742
2743        /**
2744         * The degrees rotation around the vertical axis through the pivot point.
2745         */
2746        @ViewDebug.ExportedProperty
2747        float mRotationY = 0f;
2748
2749        /**
2750         * The degrees rotation around the horizontal axis through the pivot point.
2751         */
2752        @ViewDebug.ExportedProperty
2753        float mRotationX = 0f;
2754
2755        /**
2756         * The degrees rotation around the pivot point.
2757         */
2758        @ViewDebug.ExportedProperty
2759        float mRotation = 0f;
2760
2761        /**
2762         * The amount of translation of the object away from its left property (post-layout).
2763         */
2764        @ViewDebug.ExportedProperty
2765        float mTranslationX = 0f;
2766
2767        /**
2768         * The amount of translation of the object away from its top property (post-layout).
2769         */
2770        @ViewDebug.ExportedProperty
2771        float mTranslationY = 0f;
2772
2773        /**
2774         * The amount of scale in the x direction around the pivot point. A
2775         * value of 1 means no scaling is applied.
2776         */
2777        @ViewDebug.ExportedProperty
2778        float mScaleX = 1f;
2779
2780        /**
2781         * The amount of scale in the y direction around the pivot point. A
2782         * value of 1 means no scaling is applied.
2783         */
2784        @ViewDebug.ExportedProperty
2785        float mScaleY = 1f;
2786
2787        /**
2788         * The x location of the point around which the view is rotated and scaled.
2789         */
2790        @ViewDebug.ExportedProperty
2791        float mPivotX = 0f;
2792
2793        /**
2794         * The y location of the point around which the view is rotated and scaled.
2795         */
2796        @ViewDebug.ExportedProperty
2797        float mPivotY = 0f;
2798
2799        /**
2800         * The opacity of the View. This is a value from 0 to 1, where 0 means
2801         * completely transparent and 1 means completely opaque.
2802         */
2803        @ViewDebug.ExportedProperty
2804        float mAlpha = 1f;
2805    }
2806
2807    TransformationInfo mTransformationInfo;
2808
2809    /**
2810     * Current clip bounds. to which all drawing of this view are constrained.
2811     */
2812    private Rect mClipBounds = null;
2813
2814    private boolean mLastIsOpaque;
2815
2816    /**
2817     * Convenience value to check for float values that are close enough to zero to be considered
2818     * zero.
2819     */
2820    private static final float NONZERO_EPSILON = .001f;
2821
2822    /**
2823     * The distance in pixels from the left edge of this view's parent
2824     * to the left edge of this view.
2825     * {@hide}
2826     */
2827    @ViewDebug.ExportedProperty(category = "layout")
2828    protected int mLeft;
2829    /**
2830     * The distance in pixels from the left edge of this view's parent
2831     * to the right edge of this view.
2832     * {@hide}
2833     */
2834    @ViewDebug.ExportedProperty(category = "layout")
2835    protected int mRight;
2836    /**
2837     * The distance in pixels from the top edge of this view's parent
2838     * to the top edge of this view.
2839     * {@hide}
2840     */
2841    @ViewDebug.ExportedProperty(category = "layout")
2842    protected int mTop;
2843    /**
2844     * The distance in pixels from the top edge of this view's parent
2845     * to the bottom edge of this view.
2846     * {@hide}
2847     */
2848    @ViewDebug.ExportedProperty(category = "layout")
2849    protected int mBottom;
2850
2851    /**
2852     * The offset, in pixels, by which the content of this view is scrolled
2853     * horizontally.
2854     * {@hide}
2855     */
2856    @ViewDebug.ExportedProperty(category = "scrolling")
2857    protected int mScrollX;
2858    /**
2859     * The offset, in pixels, by which the content of this view is scrolled
2860     * vertically.
2861     * {@hide}
2862     */
2863    @ViewDebug.ExportedProperty(category = "scrolling")
2864    protected int mScrollY;
2865
2866    /**
2867     * The left padding in pixels, that is the distance in pixels between the
2868     * left edge of this view and the left edge of its content.
2869     * {@hide}
2870     */
2871    @ViewDebug.ExportedProperty(category = "padding")
2872    protected int mPaddingLeft = 0;
2873    /**
2874     * The right padding in pixels, that is the distance in pixels between the
2875     * right edge of this view and the right edge of its content.
2876     * {@hide}
2877     */
2878    @ViewDebug.ExportedProperty(category = "padding")
2879    protected int mPaddingRight = 0;
2880    /**
2881     * The top padding in pixels, that is the distance in pixels between the
2882     * top edge of this view and the top edge of its content.
2883     * {@hide}
2884     */
2885    @ViewDebug.ExportedProperty(category = "padding")
2886    protected int mPaddingTop;
2887    /**
2888     * The bottom padding in pixels, that is the distance in pixels between the
2889     * bottom edge of this view and the bottom edge of its content.
2890     * {@hide}
2891     */
2892    @ViewDebug.ExportedProperty(category = "padding")
2893    protected int mPaddingBottom;
2894
2895    /**
2896     * The layout insets in pixels, that is the distance in pixels between the
2897     * visible edges of this view its bounds.
2898     */
2899    private Insets mLayoutInsets;
2900
2901    /**
2902     * Briefly describes the view and is primarily used for accessibility support.
2903     */
2904    private CharSequence mContentDescription;
2905
2906    /**
2907     * Specifies the id of a view for which this view serves as a label for
2908     * accessibility purposes.
2909     */
2910    private int mLabelForId = View.NO_ID;
2911
2912    /**
2913     * Predicate for matching labeled view id with its label for
2914     * accessibility purposes.
2915     */
2916    private MatchLabelForPredicate mMatchLabelForPredicate;
2917
2918    /**
2919     * Predicate for matching a view by its id.
2920     */
2921    private MatchIdPredicate mMatchIdPredicate;
2922
2923    /**
2924     * Cache the paddingRight set by the user to append to the scrollbar's size.
2925     *
2926     * @hide
2927     */
2928    @ViewDebug.ExportedProperty(category = "padding")
2929    protected int mUserPaddingRight;
2930
2931    /**
2932     * Cache the paddingBottom set by the user to append to the scrollbar's size.
2933     *
2934     * @hide
2935     */
2936    @ViewDebug.ExportedProperty(category = "padding")
2937    protected int mUserPaddingBottom;
2938
2939    /**
2940     * Cache the paddingLeft set by the user to append to the scrollbar's size.
2941     *
2942     * @hide
2943     */
2944    @ViewDebug.ExportedProperty(category = "padding")
2945    protected int mUserPaddingLeft;
2946
2947    /**
2948     * Cache the paddingStart set by the user to append to the scrollbar's size.
2949     *
2950     */
2951    @ViewDebug.ExportedProperty(category = "padding")
2952    int mUserPaddingStart;
2953
2954    /**
2955     * Cache the paddingEnd set by the user to append to the scrollbar's size.
2956     *
2957     */
2958    @ViewDebug.ExportedProperty(category = "padding")
2959    int mUserPaddingEnd;
2960
2961    /**
2962     * Cache initial left padding.
2963     *
2964     * @hide
2965     */
2966    int mUserPaddingLeftInitial;
2967
2968    /**
2969     * Cache initial right padding.
2970     *
2971     * @hide
2972     */
2973    int mUserPaddingRightInitial;
2974
2975    /**
2976     * Default undefined padding
2977     */
2978    private static final int UNDEFINED_PADDING = Integer.MIN_VALUE;
2979
2980    /**
2981     * @hide
2982     */
2983    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
2984    /**
2985     * @hide
2986     */
2987    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
2988
2989    private LongSparseLongArray mMeasureCache;
2990
2991    @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_")
2992    private Drawable mBackground;
2993
2994    private int mBackgroundResource;
2995    private boolean mBackgroundSizeChanged;
2996
2997    static class ListenerInfo {
2998        /**
2999         * Listener used to dispatch focus change events.
3000         * This field should be made private, so it is hidden from the SDK.
3001         * {@hide}
3002         */
3003        protected OnFocusChangeListener mOnFocusChangeListener;
3004
3005        /**
3006         * Listeners for layout change events.
3007         */
3008        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
3009
3010        /**
3011         * Listeners for attach events.
3012         */
3013        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
3014
3015        /**
3016         * Listener used to dispatch click events.
3017         * This field should be made private, so it is hidden from the SDK.
3018         * {@hide}
3019         */
3020        public OnClickListener mOnClickListener;
3021
3022        /**
3023         * Listener used to dispatch long click events.
3024         * This field should be made private, so it is hidden from the SDK.
3025         * {@hide}
3026         */
3027        protected OnLongClickListener mOnLongClickListener;
3028
3029        /**
3030         * Listener used to build the context menu.
3031         * This field should be made private, so it is hidden from the SDK.
3032         * {@hide}
3033         */
3034        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
3035
3036        private OnKeyListener mOnKeyListener;
3037
3038        private OnTouchListener mOnTouchListener;
3039
3040        private OnHoverListener mOnHoverListener;
3041
3042        private OnGenericMotionListener mOnGenericMotionListener;
3043
3044        private OnDragListener mOnDragListener;
3045
3046        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
3047    }
3048
3049    ListenerInfo mListenerInfo;
3050
3051    /**
3052     * The application environment this view lives in.
3053     * This field should be made private, so it is hidden from the SDK.
3054     * {@hide}
3055     */
3056    protected Context mContext;
3057
3058    private final Resources mResources;
3059
3060    private ScrollabilityCache mScrollCache;
3061
3062    private int[] mDrawableState = null;
3063
3064    /**
3065     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
3066     * the user may specify which view to go to next.
3067     */
3068    private int mNextFocusLeftId = View.NO_ID;
3069
3070    /**
3071     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
3072     * the user may specify which view to go to next.
3073     */
3074    private int mNextFocusRightId = View.NO_ID;
3075
3076    /**
3077     * When this view has focus and the next focus is {@link #FOCUS_UP},
3078     * the user may specify which view to go to next.
3079     */
3080    private int mNextFocusUpId = View.NO_ID;
3081
3082    /**
3083     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
3084     * the user may specify which view to go to next.
3085     */
3086    private int mNextFocusDownId = View.NO_ID;
3087
3088    /**
3089     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
3090     * the user may specify which view to go to next.
3091     */
3092    int mNextFocusForwardId = View.NO_ID;
3093
3094    private CheckForLongPress mPendingCheckForLongPress;
3095    private CheckForTap mPendingCheckForTap = null;
3096    private PerformClick mPerformClick;
3097    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
3098
3099    private UnsetPressedState mUnsetPressedState;
3100
3101    /**
3102     * Whether the long press's action has been invoked.  The tap's action is invoked on the
3103     * up event while a long press is invoked as soon as the long press duration is reached, so
3104     * a long press could be performed before the tap is checked, in which case the tap's action
3105     * should not be invoked.
3106     */
3107    private boolean mHasPerformedLongPress;
3108
3109    /**
3110     * The minimum height of the view. We'll try our best to have the height
3111     * of this view to at least this amount.
3112     */
3113    @ViewDebug.ExportedProperty(category = "measurement")
3114    private int mMinHeight;
3115
3116    /**
3117     * The minimum width of the view. We'll try our best to have the width
3118     * of this view to at least this amount.
3119     */
3120    @ViewDebug.ExportedProperty(category = "measurement")
3121    private int mMinWidth;
3122
3123    /**
3124     * The delegate to handle touch events that are physically in this view
3125     * but should be handled by another view.
3126     */
3127    private TouchDelegate mTouchDelegate = null;
3128
3129    /**
3130     * Solid color to use as a background when creating the drawing cache. Enables
3131     * the cache to use 16 bit bitmaps instead of 32 bit.
3132     */
3133    private int mDrawingCacheBackgroundColor = 0;
3134
3135    /**
3136     * Special tree observer used when mAttachInfo is null.
3137     */
3138    private ViewTreeObserver mFloatingTreeObserver;
3139
3140    /**
3141     * Cache the touch slop from the context that created the view.
3142     */
3143    private int mTouchSlop;
3144
3145    /**
3146     * Object that handles automatic animation of view properties.
3147     */
3148    private ViewPropertyAnimator mAnimator = null;
3149
3150    /**
3151     * Flag indicating that a drag can cross window boundaries.  When
3152     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
3153     * with this flag set, all visible applications will be able to participate
3154     * in the drag operation and receive the dragged content.
3155     *
3156     * @hide
3157     */
3158    public static final int DRAG_FLAG_GLOBAL = 1;
3159
3160    /**
3161     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
3162     */
3163    private float mVerticalScrollFactor;
3164
3165    /**
3166     * Position of the vertical scroll bar.
3167     */
3168    private int mVerticalScrollbarPosition;
3169
3170    /**
3171     * Position the scroll bar at the default position as determined by the system.
3172     */
3173    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
3174
3175    /**
3176     * Position the scroll bar along the left edge.
3177     */
3178    public static final int SCROLLBAR_POSITION_LEFT = 1;
3179
3180    /**
3181     * Position the scroll bar along the right edge.
3182     */
3183    public static final int SCROLLBAR_POSITION_RIGHT = 2;
3184
3185    /**
3186     * Indicates that the view does not have a layer.
3187     *
3188     * @see #getLayerType()
3189     * @see #setLayerType(int, android.graphics.Paint)
3190     * @see #LAYER_TYPE_SOFTWARE
3191     * @see #LAYER_TYPE_HARDWARE
3192     */
3193    public static final int LAYER_TYPE_NONE = 0;
3194
3195    /**
3196     * <p>Indicates that the view has a software layer. A software layer is backed
3197     * by a bitmap and causes the view to be rendered using Android's software
3198     * rendering pipeline, even if hardware acceleration is enabled.</p>
3199     *
3200     * <p>Software layers have various usages:</p>
3201     * <p>When the application is not using hardware acceleration, a software layer
3202     * is useful to apply a specific color filter and/or blending mode and/or
3203     * translucency to a view and all its children.</p>
3204     * <p>When the application is using hardware acceleration, a software layer
3205     * is useful to render drawing primitives not supported by the hardware
3206     * accelerated pipeline. It can also be used to cache a complex view tree
3207     * into a texture and reduce the complexity of drawing operations. For instance,
3208     * when animating a complex view tree with a translation, a software layer can
3209     * be used to render the view tree only once.</p>
3210     * <p>Software layers should be avoided when the affected view tree updates
3211     * often. Every update will require to re-render the software layer, which can
3212     * potentially be slow (particularly when hardware acceleration is turned on
3213     * since the layer will have to be uploaded into a hardware texture after every
3214     * update.)</p>
3215     *
3216     * @see #getLayerType()
3217     * @see #setLayerType(int, android.graphics.Paint)
3218     * @see #LAYER_TYPE_NONE
3219     * @see #LAYER_TYPE_HARDWARE
3220     */
3221    public static final int LAYER_TYPE_SOFTWARE = 1;
3222
3223    /**
3224     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3225     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3226     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3227     * rendering pipeline, but only if hardware acceleration is turned on for the
3228     * view hierarchy. When hardware acceleration is turned off, hardware layers
3229     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3230     *
3231     * <p>A hardware layer is useful to apply a specific color filter and/or
3232     * blending mode and/or translucency to a view and all its children.</p>
3233     * <p>A hardware layer can be used to cache a complex view tree into a
3234     * texture and reduce the complexity of drawing operations. For instance,
3235     * when animating a complex view tree with a translation, a hardware layer can
3236     * be used to render the view tree only once.</p>
3237     * <p>A hardware layer can also be used to increase the rendering quality when
3238     * rotation transformations are applied on a view. It can also be used to
3239     * prevent potential clipping issues when applying 3D transforms on a view.</p>
3240     *
3241     * @see #getLayerType()
3242     * @see #setLayerType(int, android.graphics.Paint)
3243     * @see #LAYER_TYPE_NONE
3244     * @see #LAYER_TYPE_SOFTWARE
3245     */
3246    public static final int LAYER_TYPE_HARDWARE = 2;
3247
3248    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3249            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
3250            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
3251            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
3252    })
3253    int mLayerType = LAYER_TYPE_NONE;
3254    Paint mLayerPaint;
3255    Rect mLocalDirtyRect;
3256    private HardwareLayer mHardwareLayer;
3257
3258    /**
3259     * Set to true when drawing cache is enabled and cannot be created.
3260     *
3261     * @hide
3262     */
3263    public boolean mCachingFailed;
3264    private Bitmap mDrawingCache;
3265    private Bitmap mUnscaledDrawingCache;
3266
3267    DisplayList mDisplayList;
3268
3269    /**
3270     * Set to true when the view is sending hover accessibility events because it
3271     * is the innermost hovered view.
3272     */
3273    private boolean mSendingHoverAccessibilityEvents;
3274
3275    /**
3276     * Delegate for injecting accessibility functionality.
3277     */
3278    AccessibilityDelegate mAccessibilityDelegate;
3279
3280    /**
3281     * The view's overlay layer. Developers get a reference to the overlay via getOverlay()
3282     * and add/remove objects to/from the overlay directly through the Overlay methods.
3283     */
3284    ViewOverlay mOverlay;
3285
3286    /**
3287     * Consistency verifier for debugging purposes.
3288     * @hide
3289     */
3290    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
3291            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
3292                    new InputEventConsistencyVerifier(this, 0) : null;
3293
3294    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
3295
3296    /**
3297     * Simple constructor to use when creating a view from code.
3298     *
3299     * @param context The Context the view is running in, through which it can
3300     *        access the current theme, resources, etc.
3301     */
3302    public View(Context context) {
3303        mContext = context;
3304        mResources = context != null ? context.getResources() : null;
3305        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
3306        // Set some flags defaults
3307        mPrivateFlags2 =
3308                (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) |
3309                (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) |
3310                (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) |
3311                (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) |
3312                (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) |
3313                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
3314        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
3315        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
3316        mUserPaddingStart = UNDEFINED_PADDING;
3317        mUserPaddingEnd = UNDEFINED_PADDING;
3318
3319        if (!sUseBrokenMakeMeasureSpec && context != null &&
3320                context.getApplicationInfo().targetSdkVersion <= JELLY_BEAN_MR1) {
3321            // Older apps may need this compatibility hack for measurement.
3322            sUseBrokenMakeMeasureSpec = true;
3323        }
3324    }
3325
3326    /**
3327     * Constructor that is called when inflating a view from XML. This is called
3328     * when a view is being constructed from an XML file, supplying attributes
3329     * that were specified in the XML file. This version uses a default style of
3330     * 0, so the only attribute values applied are those in the Context's Theme
3331     * and the given AttributeSet.
3332     *
3333     * <p>
3334     * The method onFinishInflate() will be called after all children have been
3335     * added.
3336     *
3337     * @param context The Context the view is running in, through which it can
3338     *        access the current theme, resources, etc.
3339     * @param attrs The attributes of the XML tag that is inflating the view.
3340     * @see #View(Context, AttributeSet, int)
3341     */
3342    public View(Context context, AttributeSet attrs) {
3343        this(context, attrs, 0);
3344    }
3345
3346    /**
3347     * Perform inflation from XML and apply a class-specific base style. This
3348     * constructor of View allows subclasses to use their own base style when
3349     * they are inflating. For example, a Button class's constructor would call
3350     * this version of the super class constructor and supply
3351     * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
3352     * the theme's button style to modify all of the base view attributes (in
3353     * particular its background) as well as the Button class's attributes.
3354     *
3355     * @param context The Context the view is running in, through which it can
3356     *        access the current theme, resources, etc.
3357     * @param attrs The attributes of the XML tag that is inflating the view.
3358     * @param defStyle The default style to apply to this view. If 0, no style
3359     *        will be applied (beyond what is included in the theme). This may
3360     *        either be an attribute resource, whose value will be retrieved
3361     *        from the current theme, or an explicit style resource.
3362     * @see #View(Context, AttributeSet)
3363     */
3364    public View(Context context, AttributeSet attrs, int defStyle) {
3365        this(context);
3366
3367        TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
3368                defStyle, 0);
3369
3370        Drawable background = null;
3371
3372        int leftPadding = -1;
3373        int topPadding = -1;
3374        int rightPadding = -1;
3375        int bottomPadding = -1;
3376        int startPadding = UNDEFINED_PADDING;
3377        int endPadding = UNDEFINED_PADDING;
3378
3379        int padding = -1;
3380
3381        int viewFlagValues = 0;
3382        int viewFlagMasks = 0;
3383
3384        boolean setScrollContainer = false;
3385
3386        int x = 0;
3387        int y = 0;
3388
3389        float tx = 0;
3390        float ty = 0;
3391        float rotation = 0;
3392        float rotationX = 0;
3393        float rotationY = 0;
3394        float sx = 1f;
3395        float sy = 1f;
3396        boolean transformSet = false;
3397
3398        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
3399        int overScrollMode = mOverScrollMode;
3400        boolean initializeScrollbars = false;
3401
3402        boolean leftPaddingDefined = false;
3403        boolean rightPaddingDefined = false;
3404        boolean startPaddingDefined = false;
3405        boolean endPaddingDefined = false;
3406
3407        final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3408
3409        final int N = a.getIndexCount();
3410        for (int i = 0; i < N; i++) {
3411            int attr = a.getIndex(i);
3412            switch (attr) {
3413                case com.android.internal.R.styleable.View_background:
3414                    background = a.getDrawable(attr);
3415                    break;
3416                case com.android.internal.R.styleable.View_padding:
3417                    padding = a.getDimensionPixelSize(attr, -1);
3418                    mUserPaddingLeftInitial = padding;
3419                    mUserPaddingRightInitial = padding;
3420                    leftPaddingDefined = true;
3421                    rightPaddingDefined = true;
3422                    break;
3423                 case com.android.internal.R.styleable.View_paddingLeft:
3424                    leftPadding = a.getDimensionPixelSize(attr, -1);
3425                    mUserPaddingLeftInitial = leftPadding;
3426                    leftPaddingDefined = true;
3427                    break;
3428                case com.android.internal.R.styleable.View_paddingTop:
3429                    topPadding = a.getDimensionPixelSize(attr, -1);
3430                    break;
3431                case com.android.internal.R.styleable.View_paddingRight:
3432                    rightPadding = a.getDimensionPixelSize(attr, -1);
3433                    mUserPaddingRightInitial = rightPadding;
3434                    rightPaddingDefined = true;
3435                    break;
3436                case com.android.internal.R.styleable.View_paddingBottom:
3437                    bottomPadding = a.getDimensionPixelSize(attr, -1);
3438                    break;
3439                case com.android.internal.R.styleable.View_paddingStart:
3440                    startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3441                    startPaddingDefined = (startPadding != UNDEFINED_PADDING);
3442                    break;
3443                case com.android.internal.R.styleable.View_paddingEnd:
3444                    endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3445                    endPaddingDefined = (endPadding != UNDEFINED_PADDING);
3446                    break;
3447                case com.android.internal.R.styleable.View_scrollX:
3448                    x = a.getDimensionPixelOffset(attr, 0);
3449                    break;
3450                case com.android.internal.R.styleable.View_scrollY:
3451                    y = a.getDimensionPixelOffset(attr, 0);
3452                    break;
3453                case com.android.internal.R.styleable.View_alpha:
3454                    setAlpha(a.getFloat(attr, 1f));
3455                    break;
3456                case com.android.internal.R.styleable.View_transformPivotX:
3457                    setPivotX(a.getDimensionPixelOffset(attr, 0));
3458                    break;
3459                case com.android.internal.R.styleable.View_transformPivotY:
3460                    setPivotY(a.getDimensionPixelOffset(attr, 0));
3461                    break;
3462                case com.android.internal.R.styleable.View_translationX:
3463                    tx = a.getDimensionPixelOffset(attr, 0);
3464                    transformSet = true;
3465                    break;
3466                case com.android.internal.R.styleable.View_translationY:
3467                    ty = a.getDimensionPixelOffset(attr, 0);
3468                    transformSet = true;
3469                    break;
3470                case com.android.internal.R.styleable.View_rotation:
3471                    rotation = a.getFloat(attr, 0);
3472                    transformSet = true;
3473                    break;
3474                case com.android.internal.R.styleable.View_rotationX:
3475                    rotationX = a.getFloat(attr, 0);
3476                    transformSet = true;
3477                    break;
3478                case com.android.internal.R.styleable.View_rotationY:
3479                    rotationY = a.getFloat(attr, 0);
3480                    transformSet = true;
3481                    break;
3482                case com.android.internal.R.styleable.View_scaleX:
3483                    sx = a.getFloat(attr, 1f);
3484                    transformSet = true;
3485                    break;
3486                case com.android.internal.R.styleable.View_scaleY:
3487                    sy = a.getFloat(attr, 1f);
3488                    transformSet = true;
3489                    break;
3490                case com.android.internal.R.styleable.View_id:
3491                    mID = a.getResourceId(attr, NO_ID);
3492                    break;
3493                case com.android.internal.R.styleable.View_tag:
3494                    mTag = a.getText(attr);
3495                    break;
3496                case com.android.internal.R.styleable.View_fitsSystemWindows:
3497                    if (a.getBoolean(attr, false)) {
3498                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
3499                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
3500                    }
3501                    break;
3502                case com.android.internal.R.styleable.View_focusable:
3503                    if (a.getBoolean(attr, false)) {
3504                        viewFlagValues |= FOCUSABLE;
3505                        viewFlagMasks |= FOCUSABLE_MASK;
3506                    }
3507                    break;
3508                case com.android.internal.R.styleable.View_focusableInTouchMode:
3509                    if (a.getBoolean(attr, false)) {
3510                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
3511                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
3512                    }
3513                    break;
3514                case com.android.internal.R.styleable.View_clickable:
3515                    if (a.getBoolean(attr, false)) {
3516                        viewFlagValues |= CLICKABLE;
3517                        viewFlagMasks |= CLICKABLE;
3518                    }
3519                    break;
3520                case com.android.internal.R.styleable.View_longClickable:
3521                    if (a.getBoolean(attr, false)) {
3522                        viewFlagValues |= LONG_CLICKABLE;
3523                        viewFlagMasks |= LONG_CLICKABLE;
3524                    }
3525                    break;
3526                case com.android.internal.R.styleable.View_saveEnabled:
3527                    if (!a.getBoolean(attr, true)) {
3528                        viewFlagValues |= SAVE_DISABLED;
3529                        viewFlagMasks |= SAVE_DISABLED_MASK;
3530                    }
3531                    break;
3532                case com.android.internal.R.styleable.View_duplicateParentState:
3533                    if (a.getBoolean(attr, false)) {
3534                        viewFlagValues |= DUPLICATE_PARENT_STATE;
3535                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
3536                    }
3537                    break;
3538                case com.android.internal.R.styleable.View_visibility:
3539                    final int visibility = a.getInt(attr, 0);
3540                    if (visibility != 0) {
3541                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
3542                        viewFlagMasks |= VISIBILITY_MASK;
3543                    }
3544                    break;
3545                case com.android.internal.R.styleable.View_layoutDirection:
3546                    // Clear any layout direction flags (included resolved bits) already set
3547                    mPrivateFlags2 &=
3548                            ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK);
3549                    // Set the layout direction flags depending on the value of the attribute
3550                    final int layoutDirection = a.getInt(attr, -1);
3551                    final int value = (layoutDirection != -1) ?
3552                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
3553                    mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT);
3554                    break;
3555                case com.android.internal.R.styleable.View_drawingCacheQuality:
3556                    final int cacheQuality = a.getInt(attr, 0);
3557                    if (cacheQuality != 0) {
3558                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
3559                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
3560                    }
3561                    break;
3562                case com.android.internal.R.styleable.View_contentDescription:
3563                    setContentDescription(a.getString(attr));
3564                    break;
3565                case com.android.internal.R.styleable.View_labelFor:
3566                    setLabelFor(a.getResourceId(attr, NO_ID));
3567                    break;
3568                case com.android.internal.R.styleable.View_soundEffectsEnabled:
3569                    if (!a.getBoolean(attr, true)) {
3570                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
3571                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
3572                    }
3573                    break;
3574                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
3575                    if (!a.getBoolean(attr, true)) {
3576                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
3577                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
3578                    }
3579                    break;
3580                case R.styleable.View_scrollbars:
3581                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
3582                    if (scrollbars != SCROLLBARS_NONE) {
3583                        viewFlagValues |= scrollbars;
3584                        viewFlagMasks |= SCROLLBARS_MASK;
3585                        initializeScrollbars = true;
3586                    }
3587                    break;
3588                //noinspection deprecation
3589                case R.styleable.View_fadingEdge:
3590                    if (targetSdkVersion >= ICE_CREAM_SANDWICH) {
3591                        // Ignore the attribute starting with ICS
3592                        break;
3593                    }
3594                    // With builds < ICS, fall through and apply fading edges
3595                case R.styleable.View_requiresFadingEdge:
3596                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
3597                    if (fadingEdge != FADING_EDGE_NONE) {
3598                        viewFlagValues |= fadingEdge;
3599                        viewFlagMasks |= FADING_EDGE_MASK;
3600                        initializeFadingEdge(a);
3601                    }
3602                    break;
3603                case R.styleable.View_scrollbarStyle:
3604                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
3605                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3606                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
3607                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
3608                    }
3609                    break;
3610                case R.styleable.View_isScrollContainer:
3611                    setScrollContainer = true;
3612                    if (a.getBoolean(attr, false)) {
3613                        setScrollContainer(true);
3614                    }
3615                    break;
3616                case com.android.internal.R.styleable.View_keepScreenOn:
3617                    if (a.getBoolean(attr, false)) {
3618                        viewFlagValues |= KEEP_SCREEN_ON;
3619                        viewFlagMasks |= KEEP_SCREEN_ON;
3620                    }
3621                    break;
3622                case R.styleable.View_filterTouchesWhenObscured:
3623                    if (a.getBoolean(attr, false)) {
3624                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
3625                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
3626                    }
3627                    break;
3628                case R.styleable.View_nextFocusLeft:
3629                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
3630                    break;
3631                case R.styleable.View_nextFocusRight:
3632                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
3633                    break;
3634                case R.styleable.View_nextFocusUp:
3635                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
3636                    break;
3637                case R.styleable.View_nextFocusDown:
3638                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
3639                    break;
3640                case R.styleable.View_nextFocusForward:
3641                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
3642                    break;
3643                case R.styleable.View_minWidth:
3644                    mMinWidth = a.getDimensionPixelSize(attr, 0);
3645                    break;
3646                case R.styleable.View_minHeight:
3647                    mMinHeight = a.getDimensionPixelSize(attr, 0);
3648                    break;
3649                case R.styleable.View_onClick:
3650                    if (context.isRestricted()) {
3651                        throw new IllegalStateException("The android:onClick attribute cannot "
3652                                + "be used within a restricted context");
3653                    }
3654
3655                    final String handlerName = a.getString(attr);
3656                    if (handlerName != null) {
3657                        setOnClickListener(new OnClickListener() {
3658                            private Method mHandler;
3659
3660                            public void onClick(View v) {
3661                                if (mHandler == null) {
3662                                    try {
3663                                        mHandler = getContext().getClass().getMethod(handlerName,
3664                                                View.class);
3665                                    } catch (NoSuchMethodException e) {
3666                                        int id = getId();
3667                                        String idText = id == NO_ID ? "" : " with id '"
3668                                                + getContext().getResources().getResourceEntryName(
3669                                                    id) + "'";
3670                                        throw new IllegalStateException("Could not find a method " +
3671                                                handlerName + "(View) in the activity "
3672                                                + getContext().getClass() + " for onClick handler"
3673                                                + " on view " + View.this.getClass() + idText, e);
3674                                    }
3675                                }
3676
3677                                try {
3678                                    mHandler.invoke(getContext(), View.this);
3679                                } catch (IllegalAccessException e) {
3680                                    throw new IllegalStateException("Could not execute non "
3681                                            + "public method of the activity", e);
3682                                } catch (InvocationTargetException e) {
3683                                    throw new IllegalStateException("Could not execute "
3684                                            + "method of the activity", e);
3685                                }
3686                            }
3687                        });
3688                    }
3689                    break;
3690                case R.styleable.View_overScrollMode:
3691                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
3692                    break;
3693                case R.styleable.View_verticalScrollbarPosition:
3694                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
3695                    break;
3696                case R.styleable.View_layerType:
3697                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
3698                    break;
3699                case R.styleable.View_textDirection:
3700                    // Clear any text direction flag already set
3701                    mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
3702                    // Set the text direction flags depending on the value of the attribute
3703                    final int textDirection = a.getInt(attr, -1);
3704                    if (textDirection != -1) {
3705                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection];
3706                    }
3707                    break;
3708                case R.styleable.View_textAlignment:
3709                    // Clear any text alignment flag already set
3710                    mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
3711                    // Set the text alignment flag depending on the value of the attribute
3712                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
3713                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment];
3714                    break;
3715                case R.styleable.View_importantForAccessibility:
3716                    setImportantForAccessibility(a.getInt(attr,
3717                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
3718                    break;
3719            }
3720        }
3721
3722        setOverScrollMode(overScrollMode);
3723
3724        // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet
3725        // the resolved layout direction). Those cached values will be used later during padding
3726        // resolution.
3727        mUserPaddingStart = startPadding;
3728        mUserPaddingEnd = endPadding;
3729
3730        if (background != null) {
3731            setBackground(background);
3732        }
3733
3734        if (padding >= 0) {
3735            leftPadding = padding;
3736            topPadding = padding;
3737            rightPadding = padding;
3738            bottomPadding = padding;
3739            mUserPaddingLeftInitial = padding;
3740            mUserPaddingRightInitial = padding;
3741        }
3742
3743        if (isRtlCompatibilityMode()) {
3744            // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case.
3745            // left / right padding are used if defined (meaning here nothing to do). If they are not
3746            // defined and start / end padding are defined (e.g. in Frameworks resources), then we use
3747            // start / end and resolve them as left / right (layout direction is not taken into account).
3748            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
3749            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
3750            // defined.
3751            if (!leftPaddingDefined && startPaddingDefined) {
3752                leftPadding = startPadding;
3753            }
3754            mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial;
3755            if (!rightPaddingDefined && endPaddingDefined) {
3756                rightPadding = endPadding;
3757            }
3758            mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial;
3759        } else {
3760            // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right
3761            // values defined. Otherwise, left /right values are used.
3762            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
3763            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
3764            // defined.
3765            final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined;
3766
3767            if (leftPaddingDefined && !hasRelativePadding) {
3768                mUserPaddingLeftInitial = leftPadding;
3769            }
3770            if (rightPaddingDefined && !hasRelativePadding) {
3771                mUserPaddingRightInitial = rightPadding;
3772            }
3773        }
3774
3775        internalSetPadding(
3776                mUserPaddingLeftInitial,
3777                topPadding >= 0 ? topPadding : mPaddingTop,
3778                mUserPaddingRightInitial,
3779                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
3780
3781        if (viewFlagMasks != 0) {
3782            setFlags(viewFlagValues, viewFlagMasks);
3783        }
3784
3785        if (initializeScrollbars) {
3786            initializeScrollbars(a);
3787        }
3788
3789        a.recycle();
3790
3791        // Needs to be called after mViewFlags is set
3792        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3793            recomputePadding();
3794        }
3795
3796        if (x != 0 || y != 0) {
3797            scrollTo(x, y);
3798        }
3799
3800        if (transformSet) {
3801            setTranslationX(tx);
3802            setTranslationY(ty);
3803            setRotation(rotation);
3804            setRotationX(rotationX);
3805            setRotationY(rotationY);
3806            setScaleX(sx);
3807            setScaleY(sy);
3808        }
3809
3810        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
3811            setScrollContainer(true);
3812        }
3813
3814        computeOpaqueFlags();
3815    }
3816
3817    /**
3818     * Non-public constructor for use in testing
3819     */
3820    View() {
3821        mResources = null;
3822    }
3823
3824    public String toString() {
3825        StringBuilder out = new StringBuilder(128);
3826        out.append(getClass().getName());
3827        out.append('{');
3828        out.append(Integer.toHexString(System.identityHashCode(this)));
3829        out.append(' ');
3830        switch (mViewFlags&VISIBILITY_MASK) {
3831            case VISIBLE: out.append('V'); break;
3832            case INVISIBLE: out.append('I'); break;
3833            case GONE: out.append('G'); break;
3834            default: out.append('.'); break;
3835        }
3836        out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.');
3837        out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.');
3838        out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D');
3839        out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.');
3840        out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.');
3841        out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.');
3842        out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.');
3843        out.append(' ');
3844        out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.');
3845        out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.');
3846        out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.');
3847        if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) {
3848            out.append('p');
3849        } else {
3850            out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.');
3851        }
3852        out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.');
3853        out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.');
3854        out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.');
3855        out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.');
3856        out.append(' ');
3857        out.append(mLeft);
3858        out.append(',');
3859        out.append(mTop);
3860        out.append('-');
3861        out.append(mRight);
3862        out.append(',');
3863        out.append(mBottom);
3864        final int id = getId();
3865        if (id != NO_ID) {
3866            out.append(" #");
3867            out.append(Integer.toHexString(id));
3868            final Resources r = mResources;
3869            if (id != 0 && r != null) {
3870                try {
3871                    String pkgname;
3872                    switch (id&0xff000000) {
3873                        case 0x7f000000:
3874                            pkgname="app";
3875                            break;
3876                        case 0x01000000:
3877                            pkgname="android";
3878                            break;
3879                        default:
3880                            pkgname = r.getResourcePackageName(id);
3881                            break;
3882                    }
3883                    String typename = r.getResourceTypeName(id);
3884                    String entryname = r.getResourceEntryName(id);
3885                    out.append(" ");
3886                    out.append(pkgname);
3887                    out.append(":");
3888                    out.append(typename);
3889                    out.append("/");
3890                    out.append(entryname);
3891                } catch (Resources.NotFoundException e) {
3892                }
3893            }
3894        }
3895        out.append("}");
3896        return out.toString();
3897    }
3898
3899    /**
3900     * <p>
3901     * Initializes the fading edges from a given set of styled attributes. This
3902     * method should be called by subclasses that need fading edges and when an
3903     * instance of these subclasses is created programmatically rather than
3904     * being inflated from XML. This method is automatically called when the XML
3905     * is inflated.
3906     * </p>
3907     *
3908     * @param a the styled attributes set to initialize the fading edges from
3909     */
3910    protected void initializeFadingEdge(TypedArray a) {
3911        initScrollCache();
3912
3913        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
3914                R.styleable.View_fadingEdgeLength,
3915                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
3916    }
3917
3918    /**
3919     * Returns the size of the vertical faded edges used to indicate that more
3920     * content in this view is visible.
3921     *
3922     * @return The size in pixels of the vertical faded edge or 0 if vertical
3923     *         faded edges are not enabled for this view.
3924     * @attr ref android.R.styleable#View_fadingEdgeLength
3925     */
3926    public int getVerticalFadingEdgeLength() {
3927        if (isVerticalFadingEdgeEnabled()) {
3928            ScrollabilityCache cache = mScrollCache;
3929            if (cache != null) {
3930                return cache.fadingEdgeLength;
3931            }
3932        }
3933        return 0;
3934    }
3935
3936    /**
3937     * Set the size of the faded edge used to indicate that more content in this
3938     * view is available.  Will not change whether the fading edge is enabled; use
3939     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
3940     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
3941     * for the vertical or horizontal fading edges.
3942     *
3943     * @param length The size in pixels of the faded edge used to indicate that more
3944     *        content in this view is visible.
3945     */
3946    public void setFadingEdgeLength(int length) {
3947        initScrollCache();
3948        mScrollCache.fadingEdgeLength = length;
3949    }
3950
3951    /**
3952     * Returns the size of the horizontal faded edges used to indicate that more
3953     * content in this view is visible.
3954     *
3955     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
3956     *         faded edges are not enabled for this view.
3957     * @attr ref android.R.styleable#View_fadingEdgeLength
3958     */
3959    public int getHorizontalFadingEdgeLength() {
3960        if (isHorizontalFadingEdgeEnabled()) {
3961            ScrollabilityCache cache = mScrollCache;
3962            if (cache != null) {
3963                return cache.fadingEdgeLength;
3964            }
3965        }
3966        return 0;
3967    }
3968
3969    /**
3970     * Returns the width of the vertical scrollbar.
3971     *
3972     * @return The width in pixels of the vertical scrollbar or 0 if there
3973     *         is no vertical scrollbar.
3974     */
3975    public int getVerticalScrollbarWidth() {
3976        ScrollabilityCache cache = mScrollCache;
3977        if (cache != null) {
3978            ScrollBarDrawable scrollBar = cache.scrollBar;
3979            if (scrollBar != null) {
3980                int size = scrollBar.getSize(true);
3981                if (size <= 0) {
3982                    size = cache.scrollBarSize;
3983                }
3984                return size;
3985            }
3986            return 0;
3987        }
3988        return 0;
3989    }
3990
3991    /**
3992     * Returns the height of the horizontal scrollbar.
3993     *
3994     * @return The height in pixels of the horizontal scrollbar or 0 if
3995     *         there is no horizontal scrollbar.
3996     */
3997    protected int getHorizontalScrollbarHeight() {
3998        ScrollabilityCache cache = mScrollCache;
3999        if (cache != null) {
4000            ScrollBarDrawable scrollBar = cache.scrollBar;
4001            if (scrollBar != null) {
4002                int size = scrollBar.getSize(false);
4003                if (size <= 0) {
4004                    size = cache.scrollBarSize;
4005                }
4006                return size;
4007            }
4008            return 0;
4009        }
4010        return 0;
4011    }
4012
4013    /**
4014     * <p>
4015     * Initializes the scrollbars from a given set of styled attributes. This
4016     * method should be called by subclasses that need scrollbars and when an
4017     * instance of these subclasses is created programmatically rather than
4018     * being inflated from XML. This method is automatically called when the XML
4019     * is inflated.
4020     * </p>
4021     *
4022     * @param a the styled attributes set to initialize the scrollbars from
4023     */
4024    protected void initializeScrollbars(TypedArray a) {
4025        initScrollCache();
4026
4027        final ScrollabilityCache scrollabilityCache = mScrollCache;
4028
4029        if (scrollabilityCache.scrollBar == null) {
4030            scrollabilityCache.scrollBar = new ScrollBarDrawable();
4031        }
4032
4033        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
4034
4035        if (!fadeScrollbars) {
4036            scrollabilityCache.state = ScrollabilityCache.ON;
4037        }
4038        scrollabilityCache.fadeScrollBars = fadeScrollbars;
4039
4040
4041        scrollabilityCache.scrollBarFadeDuration = a.getInt(
4042                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
4043                        .getScrollBarFadeDuration());
4044        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
4045                R.styleable.View_scrollbarDefaultDelayBeforeFade,
4046                ViewConfiguration.getScrollDefaultDelay());
4047
4048
4049        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
4050                com.android.internal.R.styleable.View_scrollbarSize,
4051                ViewConfiguration.get(mContext).getScaledScrollBarSize());
4052
4053        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
4054        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
4055
4056        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
4057        if (thumb != null) {
4058            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
4059        }
4060
4061        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
4062                false);
4063        if (alwaysDraw) {
4064            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
4065        }
4066
4067        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
4068        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
4069
4070        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
4071        if (thumb != null) {
4072            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
4073        }
4074
4075        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
4076                false);
4077        if (alwaysDraw) {
4078            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
4079        }
4080
4081        // Apply layout direction to the new Drawables if needed
4082        final int layoutDirection = getLayoutDirection();
4083        if (track != null) {
4084            track.setLayoutDirection(layoutDirection);
4085        }
4086        if (thumb != null) {
4087            thumb.setLayoutDirection(layoutDirection);
4088        }
4089
4090        // Re-apply user/background padding so that scrollbar(s) get added
4091        resolvePadding();
4092    }
4093
4094    /**
4095     * <p>
4096     * Initalizes the scrollability cache if necessary.
4097     * </p>
4098     */
4099    private void initScrollCache() {
4100        if (mScrollCache == null) {
4101            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
4102        }
4103    }
4104
4105    private ScrollabilityCache getScrollCache() {
4106        initScrollCache();
4107        return mScrollCache;
4108    }
4109
4110    /**
4111     * Set the position of the vertical scroll bar. Should be one of
4112     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
4113     * {@link #SCROLLBAR_POSITION_RIGHT}.
4114     *
4115     * @param position Where the vertical scroll bar should be positioned.
4116     */
4117    public void setVerticalScrollbarPosition(int position) {
4118        if (mVerticalScrollbarPosition != position) {
4119            mVerticalScrollbarPosition = position;
4120            computeOpaqueFlags();
4121            resolvePadding();
4122        }
4123    }
4124
4125    /**
4126     * @return The position where the vertical scroll bar will show, if applicable.
4127     * @see #setVerticalScrollbarPosition(int)
4128     */
4129    public int getVerticalScrollbarPosition() {
4130        return mVerticalScrollbarPosition;
4131    }
4132
4133    ListenerInfo getListenerInfo() {
4134        if (mListenerInfo != null) {
4135            return mListenerInfo;
4136        }
4137        mListenerInfo = new ListenerInfo();
4138        return mListenerInfo;
4139    }
4140
4141    /**
4142     * Register a callback to be invoked when focus of this view changed.
4143     *
4144     * @param l The callback that will run.
4145     */
4146    public void setOnFocusChangeListener(OnFocusChangeListener l) {
4147        getListenerInfo().mOnFocusChangeListener = l;
4148    }
4149
4150    /**
4151     * Add a listener that will be called when the bounds of the view change due to
4152     * layout processing.
4153     *
4154     * @param listener The listener that will be called when layout bounds change.
4155     */
4156    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
4157        ListenerInfo li = getListenerInfo();
4158        if (li.mOnLayoutChangeListeners == null) {
4159            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
4160        }
4161        if (!li.mOnLayoutChangeListeners.contains(listener)) {
4162            li.mOnLayoutChangeListeners.add(listener);
4163        }
4164    }
4165
4166    /**
4167     * Remove a listener for layout changes.
4168     *
4169     * @param listener The listener for layout bounds change.
4170     */
4171    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
4172        ListenerInfo li = mListenerInfo;
4173        if (li == null || li.mOnLayoutChangeListeners == null) {
4174            return;
4175        }
4176        li.mOnLayoutChangeListeners.remove(listener);
4177    }
4178
4179    /**
4180     * Add a listener for attach state changes.
4181     *
4182     * This listener will be called whenever this view is attached or detached
4183     * from a window. Remove the listener using
4184     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
4185     *
4186     * @param listener Listener to attach
4187     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
4188     */
4189    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4190        ListenerInfo li = getListenerInfo();
4191        if (li.mOnAttachStateChangeListeners == null) {
4192            li.mOnAttachStateChangeListeners
4193                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
4194        }
4195        li.mOnAttachStateChangeListeners.add(listener);
4196    }
4197
4198    /**
4199     * Remove a listener for attach state changes. The listener will receive no further
4200     * notification of window attach/detach events.
4201     *
4202     * @param listener Listener to remove
4203     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
4204     */
4205    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4206        ListenerInfo li = mListenerInfo;
4207        if (li == null || li.mOnAttachStateChangeListeners == null) {
4208            return;
4209        }
4210        li.mOnAttachStateChangeListeners.remove(listener);
4211    }
4212
4213    /**
4214     * Returns the focus-change callback registered for this view.
4215     *
4216     * @return The callback, or null if one is not registered.
4217     */
4218    public OnFocusChangeListener getOnFocusChangeListener() {
4219        ListenerInfo li = mListenerInfo;
4220        return li != null ? li.mOnFocusChangeListener : null;
4221    }
4222
4223    /**
4224     * Register a callback to be invoked when this view is clicked. If this view is not
4225     * clickable, it becomes clickable.
4226     *
4227     * @param l The callback that will run
4228     *
4229     * @see #setClickable(boolean)
4230     */
4231    public void setOnClickListener(OnClickListener l) {
4232        if (!isClickable()) {
4233            setClickable(true);
4234        }
4235        getListenerInfo().mOnClickListener = l;
4236    }
4237
4238    /**
4239     * Return whether this view has an attached OnClickListener.  Returns
4240     * true if there is a listener, false if there is none.
4241     */
4242    public boolean hasOnClickListeners() {
4243        ListenerInfo li = mListenerInfo;
4244        return (li != null && li.mOnClickListener != null);
4245    }
4246
4247    /**
4248     * Register a callback to be invoked when this view is clicked and held. If this view is not
4249     * long clickable, it becomes long clickable.
4250     *
4251     * @param l The callback that will run
4252     *
4253     * @see #setLongClickable(boolean)
4254     */
4255    public void setOnLongClickListener(OnLongClickListener l) {
4256        if (!isLongClickable()) {
4257            setLongClickable(true);
4258        }
4259        getListenerInfo().mOnLongClickListener = l;
4260    }
4261
4262    /**
4263     * Register a callback to be invoked when the context menu for this view is
4264     * being built. If this view is not long clickable, it becomes long clickable.
4265     *
4266     * @param l The callback that will run
4267     *
4268     */
4269    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
4270        if (!isLongClickable()) {
4271            setLongClickable(true);
4272        }
4273        getListenerInfo().mOnCreateContextMenuListener = l;
4274    }
4275
4276    /**
4277     * Call this view's OnClickListener, if it is defined.  Performs all normal
4278     * actions associated with clicking: reporting accessibility event, playing
4279     * a sound, etc.
4280     *
4281     * @return True there was an assigned OnClickListener that was called, false
4282     *         otherwise is returned.
4283     */
4284    public boolean performClick() {
4285        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
4286
4287        ListenerInfo li = mListenerInfo;
4288        if (li != null && li.mOnClickListener != null) {
4289            playSoundEffect(SoundEffectConstants.CLICK);
4290            li.mOnClickListener.onClick(this);
4291            return true;
4292        }
4293
4294        return false;
4295    }
4296
4297    /**
4298     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
4299     * this only calls the listener, and does not do any associated clicking
4300     * actions like reporting an accessibility event.
4301     *
4302     * @return True there was an assigned OnClickListener that was called, false
4303     *         otherwise is returned.
4304     */
4305    public boolean callOnClick() {
4306        ListenerInfo li = mListenerInfo;
4307        if (li != null && li.mOnClickListener != null) {
4308            li.mOnClickListener.onClick(this);
4309            return true;
4310        }
4311        return false;
4312    }
4313
4314    /**
4315     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
4316     * OnLongClickListener did not consume the event.
4317     *
4318     * @return True if one of the above receivers consumed the event, false otherwise.
4319     */
4320    public boolean performLongClick() {
4321        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
4322
4323        boolean handled = false;
4324        ListenerInfo li = mListenerInfo;
4325        if (li != null && li.mOnLongClickListener != null) {
4326            handled = li.mOnLongClickListener.onLongClick(View.this);
4327        }
4328        if (!handled) {
4329            handled = showContextMenu();
4330        }
4331        if (handled) {
4332            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
4333        }
4334        return handled;
4335    }
4336
4337    /**
4338     * Performs button-related actions during a touch down event.
4339     *
4340     * @param event The event.
4341     * @return True if the down was consumed.
4342     *
4343     * @hide
4344     */
4345    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
4346        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
4347            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
4348                return true;
4349            }
4350        }
4351        return false;
4352    }
4353
4354    /**
4355     * Bring up the context menu for this view.
4356     *
4357     * @return Whether a context menu was displayed.
4358     */
4359    public boolean showContextMenu() {
4360        return getParent().showContextMenuForChild(this);
4361    }
4362
4363    /**
4364     * Bring up the context menu for this view, referring to the item under the specified point.
4365     *
4366     * @param x The referenced x coordinate.
4367     * @param y The referenced y coordinate.
4368     * @param metaState The keyboard modifiers that were pressed.
4369     * @return Whether a context menu was displayed.
4370     *
4371     * @hide
4372     */
4373    public boolean showContextMenu(float x, float y, int metaState) {
4374        return showContextMenu();
4375    }
4376
4377    /**
4378     * Start an action mode.
4379     *
4380     * @param callback Callback that will control the lifecycle of the action mode
4381     * @return The new action mode if it is started, null otherwise
4382     *
4383     * @see ActionMode
4384     */
4385    public ActionMode startActionMode(ActionMode.Callback callback) {
4386        ViewParent parent = getParent();
4387        if (parent == null) return null;
4388        return parent.startActionModeForChild(this, callback);
4389    }
4390
4391    /**
4392     * Register a callback to be invoked when a hardware key is pressed in this view.
4393     * Key presses in software input methods will generally not trigger the methods of
4394     * this listener.
4395     * @param l the key listener to attach to this view
4396     */
4397    public void setOnKeyListener(OnKeyListener l) {
4398        getListenerInfo().mOnKeyListener = l;
4399    }
4400
4401    /**
4402     * Register a callback to be invoked when a touch event is sent to this view.
4403     * @param l the touch listener to attach to this view
4404     */
4405    public void setOnTouchListener(OnTouchListener l) {
4406        getListenerInfo().mOnTouchListener = l;
4407    }
4408
4409    /**
4410     * Register a callback to be invoked when a generic motion event is sent to this view.
4411     * @param l the generic motion listener to attach to this view
4412     */
4413    public void setOnGenericMotionListener(OnGenericMotionListener l) {
4414        getListenerInfo().mOnGenericMotionListener = l;
4415    }
4416
4417    /**
4418     * Register a callback to be invoked when a hover event is sent to this view.
4419     * @param l the hover listener to attach to this view
4420     */
4421    public void setOnHoverListener(OnHoverListener l) {
4422        getListenerInfo().mOnHoverListener = l;
4423    }
4424
4425    /**
4426     * Register a drag event listener callback object for this View. The parameter is
4427     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
4428     * View, the system calls the
4429     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
4430     * @param l An implementation of {@link android.view.View.OnDragListener}.
4431     */
4432    public void setOnDragListener(OnDragListener l) {
4433        getListenerInfo().mOnDragListener = l;
4434    }
4435
4436    /**
4437     * Give this view focus. This will cause
4438     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
4439     *
4440     * Note: this does not check whether this {@link View} should get focus, it just
4441     * gives it focus no matter what.  It should only be called internally by framework
4442     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
4443     *
4444     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
4445     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
4446     *        focus moved when requestFocus() is called. It may not always
4447     *        apply, in which case use the default View.FOCUS_DOWN.
4448     * @param previouslyFocusedRect The rectangle of the view that had focus
4449     *        prior in this View's coordinate system.
4450     */
4451    void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
4452        if (DBG) {
4453            System.out.println(this + " requestFocus()");
4454        }
4455
4456        if ((mPrivateFlags & PFLAG_FOCUSED) == 0) {
4457            mPrivateFlags |= PFLAG_FOCUSED;
4458
4459            View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null;
4460
4461            if (mParent != null) {
4462                mParent.requestChildFocus(this, this);
4463            }
4464
4465            if (mAttachInfo != null) {
4466                mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this);
4467            }
4468
4469            onFocusChanged(true, direction, previouslyFocusedRect);
4470            refreshDrawableState();
4471        }
4472    }
4473
4474    /**
4475     * Request that a rectangle of this view be visible on the screen,
4476     * scrolling if necessary just enough.
4477     *
4478     * <p>A View should call this if it maintains some notion of which part
4479     * of its content is interesting.  For example, a text editing view
4480     * should call this when its cursor moves.
4481     *
4482     * @param rectangle The rectangle.
4483     * @return Whether any parent scrolled.
4484     */
4485    public boolean requestRectangleOnScreen(Rect rectangle) {
4486        return requestRectangleOnScreen(rectangle, false);
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     * <p>When <code>immediate</code> is set to true, scrolling will not be
4498     * animated.
4499     *
4500     * @param rectangle The rectangle.
4501     * @param immediate True to forbid animated scrolling, false otherwise
4502     * @return Whether any parent scrolled.
4503     */
4504    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
4505        if (mParent == null) {
4506            return false;
4507        }
4508
4509        View child = this;
4510
4511        RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF();
4512        position.set(rectangle);
4513
4514        ViewParent parent = mParent;
4515        boolean scrolled = false;
4516        while (parent != null) {
4517            rectangle.set((int) position.left, (int) position.top,
4518                    (int) position.right, (int) position.bottom);
4519
4520            scrolled |= parent.requestChildRectangleOnScreen(child,
4521                    rectangle, immediate);
4522
4523            if (!child.hasIdentityMatrix()) {
4524                child.getMatrix().mapRect(position);
4525            }
4526
4527            position.offset(child.mLeft, child.mTop);
4528
4529            if (!(parent instanceof View)) {
4530                break;
4531            }
4532
4533            View parentView = (View) parent;
4534
4535            position.offset(-parentView.getScrollX(), -parentView.getScrollY());
4536
4537            child = parentView;
4538            parent = child.getParent();
4539        }
4540
4541        return scrolled;
4542    }
4543
4544    /**
4545     * Called when this view wants to give up focus. If focus is cleared
4546     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
4547     * <p>
4548     * <strong>Note:</strong> When a View clears focus the framework is trying
4549     * to give focus to the first focusable View from the top. Hence, if this
4550     * View is the first from the top that can take focus, then all callbacks
4551     * related to clearing focus will be invoked after wich the framework will
4552     * give focus to this view.
4553     * </p>
4554     */
4555    public void clearFocus() {
4556        if (DBG) {
4557            System.out.println(this + " clearFocus()");
4558        }
4559
4560        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
4561            mPrivateFlags &= ~PFLAG_FOCUSED;
4562
4563            if (mParent != null) {
4564                mParent.clearChildFocus(this);
4565            }
4566
4567            onFocusChanged(false, 0, null);
4568
4569            refreshDrawableState();
4570
4571            if (!rootViewRequestFocus()) {
4572                notifyGlobalFocusCleared(this);
4573            }
4574        }
4575    }
4576
4577    void notifyGlobalFocusCleared(View oldFocus) {
4578        if (oldFocus != null && mAttachInfo != null) {
4579            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
4580        }
4581    }
4582
4583    boolean rootViewRequestFocus() {
4584        final View root = getRootView();
4585        return root != null && root.requestFocus();
4586    }
4587
4588    /**
4589     * Called internally by the view system when a new view is getting focus.
4590     * This is what clears the old focus.
4591     */
4592    void unFocus() {
4593        if (DBG) {
4594            System.out.println(this + " unFocus()");
4595        }
4596
4597        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
4598            mPrivateFlags &= ~PFLAG_FOCUSED;
4599
4600            onFocusChanged(false, 0, null);
4601            refreshDrawableState();
4602        }
4603    }
4604
4605    /**
4606     * Returns true if this view has focus iteself, or is the ancestor of the
4607     * view that has focus.
4608     *
4609     * @return True if this view has or contains focus, false otherwise.
4610     */
4611    @ViewDebug.ExportedProperty(category = "focus")
4612    public boolean hasFocus() {
4613        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
4614    }
4615
4616    /**
4617     * Returns true if this view is focusable or if it contains a reachable View
4618     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
4619     * is a View whose parents do not block descendants focus.
4620     *
4621     * Only {@link #VISIBLE} views are considered focusable.
4622     *
4623     * @return True if the view is focusable or if the view contains a focusable
4624     *         View, false otherwise.
4625     *
4626     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
4627     */
4628    public boolean hasFocusable() {
4629        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
4630    }
4631
4632    /**
4633     * Called by the view system when the focus state of this view changes.
4634     * When the focus change event is caused by directional navigation, direction
4635     * and previouslyFocusedRect provide insight into where the focus is coming from.
4636     * When overriding, be sure to call up through to the super class so that
4637     * the standard focus handling will occur.
4638     *
4639     * @param gainFocus True if the View has focus; false otherwise.
4640     * @param direction The direction focus has moved when requestFocus()
4641     *                  is called to give this view focus. Values are
4642     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
4643     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
4644     *                  It may not always apply, in which case use the default.
4645     * @param previouslyFocusedRect The rectangle, in this view's coordinate
4646     *        system, of the previously focused view.  If applicable, this will be
4647     *        passed in as finer grained information about where the focus is coming
4648     *        from (in addition to direction).  Will be <code>null</code> otherwise.
4649     */
4650    protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
4651        if (gainFocus) {
4652            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
4653        } else {
4654            notifyViewAccessibilityStateChangedIfNeeded();
4655        }
4656
4657        InputMethodManager imm = InputMethodManager.peekInstance();
4658        if (!gainFocus) {
4659            if (isPressed()) {
4660                setPressed(false);
4661            }
4662            if (imm != null && mAttachInfo != null
4663                    && mAttachInfo.mHasWindowFocus) {
4664                imm.focusOut(this);
4665            }
4666            onFocusLost();
4667        } else if (imm != null && mAttachInfo != null
4668                && mAttachInfo.mHasWindowFocus) {
4669            imm.focusIn(this);
4670        }
4671
4672        invalidate(true);
4673        ListenerInfo li = mListenerInfo;
4674        if (li != null && li.mOnFocusChangeListener != null) {
4675            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
4676        }
4677
4678        if (mAttachInfo != null) {
4679            mAttachInfo.mKeyDispatchState.reset(this);
4680        }
4681    }
4682
4683    /**
4684     * Sends an accessibility event of the given type. If accessibility is
4685     * not enabled this method has no effect. The default implementation calls
4686     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
4687     * to populate information about the event source (this View), then calls
4688     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
4689     * populate the text content of the event source including its descendants,
4690     * and last calls
4691     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
4692     * on its parent to resuest sending of the event to interested parties.
4693     * <p>
4694     * If an {@link AccessibilityDelegate} has been specified via calling
4695     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4696     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
4697     * responsible for handling this call.
4698     * </p>
4699     *
4700     * @param eventType The type of the event to send, as defined by several types from
4701     * {@link android.view.accessibility.AccessibilityEvent}, such as
4702     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
4703     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
4704     *
4705     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4706     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4707     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
4708     * @see AccessibilityDelegate
4709     */
4710    public void sendAccessibilityEvent(int eventType) {
4711        // Excluded views do not send accessibility events.
4712        if (!includeForAccessibility()) {
4713            return;
4714        }
4715        if (mAccessibilityDelegate != null) {
4716            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
4717        } else {
4718            sendAccessibilityEventInternal(eventType);
4719        }
4720    }
4721
4722    /**
4723     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
4724     * {@link AccessibilityEvent} to make an announcement which is related to some
4725     * sort of a context change for which none of the events representing UI transitions
4726     * is a good fit. For example, announcing a new page in a book. If accessibility
4727     * is not enabled this method does nothing.
4728     *
4729     * @param text The announcement text.
4730     */
4731    public void announceForAccessibility(CharSequence text) {
4732        if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) {
4733            AccessibilityEvent event = AccessibilityEvent.obtain(
4734                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
4735            onInitializeAccessibilityEvent(event);
4736            event.getText().add(text);
4737            event.setContentDescription(null);
4738            mParent.requestSendAccessibilityEvent(this, event);
4739        }
4740    }
4741
4742    /**
4743     * @see #sendAccessibilityEvent(int)
4744     *
4745     * Note: Called from the default {@link AccessibilityDelegate}.
4746     */
4747    void sendAccessibilityEventInternal(int eventType) {
4748        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4749            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
4750        }
4751    }
4752
4753    /**
4754     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
4755     * takes as an argument an empty {@link AccessibilityEvent} and does not
4756     * perform a check whether accessibility is enabled.
4757     * <p>
4758     * If an {@link AccessibilityDelegate} has been specified via calling
4759     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4760     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
4761     * is responsible for handling this call.
4762     * </p>
4763     *
4764     * @param event The event to send.
4765     *
4766     * @see #sendAccessibilityEvent(int)
4767     */
4768    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
4769        if (mAccessibilityDelegate != null) {
4770            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
4771        } else {
4772            sendAccessibilityEventUncheckedInternal(event);
4773        }
4774    }
4775
4776    /**
4777     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
4778     *
4779     * Note: Called from the default {@link AccessibilityDelegate}.
4780     */
4781    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
4782        if (!isShown()) {
4783            return;
4784        }
4785        onInitializeAccessibilityEvent(event);
4786        // Only a subset of accessibility events populates text content.
4787        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
4788            dispatchPopulateAccessibilityEvent(event);
4789        }
4790        // In the beginning we called #isShown(), so we know that getParent() is not null.
4791        getParent().requestSendAccessibilityEvent(this, event);
4792    }
4793
4794    /**
4795     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
4796     * to its children for adding their text content to the event. Note that the
4797     * event text is populated in a separate dispatch path since we add to the
4798     * event not only the text of the source but also the text of all its descendants.
4799     * A typical implementation will call
4800     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
4801     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4802     * on each child. Override this method if custom population of the event text
4803     * content is required.
4804     * <p>
4805     * If an {@link AccessibilityDelegate} has been specified via calling
4806     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4807     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
4808     * is responsible for handling this call.
4809     * </p>
4810     * <p>
4811     * <em>Note:</em> Accessibility events of certain types are not dispatched for
4812     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
4813     * </p>
4814     *
4815     * @param event The event.
4816     *
4817     * @return True if the event population was completed.
4818     */
4819    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
4820        if (mAccessibilityDelegate != null) {
4821            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
4822        } else {
4823            return dispatchPopulateAccessibilityEventInternal(event);
4824        }
4825    }
4826
4827    /**
4828     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4829     *
4830     * Note: Called from the default {@link AccessibilityDelegate}.
4831     */
4832    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4833        onPopulateAccessibilityEvent(event);
4834        return false;
4835    }
4836
4837    /**
4838     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4839     * giving a chance to this View to populate the accessibility event with its
4840     * text content. While this method is free to modify event
4841     * attributes other than text content, doing so should normally be performed in
4842     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
4843     * <p>
4844     * Example: Adding formatted date string to an accessibility event in addition
4845     *          to the text added by the super implementation:
4846     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4847     *     super.onPopulateAccessibilityEvent(event);
4848     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
4849     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
4850     *         mCurrentDate.getTimeInMillis(), flags);
4851     *     event.getText().add(selectedDateUtterance);
4852     * }</pre>
4853     * <p>
4854     * If an {@link AccessibilityDelegate} has been specified via calling
4855     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4856     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
4857     * is responsible for handling this call.
4858     * </p>
4859     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4860     * information to the event, in case the default implementation has basic information to add.
4861     * </p>
4862     *
4863     * @param event The accessibility event which to populate.
4864     *
4865     * @see #sendAccessibilityEvent(int)
4866     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4867     */
4868    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4869        if (mAccessibilityDelegate != null) {
4870            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
4871        } else {
4872            onPopulateAccessibilityEventInternal(event);
4873        }
4874    }
4875
4876    /**
4877     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
4878     *
4879     * Note: Called from the default {@link AccessibilityDelegate}.
4880     */
4881    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4882    }
4883
4884    /**
4885     * Initializes an {@link AccessibilityEvent} with information about
4886     * this View which is the event source. In other words, the source of
4887     * an accessibility event is the view whose state change triggered firing
4888     * the event.
4889     * <p>
4890     * Example: Setting the password property of an event in addition
4891     *          to properties set by the super implementation:
4892     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4893     *     super.onInitializeAccessibilityEvent(event);
4894     *     event.setPassword(true);
4895     * }</pre>
4896     * <p>
4897     * If an {@link AccessibilityDelegate} has been specified via calling
4898     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4899     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
4900     * is responsible for handling this call.
4901     * </p>
4902     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4903     * information to the event, in case the default implementation has basic information to add.
4904     * </p>
4905     * @param event The event to initialize.
4906     *
4907     * @see #sendAccessibilityEvent(int)
4908     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4909     */
4910    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4911        if (mAccessibilityDelegate != null) {
4912            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
4913        } else {
4914            onInitializeAccessibilityEventInternal(event);
4915        }
4916    }
4917
4918    /**
4919     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4920     *
4921     * Note: Called from the default {@link AccessibilityDelegate}.
4922     */
4923    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
4924        event.setSource(this);
4925        event.setClassName(View.class.getName());
4926        event.setPackageName(getContext().getPackageName());
4927        event.setEnabled(isEnabled());
4928        event.setContentDescription(mContentDescription);
4929
4930        switch (event.getEventType()) {
4931            case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
4932                ArrayList<View> focusablesTempList = (mAttachInfo != null)
4933                        ? mAttachInfo.mTempArrayList : new ArrayList<View>();
4934                getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
4935                event.setItemCount(focusablesTempList.size());
4936                event.setCurrentItemIndex(focusablesTempList.indexOf(this));
4937                if (mAttachInfo != null) {
4938                    focusablesTempList.clear();
4939                }
4940            } break;
4941            case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: {
4942                CharSequence text = getIterableTextForAccessibility();
4943                if (text != null && text.length() > 0) {
4944                    event.setFromIndex(getAccessibilitySelectionStart());
4945                    event.setToIndex(getAccessibilitySelectionEnd());
4946                    event.setItemCount(text.length());
4947                }
4948            } break;
4949        }
4950    }
4951
4952    /**
4953     * Returns an {@link AccessibilityNodeInfo} representing this view from the
4954     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
4955     * This method is responsible for obtaining an accessibility node info from a
4956     * pool of reusable instances and calling
4957     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
4958     * initialize the former.
4959     * <p>
4960     * Note: The client is responsible for recycling the obtained instance by calling
4961     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
4962     * </p>
4963     *
4964     * @return A populated {@link AccessibilityNodeInfo}.
4965     *
4966     * @see AccessibilityNodeInfo
4967     */
4968    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
4969        if (mAccessibilityDelegate != null) {
4970            return mAccessibilityDelegate.createAccessibilityNodeInfo(this);
4971        } else {
4972            return createAccessibilityNodeInfoInternal();
4973        }
4974    }
4975
4976    /**
4977     * @see #createAccessibilityNodeInfo()
4978     */
4979    AccessibilityNodeInfo createAccessibilityNodeInfoInternal() {
4980        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
4981        if (provider != null) {
4982            return provider.createAccessibilityNodeInfo(View.NO_ID);
4983        } else {
4984            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
4985            onInitializeAccessibilityNodeInfo(info);
4986            return info;
4987        }
4988    }
4989
4990    /**
4991     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
4992     * The base implementation sets:
4993     * <ul>
4994     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
4995     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
4996     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
4997     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
4998     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
4999     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
5000     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
5001     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
5002     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
5003     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
5004     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
5005     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
5006     * </ul>
5007     * <p>
5008     * Subclasses should override this method, call the super implementation,
5009     * and set additional attributes.
5010     * </p>
5011     * <p>
5012     * If an {@link AccessibilityDelegate} has been specified via calling
5013     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5014     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
5015     * is responsible for handling this call.
5016     * </p>
5017     *
5018     * @param info The instance to initialize.
5019     */
5020    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
5021        if (mAccessibilityDelegate != null) {
5022            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
5023        } else {
5024            onInitializeAccessibilityNodeInfoInternal(info);
5025        }
5026    }
5027
5028    /**
5029     * Gets the location of this view in screen coordintates.
5030     *
5031     * @param outRect The output location
5032     */
5033    void getBoundsOnScreen(Rect outRect) {
5034        if (mAttachInfo == null) {
5035            return;
5036        }
5037
5038        RectF position = mAttachInfo.mTmpTransformRect;
5039        position.set(0, 0, mRight - mLeft, mBottom - mTop);
5040
5041        if (!hasIdentityMatrix()) {
5042            getMatrix().mapRect(position);
5043        }
5044
5045        position.offset(mLeft, mTop);
5046
5047        ViewParent parent = mParent;
5048        while (parent instanceof View) {
5049            View parentView = (View) parent;
5050
5051            position.offset(-parentView.mScrollX, -parentView.mScrollY);
5052
5053            if (!parentView.hasIdentityMatrix()) {
5054                parentView.getMatrix().mapRect(position);
5055            }
5056
5057            position.offset(parentView.mLeft, parentView.mTop);
5058
5059            parent = parentView.mParent;
5060        }
5061
5062        if (parent instanceof ViewRootImpl) {
5063            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
5064            position.offset(0, -viewRootImpl.mCurScrollY);
5065        }
5066
5067        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
5068
5069        outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f),
5070                (int) (position.right + 0.5f), (int) (position.bottom + 0.5f));
5071    }
5072
5073    /**
5074     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
5075     *
5076     * Note: Called from the default {@link AccessibilityDelegate}.
5077     */
5078    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
5079        Rect bounds = mAttachInfo.mTmpInvalRect;
5080
5081        getDrawingRect(bounds);
5082        info.setBoundsInParent(bounds);
5083
5084        getBoundsOnScreen(bounds);
5085        info.setBoundsInScreen(bounds);
5086
5087        ViewParent parent = getParentForAccessibility();
5088        if (parent instanceof View) {
5089            info.setParent((View) parent);
5090        }
5091
5092        if (mID != View.NO_ID) {
5093            View rootView = getRootView();
5094            if (rootView == null) {
5095                rootView = this;
5096            }
5097            View label = rootView.findLabelForView(this, mID);
5098            if (label != null) {
5099                info.setLabeledBy(label);
5100            }
5101
5102            if ((mAttachInfo.mAccessibilityFetchFlags
5103                    & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0
5104                    && Resources.resourceHasPackage(mID)) {
5105                try {
5106                    String viewId = getResources().getResourceName(mID);
5107                    info.setViewIdResourceName(viewId);
5108                } catch (Resources.NotFoundException nfe) {
5109                    /* ignore */
5110                }
5111            }
5112        }
5113
5114        if (mLabelForId != View.NO_ID) {
5115            View rootView = getRootView();
5116            if (rootView == null) {
5117                rootView = this;
5118            }
5119            View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId);
5120            if (labeled != null) {
5121                info.setLabelFor(labeled);
5122            }
5123        }
5124
5125        info.setVisibleToUser(isVisibleToUser());
5126
5127        info.setPackageName(mContext.getPackageName());
5128        info.setClassName(View.class.getName());
5129        info.setContentDescription(getContentDescription());
5130
5131        info.setEnabled(isEnabled());
5132        info.setClickable(isClickable());
5133        info.setFocusable(isFocusable());
5134        info.setFocused(isFocused());
5135        info.setAccessibilityFocused(isAccessibilityFocused());
5136        info.setSelected(isSelected());
5137        info.setLongClickable(isLongClickable());
5138
5139        // TODO: These make sense only if we are in an AdapterView but all
5140        // views can be selected. Maybe from accessibility perspective
5141        // we should report as selectable view in an AdapterView.
5142        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
5143        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
5144
5145        if (isFocusable()) {
5146            if (isFocused()) {
5147                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
5148            } else {
5149                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
5150            }
5151        }
5152
5153        if (!isAccessibilityFocused()) {
5154            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
5155        } else {
5156            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
5157        }
5158
5159        if (isClickable() && isEnabled()) {
5160            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
5161        }
5162
5163        if (isLongClickable() && isEnabled()) {
5164            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
5165        }
5166
5167        CharSequence text = getIterableTextForAccessibility();
5168        if (text != null && text.length() > 0) {
5169            info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd());
5170
5171            info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION);
5172            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
5173            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
5174            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
5175                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
5176                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
5177        }
5178    }
5179
5180    private View findLabelForView(View view, int labeledId) {
5181        if (mMatchLabelForPredicate == null) {
5182            mMatchLabelForPredicate = new MatchLabelForPredicate();
5183        }
5184        mMatchLabelForPredicate.mLabeledId = labeledId;
5185        return findViewByPredicateInsideOut(view, mMatchLabelForPredicate);
5186    }
5187
5188    /**
5189     * Computes whether this view is visible to the user. Such a view is
5190     * attached, visible, all its predecessors are visible, it is not clipped
5191     * entirely by its predecessors, and has an alpha greater than zero.
5192     *
5193     * @return Whether the view is visible on the screen.
5194     *
5195     * @hide
5196     */
5197    protected boolean isVisibleToUser() {
5198        return isVisibleToUser(null);
5199    }
5200
5201    /**
5202     * Computes whether the given portion of this view is visible to the user.
5203     * Such a view is attached, visible, all its predecessors are visible,
5204     * has an alpha greater than zero, and the specified portion is not
5205     * clipped entirely by its predecessors.
5206     *
5207     * @param boundInView the portion of the view to test; coordinates should be relative; may be
5208     *                    <code>null</code>, and the entire view will be tested in this case.
5209     *                    When <code>true</code> is returned by the function, the actual visible
5210     *                    region will be stored in this parameter; that is, if boundInView is fully
5211     *                    contained within the view, no modification will be made, otherwise regions
5212     *                    outside of the visible area of the view will be clipped.
5213     *
5214     * @return Whether the specified portion of the view is visible on the screen.
5215     *
5216     * @hide
5217     */
5218    protected boolean isVisibleToUser(Rect boundInView) {
5219        if (mAttachInfo != null) {
5220            // Attached to invisible window means this view is not visible.
5221            if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
5222                return false;
5223            }
5224            // An invisible predecessor or one with alpha zero means
5225            // that this view is not visible to the user.
5226            Object current = this;
5227            while (current instanceof View) {
5228                View view = (View) current;
5229                // We have attach info so this view is attached and there is no
5230                // need to check whether we reach to ViewRootImpl on the way up.
5231                if (view.getAlpha() <= 0 || view.getVisibility() != VISIBLE) {
5232                    return false;
5233                }
5234                current = view.mParent;
5235            }
5236            // Check if the view is entirely covered by its predecessors.
5237            Rect visibleRect = mAttachInfo.mTmpInvalRect;
5238            Point offset = mAttachInfo.mPoint;
5239            if (!getGlobalVisibleRect(visibleRect, offset)) {
5240                return false;
5241            }
5242            // Check if the visible portion intersects the rectangle of interest.
5243            if (boundInView != null) {
5244                visibleRect.offset(-offset.x, -offset.y);
5245                return boundInView.intersect(visibleRect);
5246            }
5247            return true;
5248        }
5249        return false;
5250    }
5251
5252    /**
5253     * Returns the delegate for implementing accessibility support via
5254     * composition. For more details see {@link AccessibilityDelegate}.
5255     *
5256     * @return The delegate, or null if none set.
5257     *
5258     * @hide
5259     */
5260    public AccessibilityDelegate getAccessibilityDelegate() {
5261        return mAccessibilityDelegate;
5262    }
5263
5264    /**
5265     * Sets a delegate for implementing accessibility support via composition as
5266     * opposed to inheritance. The delegate's primary use is for implementing
5267     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
5268     *
5269     * @param delegate The delegate instance.
5270     *
5271     * @see AccessibilityDelegate
5272     */
5273    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
5274        mAccessibilityDelegate = delegate;
5275    }
5276
5277    /**
5278     * Gets the provider for managing a virtual view hierarchy rooted at this View
5279     * and reported to {@link android.accessibilityservice.AccessibilityService}s
5280     * that explore the window content.
5281     * <p>
5282     * If this method returns an instance, this instance is responsible for managing
5283     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
5284     * View including the one representing the View itself. Similarly the returned
5285     * instance is responsible for performing accessibility actions on any virtual
5286     * view or the root view itself.
5287     * </p>
5288     * <p>
5289     * If an {@link AccessibilityDelegate} has been specified via calling
5290     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5291     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
5292     * is responsible for handling this call.
5293     * </p>
5294     *
5295     * @return The provider.
5296     *
5297     * @see AccessibilityNodeProvider
5298     */
5299    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
5300        if (mAccessibilityDelegate != null) {
5301            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
5302        } else {
5303            return null;
5304        }
5305    }
5306
5307    /**
5308     * Gets the unique identifier of this view on the screen for accessibility purposes.
5309     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
5310     *
5311     * @return The view accessibility id.
5312     *
5313     * @hide
5314     */
5315    public int getAccessibilityViewId() {
5316        if (mAccessibilityViewId == NO_ID) {
5317            mAccessibilityViewId = sNextAccessibilityViewId++;
5318        }
5319        return mAccessibilityViewId;
5320    }
5321
5322    /**
5323     * Gets the unique identifier of the window in which this View reseides.
5324     *
5325     * @return The window accessibility id.
5326     *
5327     * @hide
5328     */
5329    public int getAccessibilityWindowId() {
5330        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID;
5331    }
5332
5333    /**
5334     * Gets the {@link View} description. It briefly describes the view and is
5335     * primarily used for accessibility support. Set this property to enable
5336     * better accessibility support for your application. This is especially
5337     * true for views that do not have textual representation (For example,
5338     * ImageButton).
5339     *
5340     * @return The content description.
5341     *
5342     * @attr ref android.R.styleable#View_contentDescription
5343     */
5344    @ViewDebug.ExportedProperty(category = "accessibility")
5345    public CharSequence getContentDescription() {
5346        return mContentDescription;
5347    }
5348
5349    /**
5350     * Sets the {@link View} description. It briefly describes the view and is
5351     * primarily used for accessibility support. Set this property to enable
5352     * better accessibility support for your application. This is especially
5353     * true for views that do not have textual representation (For example,
5354     * ImageButton).
5355     *
5356     * @param contentDescription The content description.
5357     *
5358     * @attr ref android.R.styleable#View_contentDescription
5359     */
5360    @RemotableViewMethod
5361    public void setContentDescription(CharSequence contentDescription) {
5362        if (mContentDescription == null) {
5363            if (contentDescription == null) {
5364                return;
5365            }
5366        } else if (mContentDescription.equals(contentDescription)) {
5367            return;
5368        }
5369        mContentDescription = contentDescription;
5370        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
5371        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
5372            setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
5373            notifySubtreeAccessibilityStateChangedIfNeeded();
5374        } else {
5375            notifyViewAccessibilityStateChangedIfNeeded();
5376        }
5377    }
5378
5379    /**
5380     * Gets the id of a view for which this view serves as a label for
5381     * accessibility purposes.
5382     *
5383     * @return The labeled view id.
5384     */
5385    @ViewDebug.ExportedProperty(category = "accessibility")
5386    public int getLabelFor() {
5387        return mLabelForId;
5388    }
5389
5390    /**
5391     * Sets the id of a view for which this view serves as a label for
5392     * accessibility purposes.
5393     *
5394     * @param id The labeled view id.
5395     */
5396    @RemotableViewMethod
5397    public void setLabelFor(int id) {
5398        mLabelForId = id;
5399        if (mLabelForId != View.NO_ID
5400                && mID == View.NO_ID) {
5401            mID = generateViewId();
5402        }
5403    }
5404
5405    /**
5406     * Invoked whenever this view loses focus, either by losing window focus or by losing
5407     * focus within its window. This method can be used to clear any state tied to the
5408     * focus. For instance, if a button is held pressed with the trackball and the window
5409     * loses focus, this method can be used to cancel the press.
5410     *
5411     * Subclasses of View overriding this method should always call super.onFocusLost().
5412     *
5413     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
5414     * @see #onWindowFocusChanged(boolean)
5415     *
5416     * @hide pending API council approval
5417     */
5418    protected void onFocusLost() {
5419        resetPressedState();
5420    }
5421
5422    private void resetPressedState() {
5423        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
5424            return;
5425        }
5426
5427        if (isPressed()) {
5428            setPressed(false);
5429
5430            if (!mHasPerformedLongPress) {
5431                removeLongPressCallback();
5432            }
5433        }
5434    }
5435
5436    /**
5437     * Returns true if this view has focus
5438     *
5439     * @return True if this view has focus, false otherwise.
5440     */
5441    @ViewDebug.ExportedProperty(category = "focus")
5442    public boolean isFocused() {
5443        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
5444    }
5445
5446    /**
5447     * Find the view in the hierarchy rooted at this view that currently has
5448     * focus.
5449     *
5450     * @return The view that currently has focus, or null if no focused view can
5451     *         be found.
5452     */
5453    public View findFocus() {
5454        return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
5455    }
5456
5457    /**
5458     * Indicates whether this view is one of the set of scrollable containers in
5459     * its window.
5460     *
5461     * @return whether this view is one of the set of scrollable containers in
5462     * its window
5463     *
5464     * @attr ref android.R.styleable#View_isScrollContainer
5465     */
5466    public boolean isScrollContainer() {
5467        return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0;
5468    }
5469
5470    /**
5471     * Change whether this view is one of the set of scrollable containers in
5472     * its window.  This will be used to determine whether the window can
5473     * resize or must pan when a soft input area is open -- scrollable
5474     * containers allow the window to use resize mode since the container
5475     * will appropriately shrink.
5476     *
5477     * @attr ref android.R.styleable#View_isScrollContainer
5478     */
5479    public void setScrollContainer(boolean isScrollContainer) {
5480        if (isScrollContainer) {
5481            if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) {
5482                mAttachInfo.mScrollContainers.add(this);
5483                mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
5484            }
5485            mPrivateFlags |= PFLAG_SCROLL_CONTAINER;
5486        } else {
5487            if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
5488                mAttachInfo.mScrollContainers.remove(this);
5489            }
5490            mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED);
5491        }
5492    }
5493
5494    /**
5495     * Returns the quality of the drawing cache.
5496     *
5497     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5498     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5499     *
5500     * @see #setDrawingCacheQuality(int)
5501     * @see #setDrawingCacheEnabled(boolean)
5502     * @see #isDrawingCacheEnabled()
5503     *
5504     * @attr ref android.R.styleable#View_drawingCacheQuality
5505     */
5506    public int getDrawingCacheQuality() {
5507        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
5508    }
5509
5510    /**
5511     * Set the drawing cache quality of this view. This value is used only when the
5512     * drawing cache is enabled
5513     *
5514     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5515     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5516     *
5517     * @see #getDrawingCacheQuality()
5518     * @see #setDrawingCacheEnabled(boolean)
5519     * @see #isDrawingCacheEnabled()
5520     *
5521     * @attr ref android.R.styleable#View_drawingCacheQuality
5522     */
5523    public void setDrawingCacheQuality(int quality) {
5524        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
5525    }
5526
5527    /**
5528     * Returns whether the screen should remain on, corresponding to the current
5529     * value of {@link #KEEP_SCREEN_ON}.
5530     *
5531     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
5532     *
5533     * @see #setKeepScreenOn(boolean)
5534     *
5535     * @attr ref android.R.styleable#View_keepScreenOn
5536     */
5537    public boolean getKeepScreenOn() {
5538        return (mViewFlags & KEEP_SCREEN_ON) != 0;
5539    }
5540
5541    /**
5542     * Controls whether the screen should remain on, modifying the
5543     * value of {@link #KEEP_SCREEN_ON}.
5544     *
5545     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
5546     *
5547     * @see #getKeepScreenOn()
5548     *
5549     * @attr ref android.R.styleable#View_keepScreenOn
5550     */
5551    public void setKeepScreenOn(boolean keepScreenOn) {
5552        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
5553    }
5554
5555    /**
5556     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5557     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5558     *
5559     * @attr ref android.R.styleable#View_nextFocusLeft
5560     */
5561    public int getNextFocusLeftId() {
5562        return mNextFocusLeftId;
5563    }
5564
5565    /**
5566     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5567     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
5568     * decide automatically.
5569     *
5570     * @attr ref android.R.styleable#View_nextFocusLeft
5571     */
5572    public void setNextFocusLeftId(int nextFocusLeftId) {
5573        mNextFocusLeftId = nextFocusLeftId;
5574    }
5575
5576    /**
5577     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5578     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5579     *
5580     * @attr ref android.R.styleable#View_nextFocusRight
5581     */
5582    public int getNextFocusRightId() {
5583        return mNextFocusRightId;
5584    }
5585
5586    /**
5587     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5588     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
5589     * decide automatically.
5590     *
5591     * @attr ref android.R.styleable#View_nextFocusRight
5592     */
5593    public void setNextFocusRightId(int nextFocusRightId) {
5594        mNextFocusRightId = nextFocusRightId;
5595    }
5596
5597    /**
5598     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5599     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5600     *
5601     * @attr ref android.R.styleable#View_nextFocusUp
5602     */
5603    public int getNextFocusUpId() {
5604        return mNextFocusUpId;
5605    }
5606
5607    /**
5608     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5609     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
5610     * decide automatically.
5611     *
5612     * @attr ref android.R.styleable#View_nextFocusUp
5613     */
5614    public void setNextFocusUpId(int nextFocusUpId) {
5615        mNextFocusUpId = nextFocusUpId;
5616    }
5617
5618    /**
5619     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5620     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5621     *
5622     * @attr ref android.R.styleable#View_nextFocusDown
5623     */
5624    public int getNextFocusDownId() {
5625        return mNextFocusDownId;
5626    }
5627
5628    /**
5629     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5630     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
5631     * decide automatically.
5632     *
5633     * @attr ref android.R.styleable#View_nextFocusDown
5634     */
5635    public void setNextFocusDownId(int nextFocusDownId) {
5636        mNextFocusDownId = nextFocusDownId;
5637    }
5638
5639    /**
5640     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5641     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5642     *
5643     * @attr ref android.R.styleable#View_nextFocusForward
5644     */
5645    public int getNextFocusForwardId() {
5646        return mNextFocusForwardId;
5647    }
5648
5649    /**
5650     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5651     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
5652     * decide automatically.
5653     *
5654     * @attr ref android.R.styleable#View_nextFocusForward
5655     */
5656    public void setNextFocusForwardId(int nextFocusForwardId) {
5657        mNextFocusForwardId = nextFocusForwardId;
5658    }
5659
5660    /**
5661     * Returns the visibility of this view and all of its ancestors
5662     *
5663     * @return True if this view and all of its ancestors are {@link #VISIBLE}
5664     */
5665    public boolean isShown() {
5666        View current = this;
5667        //noinspection ConstantConditions
5668        do {
5669            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
5670                return false;
5671            }
5672            ViewParent parent = current.mParent;
5673            if (parent == null) {
5674                return false; // We are not attached to the view root
5675            }
5676            if (!(parent instanceof View)) {
5677                return true;
5678            }
5679            current = (View) parent;
5680        } while (current != null);
5681
5682        return false;
5683    }
5684
5685    /**
5686     * Called by the view hierarchy when the content insets for a window have
5687     * changed, to allow it to adjust its content to fit within those windows.
5688     * The content insets tell you the space that the status bar, input method,
5689     * and other system windows infringe on the application's window.
5690     *
5691     * <p>You do not normally need to deal with this function, since the default
5692     * window decoration given to applications takes care of applying it to the
5693     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
5694     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
5695     * and your content can be placed under those system elements.  You can then
5696     * use this method within your view hierarchy if you have parts of your UI
5697     * which you would like to ensure are not being covered.
5698     *
5699     * <p>The default implementation of this method simply applies the content
5700     * insets to the view's padding, consuming that content (modifying the
5701     * insets to be 0), and returning true.  This behavior is off by default, but can
5702     * be enabled through {@link #setFitsSystemWindows(boolean)}.
5703     *
5704     * <p>This function's traversal down the hierarchy is depth-first.  The same content
5705     * insets object is propagated down the hierarchy, so any changes made to it will
5706     * be seen by all following views (including potentially ones above in
5707     * the hierarchy since this is a depth-first traversal).  The first view
5708     * that returns true will abort the entire traversal.
5709     *
5710     * <p>The default implementation works well for a situation where it is
5711     * used with a container that covers the entire window, allowing it to
5712     * apply the appropriate insets to its content on all edges.  If you need
5713     * a more complicated layout (such as two different views fitting system
5714     * windows, one on the top of the window, and one on the bottom),
5715     * you can override the method and handle the insets however you would like.
5716     * Note that the insets provided by the framework are always relative to the
5717     * far edges of the window, not accounting for the location of the called view
5718     * within that window.  (In fact when this method is called you do not yet know
5719     * where the layout will place the view, as it is done before layout happens.)
5720     *
5721     * <p>Note: unlike many View methods, there is no dispatch phase to this
5722     * call.  If you are overriding it in a ViewGroup and want to allow the
5723     * call to continue to your children, you must be sure to call the super
5724     * implementation.
5725     *
5726     * <p>Here is a sample layout that makes use of fitting system windows
5727     * to have controls for a video view placed inside of the window decorations
5728     * that it hides and shows.  This can be used with code like the second
5729     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
5730     *
5731     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
5732     *
5733     * @param insets Current content insets of the window.  Prior to
5734     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
5735     * the insets or else you and Android will be unhappy.
5736     *
5737     * @return {@code true} if this view applied the insets and it should not
5738     * continue propagating further down the hierarchy, {@code false} otherwise.
5739     * @see #getFitsSystemWindows()
5740     * @see #setFitsSystemWindows(boolean)
5741     * @see #setSystemUiVisibility(int)
5742     */
5743    protected boolean fitSystemWindows(Rect insets) {
5744        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
5745            mUserPaddingStart = UNDEFINED_PADDING;
5746            mUserPaddingEnd = UNDEFINED_PADDING;
5747            Rect localInsets = sThreadLocal.get();
5748            if (localInsets == null) {
5749                localInsets = new Rect();
5750                sThreadLocal.set(localInsets);
5751            }
5752            boolean res = computeFitSystemWindows(insets, localInsets);
5753            internalSetPadding(localInsets.left, localInsets.top,
5754                    localInsets.right, localInsets.bottom);
5755            return res;
5756        }
5757        return false;
5758    }
5759
5760    /**
5761     * @hide Compute the insets that should be consumed by this view and the ones
5762     * that should propagate to those under it.
5763     */
5764    protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) {
5765        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
5766                || mAttachInfo == null
5767                || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0
5768                        && !mAttachInfo.mOverscanRequested)) {
5769            outLocalInsets.set(inoutInsets);
5770            inoutInsets.set(0, 0, 0, 0);
5771            return true;
5772        } else {
5773            // The application wants to take care of fitting system window for
5774            // the content...  however we still need to take care of any overscan here.
5775            final Rect overscan = mAttachInfo.mOverscanInsets;
5776            outLocalInsets.set(overscan);
5777            inoutInsets.left -= overscan.left;
5778            inoutInsets.top -= overscan.top;
5779            inoutInsets.right -= overscan.right;
5780            inoutInsets.bottom -= overscan.bottom;
5781            return false;
5782        }
5783    }
5784
5785    /**
5786     * Sets whether or not this view should account for system screen decorations
5787     * such as the status bar and inset its content; that is, controlling whether
5788     * the default implementation of {@link #fitSystemWindows(Rect)} will be
5789     * executed.  See that method for more details.
5790     *
5791     * <p>Note that if you are providing your own implementation of
5792     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
5793     * flag to true -- your implementation will be overriding the default
5794     * implementation that checks this flag.
5795     *
5796     * @param fitSystemWindows If true, then the default implementation of
5797     * {@link #fitSystemWindows(Rect)} will be executed.
5798     *
5799     * @attr ref android.R.styleable#View_fitsSystemWindows
5800     * @see #getFitsSystemWindows()
5801     * @see #fitSystemWindows(Rect)
5802     * @see #setSystemUiVisibility(int)
5803     */
5804    public void setFitsSystemWindows(boolean fitSystemWindows) {
5805        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
5806    }
5807
5808    /**
5809     * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method
5810     * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)}
5811     * will be executed.
5812     *
5813     * @return {@code true} if the default implementation of
5814     * {@link #fitSystemWindows(Rect)} will be executed.
5815     *
5816     * @attr ref android.R.styleable#View_fitsSystemWindows
5817     * @see #setFitsSystemWindows(boolean)
5818     * @see #fitSystemWindows(Rect)
5819     * @see #setSystemUiVisibility(int)
5820     */
5821    public boolean getFitsSystemWindows() {
5822        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
5823    }
5824
5825    /** @hide */
5826    public boolean fitsSystemWindows() {
5827        return getFitsSystemWindows();
5828    }
5829
5830    /**
5831     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
5832     */
5833    public void requestFitSystemWindows() {
5834        if (mParent != null) {
5835            mParent.requestFitSystemWindows();
5836        }
5837    }
5838
5839    /**
5840     * For use by PhoneWindow to make its own system window fitting optional.
5841     * @hide
5842     */
5843    public void makeOptionalFitsSystemWindows() {
5844        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
5845    }
5846
5847    /**
5848     * Returns the visibility status for this view.
5849     *
5850     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5851     * @attr ref android.R.styleable#View_visibility
5852     */
5853    @ViewDebug.ExportedProperty(mapping = {
5854        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
5855        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
5856        @ViewDebug.IntToString(from = GONE,      to = "GONE")
5857    })
5858    public int getVisibility() {
5859        return mViewFlags & VISIBILITY_MASK;
5860    }
5861
5862    /**
5863     * Set the enabled state of this view.
5864     *
5865     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5866     * @attr ref android.R.styleable#View_visibility
5867     */
5868    @RemotableViewMethod
5869    public void setVisibility(int visibility) {
5870        setFlags(visibility, VISIBILITY_MASK);
5871        if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false);
5872    }
5873
5874    /**
5875     * Returns the enabled status for this view. The interpretation of the
5876     * enabled state varies by subclass.
5877     *
5878     * @return True if this view is enabled, false otherwise.
5879     */
5880    @ViewDebug.ExportedProperty
5881    public boolean isEnabled() {
5882        return (mViewFlags & ENABLED_MASK) == ENABLED;
5883    }
5884
5885    /**
5886     * Set the enabled state of this view. The interpretation of the enabled
5887     * state varies by subclass.
5888     *
5889     * @param enabled True if this view is enabled, false otherwise.
5890     */
5891    @RemotableViewMethod
5892    public void setEnabled(boolean enabled) {
5893        if (enabled == isEnabled()) return;
5894
5895        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
5896
5897        /*
5898         * The View most likely has to change its appearance, so refresh
5899         * the drawable state.
5900         */
5901        refreshDrawableState();
5902
5903        // Invalidate too, since the default behavior for views is to be
5904        // be drawn at 50% alpha rather than to change the drawable.
5905        invalidate(true);
5906    }
5907
5908    /**
5909     * Set whether this view can receive the focus.
5910     *
5911     * Setting this to false will also ensure that this view is not focusable
5912     * in touch mode.
5913     *
5914     * @param focusable If true, this view can receive the focus.
5915     *
5916     * @see #setFocusableInTouchMode(boolean)
5917     * @attr ref android.R.styleable#View_focusable
5918     */
5919    public void setFocusable(boolean focusable) {
5920        if (!focusable) {
5921            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
5922        }
5923        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
5924    }
5925
5926    /**
5927     * Set whether this view can receive focus while in touch mode.
5928     *
5929     * Setting this to true will also ensure that this view is focusable.
5930     *
5931     * @param focusableInTouchMode If true, this view can receive the focus while
5932     *   in touch mode.
5933     *
5934     * @see #setFocusable(boolean)
5935     * @attr ref android.R.styleable#View_focusableInTouchMode
5936     */
5937    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
5938        // Focusable in touch mode should always be set before the focusable flag
5939        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
5940        // which, in touch mode, will not successfully request focus on this view
5941        // because the focusable in touch mode flag is not set
5942        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
5943        if (focusableInTouchMode) {
5944            setFlags(FOCUSABLE, FOCUSABLE_MASK);
5945        }
5946    }
5947
5948    /**
5949     * Set whether this view should have sound effects enabled for events such as
5950     * clicking and touching.
5951     *
5952     * <p>You may wish to disable sound effects for a view if you already play sounds,
5953     * for instance, a dial key that plays dtmf tones.
5954     *
5955     * @param soundEffectsEnabled whether sound effects are enabled for this view.
5956     * @see #isSoundEffectsEnabled()
5957     * @see #playSoundEffect(int)
5958     * @attr ref android.R.styleable#View_soundEffectsEnabled
5959     */
5960    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
5961        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
5962    }
5963
5964    /**
5965     * @return whether this view should have sound effects enabled for events such as
5966     *     clicking and touching.
5967     *
5968     * @see #setSoundEffectsEnabled(boolean)
5969     * @see #playSoundEffect(int)
5970     * @attr ref android.R.styleable#View_soundEffectsEnabled
5971     */
5972    @ViewDebug.ExportedProperty
5973    public boolean isSoundEffectsEnabled() {
5974        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
5975    }
5976
5977    /**
5978     * Set whether this view should have haptic feedback for events such as
5979     * long presses.
5980     *
5981     * <p>You may wish to disable haptic feedback if your view already controls
5982     * its own haptic feedback.
5983     *
5984     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
5985     * @see #isHapticFeedbackEnabled()
5986     * @see #performHapticFeedback(int)
5987     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
5988     */
5989    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
5990        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
5991    }
5992
5993    /**
5994     * @return whether this view should have haptic feedback enabled for events
5995     * long presses.
5996     *
5997     * @see #setHapticFeedbackEnabled(boolean)
5998     * @see #performHapticFeedback(int)
5999     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
6000     */
6001    @ViewDebug.ExportedProperty
6002    public boolean isHapticFeedbackEnabled() {
6003        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
6004    }
6005
6006    /**
6007     * Returns the layout direction for this view.
6008     *
6009     * @return One of {@link #LAYOUT_DIRECTION_LTR},
6010     *   {@link #LAYOUT_DIRECTION_RTL},
6011     *   {@link #LAYOUT_DIRECTION_INHERIT} or
6012     *   {@link #LAYOUT_DIRECTION_LOCALE}.
6013     *
6014     * @attr ref android.R.styleable#View_layoutDirection
6015     *
6016     * @hide
6017     */
6018    @ViewDebug.ExportedProperty(category = "layout", mapping = {
6019        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
6020        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
6021        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
6022        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
6023    })
6024    public int getRawLayoutDirection() {
6025        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
6026    }
6027
6028    /**
6029     * Set the layout direction for this view. This will propagate a reset of layout direction
6030     * resolution to the view's children and resolve layout direction for this view.
6031     *
6032     * @param layoutDirection the layout direction to set. Should be one of:
6033     *
6034     * {@link #LAYOUT_DIRECTION_LTR},
6035     * {@link #LAYOUT_DIRECTION_RTL},
6036     * {@link #LAYOUT_DIRECTION_INHERIT},
6037     * {@link #LAYOUT_DIRECTION_LOCALE}.
6038     *
6039     * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution
6040     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
6041     * will return the default {@link #LAYOUT_DIRECTION_LTR}.
6042     *
6043     * @attr ref android.R.styleable#View_layoutDirection
6044     */
6045    @RemotableViewMethod
6046    public void setLayoutDirection(int layoutDirection) {
6047        if (getRawLayoutDirection() != layoutDirection) {
6048            // Reset the current layout direction and the resolved one
6049            mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK;
6050            resetRtlProperties();
6051            // Set the new layout direction (filtered)
6052            mPrivateFlags2 |=
6053                    ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK);
6054            // We need to resolve all RTL properties as they all depend on layout direction
6055            resolveRtlPropertiesIfNeeded();
6056            requestLayout();
6057            invalidate(true);
6058        }
6059    }
6060
6061    /**
6062     * Returns the resolved layout direction for this view.
6063     *
6064     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
6065     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
6066     *
6067     * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version
6068     * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}.
6069     *
6070     * @attr ref android.R.styleable#View_layoutDirection
6071     */
6072    @ViewDebug.ExportedProperty(category = "layout", mapping = {
6073        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
6074        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
6075    })
6076    public int getLayoutDirection() {
6077        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
6078        if (targetSdkVersion < JELLY_BEAN_MR1) {
6079            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
6080            return LAYOUT_DIRECTION_RESOLVED_DEFAULT;
6081        }
6082        return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ==
6083                PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
6084    }
6085
6086    /**
6087     * Indicates whether or not this view's layout is right-to-left. This is resolved from
6088     * layout attribute and/or the inherited value from the parent
6089     *
6090     * @return true if the layout is right-to-left.
6091     *
6092     * @hide
6093     */
6094    @ViewDebug.ExportedProperty(category = "layout")
6095    public boolean isLayoutRtl() {
6096        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
6097    }
6098
6099    /**
6100     * Indicates whether the view is currently tracking transient state that the
6101     * app should not need to concern itself with saving and restoring, but that
6102     * the framework should take special note to preserve when possible.
6103     *
6104     * <p>A view with transient state cannot be trivially rebound from an external
6105     * data source, such as an adapter binding item views in a list. This may be
6106     * because the view is performing an animation, tracking user selection
6107     * of content, or similar.</p>
6108     *
6109     * @return true if the view has transient state
6110     */
6111    @ViewDebug.ExportedProperty(category = "layout")
6112    public boolean hasTransientState() {
6113        return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE;
6114    }
6115
6116    /**
6117     * Set whether this view is currently tracking transient state that the
6118     * framework should attempt to preserve when possible. This flag is reference counted,
6119     * so every call to setHasTransientState(true) should be paired with a later call
6120     * to setHasTransientState(false).
6121     *
6122     * <p>A view with transient state cannot be trivially rebound from an external
6123     * data source, such as an adapter binding item views in a list. This may be
6124     * because the view is performing an animation, tracking user selection
6125     * of content, or similar.</p>
6126     *
6127     * @param hasTransientState true if this view has transient state
6128     */
6129    public void setHasTransientState(boolean hasTransientState) {
6130        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
6131                mTransientStateCount - 1;
6132        if (mTransientStateCount < 0) {
6133            mTransientStateCount = 0;
6134            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
6135                    "unmatched pair of setHasTransientState calls");
6136        } else if ((hasTransientState && mTransientStateCount == 1) ||
6137                (!hasTransientState && mTransientStateCount == 0)) {
6138            // update flag if we've just incremented up from 0 or decremented down to 0
6139            mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) |
6140                    (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0);
6141            if (mParent != null) {
6142                try {
6143                    mParent.childHasTransientStateChanged(this, hasTransientState);
6144                } catch (AbstractMethodError e) {
6145                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
6146                            " does not fully implement ViewParent", e);
6147                }
6148            }
6149        }
6150    }
6151
6152    /**
6153     * Returns true if this view is currently attached to a window.
6154     */
6155    public boolean isAttachedToWindow() {
6156        return mAttachInfo != null;
6157    }
6158
6159    /**
6160     * Returns true if this view has been through at least one layout since it
6161     * was last attached to or detached from a window.
6162     */
6163    public boolean isLaidOut() {
6164        return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT;
6165    }
6166
6167    /**
6168     * If this view doesn't do any drawing on its own, set this flag to
6169     * allow further optimizations. By default, this flag is not set on
6170     * View, but could be set on some View subclasses such as ViewGroup.
6171     *
6172     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
6173     * you should clear this flag.
6174     *
6175     * @param willNotDraw whether or not this View draw on its own
6176     */
6177    public void setWillNotDraw(boolean willNotDraw) {
6178        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
6179    }
6180
6181    /**
6182     * Returns whether or not this View draws on its own.
6183     *
6184     * @return true if this view has nothing to draw, false otherwise
6185     */
6186    @ViewDebug.ExportedProperty(category = "drawing")
6187    public boolean willNotDraw() {
6188        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
6189    }
6190
6191    /**
6192     * When a View's drawing cache is enabled, drawing is redirected to an
6193     * offscreen bitmap. Some views, like an ImageView, must be able to
6194     * bypass this mechanism if they already draw a single bitmap, to avoid
6195     * unnecessary usage of the memory.
6196     *
6197     * @param willNotCacheDrawing true if this view does not cache its
6198     *        drawing, false otherwise
6199     */
6200    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
6201        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
6202    }
6203
6204    /**
6205     * Returns whether or not this View can cache its drawing or not.
6206     *
6207     * @return true if this view does not cache its drawing, false otherwise
6208     */
6209    @ViewDebug.ExportedProperty(category = "drawing")
6210    public boolean willNotCacheDrawing() {
6211        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
6212    }
6213
6214    /**
6215     * Indicates whether this view reacts to click events or not.
6216     *
6217     * @return true if the view is clickable, false otherwise
6218     *
6219     * @see #setClickable(boolean)
6220     * @attr ref android.R.styleable#View_clickable
6221     */
6222    @ViewDebug.ExportedProperty
6223    public boolean isClickable() {
6224        return (mViewFlags & CLICKABLE) == CLICKABLE;
6225    }
6226
6227    /**
6228     * Enables or disables click events for this view. When a view
6229     * is clickable it will change its state to "pressed" on every click.
6230     * Subclasses should set the view clickable to visually react to
6231     * user's clicks.
6232     *
6233     * @param clickable true to make the view clickable, false otherwise
6234     *
6235     * @see #isClickable()
6236     * @attr ref android.R.styleable#View_clickable
6237     */
6238    public void setClickable(boolean clickable) {
6239        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
6240    }
6241
6242    /**
6243     * Indicates whether this view reacts to long click events or not.
6244     *
6245     * @return true if the view is long clickable, false otherwise
6246     *
6247     * @see #setLongClickable(boolean)
6248     * @attr ref android.R.styleable#View_longClickable
6249     */
6250    public boolean isLongClickable() {
6251        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
6252    }
6253
6254    /**
6255     * Enables or disables long click events for this view. When a view is long
6256     * clickable it reacts to the user holding down the button for a longer
6257     * duration than a tap. This event can either launch the listener or a
6258     * context menu.
6259     *
6260     * @param longClickable true to make the view long clickable, false otherwise
6261     * @see #isLongClickable()
6262     * @attr ref android.R.styleable#View_longClickable
6263     */
6264    public void setLongClickable(boolean longClickable) {
6265        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
6266    }
6267
6268    /**
6269     * Sets the pressed state for this view.
6270     *
6271     * @see #isClickable()
6272     * @see #setClickable(boolean)
6273     *
6274     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
6275     *        the View's internal state from a previously set "pressed" state.
6276     */
6277    public void setPressed(boolean pressed) {
6278        final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
6279
6280        if (pressed) {
6281            mPrivateFlags |= PFLAG_PRESSED;
6282        } else {
6283            mPrivateFlags &= ~PFLAG_PRESSED;
6284        }
6285
6286        if (needsRefresh) {
6287            refreshDrawableState();
6288        }
6289        dispatchSetPressed(pressed);
6290    }
6291
6292    /**
6293     * Dispatch setPressed to all of this View's children.
6294     *
6295     * @see #setPressed(boolean)
6296     *
6297     * @param pressed The new pressed state
6298     */
6299    protected void dispatchSetPressed(boolean pressed) {
6300    }
6301
6302    /**
6303     * Indicates whether the view is currently in pressed state. Unless
6304     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
6305     * the pressed state.
6306     *
6307     * @see #setPressed(boolean)
6308     * @see #isClickable()
6309     * @see #setClickable(boolean)
6310     *
6311     * @return true if the view is currently pressed, false otherwise
6312     */
6313    public boolean isPressed() {
6314        return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED;
6315    }
6316
6317    /**
6318     * Indicates whether this view will save its state (that is,
6319     * whether its {@link #onSaveInstanceState} method will be called).
6320     *
6321     * @return Returns true if the view state saving is enabled, else false.
6322     *
6323     * @see #setSaveEnabled(boolean)
6324     * @attr ref android.R.styleable#View_saveEnabled
6325     */
6326    public boolean isSaveEnabled() {
6327        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
6328    }
6329
6330    /**
6331     * Controls whether the saving of this view's state is
6332     * enabled (that is, whether its {@link #onSaveInstanceState} method
6333     * will be called).  Note that even if freezing is enabled, the
6334     * view still must have an id assigned to it (via {@link #setId(int)})
6335     * for its state to be saved.  This flag can only disable the
6336     * saving of this view; any child views may still have their state saved.
6337     *
6338     * @param enabled Set to false to <em>disable</em> state saving, or true
6339     * (the default) to allow it.
6340     *
6341     * @see #isSaveEnabled()
6342     * @see #setId(int)
6343     * @see #onSaveInstanceState()
6344     * @attr ref android.R.styleable#View_saveEnabled
6345     */
6346    public void setSaveEnabled(boolean enabled) {
6347        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
6348    }
6349
6350    /**
6351     * Gets whether the framework should discard touches when the view's
6352     * window is obscured by another visible window.
6353     * Refer to the {@link View} security documentation for more details.
6354     *
6355     * @return True if touch filtering is enabled.
6356     *
6357     * @see #setFilterTouchesWhenObscured(boolean)
6358     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
6359     */
6360    @ViewDebug.ExportedProperty
6361    public boolean getFilterTouchesWhenObscured() {
6362        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
6363    }
6364
6365    /**
6366     * Sets whether the framework should discard touches when the view's
6367     * window is obscured by another visible window.
6368     * Refer to the {@link View} security documentation for more details.
6369     *
6370     * @param enabled True if touch filtering should be enabled.
6371     *
6372     * @see #getFilterTouchesWhenObscured
6373     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
6374     */
6375    public void setFilterTouchesWhenObscured(boolean enabled) {
6376        setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
6377                FILTER_TOUCHES_WHEN_OBSCURED);
6378    }
6379
6380    /**
6381     * Indicates whether the entire hierarchy under this view will save its
6382     * state when a state saving traversal occurs from its parent.  The default
6383     * is true; if false, these views will not be saved unless
6384     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
6385     *
6386     * @return Returns true if the view state saving from parent is enabled, else false.
6387     *
6388     * @see #setSaveFromParentEnabled(boolean)
6389     */
6390    public boolean isSaveFromParentEnabled() {
6391        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
6392    }
6393
6394    /**
6395     * Controls whether the entire hierarchy under this view will save its
6396     * state when a state saving traversal occurs from its parent.  The default
6397     * is true; if false, these views will not be saved unless
6398     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
6399     *
6400     * @param enabled Set to false to <em>disable</em> state saving, or true
6401     * (the default) to allow it.
6402     *
6403     * @see #isSaveFromParentEnabled()
6404     * @see #setId(int)
6405     * @see #onSaveInstanceState()
6406     */
6407    public void setSaveFromParentEnabled(boolean enabled) {
6408        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
6409    }
6410
6411
6412    /**
6413     * Returns whether this View is able to take focus.
6414     *
6415     * @return True if this view can take focus, or false otherwise.
6416     * @attr ref android.R.styleable#View_focusable
6417     */
6418    @ViewDebug.ExportedProperty(category = "focus")
6419    public final boolean isFocusable() {
6420        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
6421    }
6422
6423    /**
6424     * When a view is focusable, it may not want to take focus when in touch mode.
6425     * For example, a button would like focus when the user is navigating via a D-pad
6426     * so that the user can click on it, but once the user starts touching the screen,
6427     * the button shouldn't take focus
6428     * @return Whether the view is focusable in touch mode.
6429     * @attr ref android.R.styleable#View_focusableInTouchMode
6430     */
6431    @ViewDebug.ExportedProperty
6432    public final boolean isFocusableInTouchMode() {
6433        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
6434    }
6435
6436    /**
6437     * Find the nearest view in the specified direction that can take focus.
6438     * This does not actually give focus to that view.
6439     *
6440     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6441     *
6442     * @return The nearest focusable in the specified direction, or null if none
6443     *         can be found.
6444     */
6445    public View focusSearch(int direction) {
6446        if (mParent != null) {
6447            return mParent.focusSearch(this, direction);
6448        } else {
6449            return null;
6450        }
6451    }
6452
6453    /**
6454     * This method is the last chance for the focused view and its ancestors to
6455     * respond to an arrow key. This is called when the focused view did not
6456     * consume the key internally, nor could the view system find a new view in
6457     * the requested direction to give focus to.
6458     *
6459     * @param focused The currently focused view.
6460     * @param direction The direction focus wants to move. One of FOCUS_UP,
6461     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
6462     * @return True if the this view consumed this unhandled move.
6463     */
6464    public boolean dispatchUnhandledMove(View focused, int direction) {
6465        return false;
6466    }
6467
6468    /**
6469     * If a user manually specified the next view id for a particular direction,
6470     * use the root to look up the view.
6471     * @param root The root view of the hierarchy containing this view.
6472     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
6473     * or FOCUS_BACKWARD.
6474     * @return The user specified next view, or null if there is none.
6475     */
6476    View findUserSetNextFocus(View root, int direction) {
6477        switch (direction) {
6478            case FOCUS_LEFT:
6479                if (mNextFocusLeftId == View.NO_ID) return null;
6480                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
6481            case FOCUS_RIGHT:
6482                if (mNextFocusRightId == View.NO_ID) return null;
6483                return findViewInsideOutShouldExist(root, mNextFocusRightId);
6484            case FOCUS_UP:
6485                if (mNextFocusUpId == View.NO_ID) return null;
6486                return findViewInsideOutShouldExist(root, mNextFocusUpId);
6487            case FOCUS_DOWN:
6488                if (mNextFocusDownId == View.NO_ID) return null;
6489                return findViewInsideOutShouldExist(root, mNextFocusDownId);
6490            case FOCUS_FORWARD:
6491                if (mNextFocusForwardId == View.NO_ID) return null;
6492                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
6493            case FOCUS_BACKWARD: {
6494                if (mID == View.NO_ID) return null;
6495                final int id = mID;
6496                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
6497                    @Override
6498                    public boolean apply(View t) {
6499                        return t.mNextFocusForwardId == id;
6500                    }
6501                });
6502            }
6503        }
6504        return null;
6505    }
6506
6507    private View findViewInsideOutShouldExist(View root, int id) {
6508        if (mMatchIdPredicate == null) {
6509            mMatchIdPredicate = new MatchIdPredicate();
6510        }
6511        mMatchIdPredicate.mId = id;
6512        View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate);
6513        if (result == null) {
6514            Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id);
6515        }
6516        return result;
6517    }
6518
6519    /**
6520     * Find and return all focusable views that are descendants of this view,
6521     * possibly including this view if it is focusable itself.
6522     *
6523     * @param direction The direction of the focus
6524     * @return A list of focusable views
6525     */
6526    public ArrayList<View> getFocusables(int direction) {
6527        ArrayList<View> result = new ArrayList<View>(24);
6528        addFocusables(result, direction);
6529        return result;
6530    }
6531
6532    /**
6533     * Add any focusable views that are descendants of this view (possibly
6534     * including this view if it is focusable itself) to views.  If we are in touch mode,
6535     * only add views that are also focusable in touch mode.
6536     *
6537     * @param views Focusable views found so far
6538     * @param direction The direction of the focus
6539     */
6540    public void addFocusables(ArrayList<View> views, int direction) {
6541        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
6542    }
6543
6544    /**
6545     * Adds any focusable views that are descendants of this view (possibly
6546     * including this view if it is focusable itself) to views. This method
6547     * adds all focusable views regardless if we are in touch mode or
6548     * only views focusable in touch mode if we are in touch mode or
6549     * only views that can take accessibility focus if accessibility is enabeld
6550     * depending on the focusable mode paramater.
6551     *
6552     * @param views Focusable views found so far or null if all we are interested is
6553     *        the number of focusables.
6554     * @param direction The direction of the focus.
6555     * @param focusableMode The type of focusables to be added.
6556     *
6557     * @see #FOCUSABLES_ALL
6558     * @see #FOCUSABLES_TOUCH_MODE
6559     */
6560    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
6561        if (views == null) {
6562            return;
6563        }
6564        if (!isFocusable()) {
6565            return;
6566        }
6567        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
6568                && isInTouchMode() && !isFocusableInTouchMode()) {
6569            return;
6570        }
6571        views.add(this);
6572    }
6573
6574    /**
6575     * Finds the Views that contain given text. The containment is case insensitive.
6576     * The search is performed by either the text that the View renders or the content
6577     * description that describes the view for accessibility purposes and the view does
6578     * not render or both. Clients can specify how the search is to be performed via
6579     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
6580     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
6581     *
6582     * @param outViews The output list of matching Views.
6583     * @param searched The text to match against.
6584     *
6585     * @see #FIND_VIEWS_WITH_TEXT
6586     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
6587     * @see #setContentDescription(CharSequence)
6588     */
6589    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) {
6590        if (getAccessibilityNodeProvider() != null) {
6591            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
6592                outViews.add(this);
6593            }
6594        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
6595                && (searched != null && searched.length() > 0)
6596                && (mContentDescription != null && mContentDescription.length() > 0)) {
6597            String searchedLowerCase = searched.toString().toLowerCase();
6598            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
6599            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
6600                outViews.add(this);
6601            }
6602        }
6603    }
6604
6605    /**
6606     * Find and return all touchable views that are descendants of this view,
6607     * possibly including this view if it is touchable itself.
6608     *
6609     * @return A list of touchable views
6610     */
6611    public ArrayList<View> getTouchables() {
6612        ArrayList<View> result = new ArrayList<View>();
6613        addTouchables(result);
6614        return result;
6615    }
6616
6617    /**
6618     * Add any touchable views that are descendants of this view (possibly
6619     * including this view if it is touchable itself) to views.
6620     *
6621     * @param views Touchable views found so far
6622     */
6623    public void addTouchables(ArrayList<View> views) {
6624        final int viewFlags = mViewFlags;
6625
6626        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
6627                && (viewFlags & ENABLED_MASK) == ENABLED) {
6628            views.add(this);
6629        }
6630    }
6631
6632    /**
6633     * Returns whether this View is accessibility focused.
6634     *
6635     * @return True if this View is accessibility focused.
6636     */
6637    boolean isAccessibilityFocused() {
6638        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
6639    }
6640
6641    /**
6642     * Call this to try to give accessibility focus to this view.
6643     *
6644     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
6645     * returns false or the view is no visible or the view already has accessibility
6646     * focus.
6647     *
6648     * See also {@link #focusSearch(int)}, which is what you call to say that you
6649     * have focus, and you want your parent to look for the next one.
6650     *
6651     * @return Whether this view actually took accessibility focus.
6652     *
6653     * @hide
6654     */
6655    public boolean requestAccessibilityFocus() {
6656        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
6657        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
6658            return false;
6659        }
6660        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6661            return false;
6662        }
6663        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
6664            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
6665            ViewRootImpl viewRootImpl = getViewRootImpl();
6666            if (viewRootImpl != null) {
6667                viewRootImpl.setAccessibilityFocus(this, null);
6668            }
6669            invalidate();
6670            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
6671            return true;
6672        }
6673        return false;
6674    }
6675
6676    /**
6677     * Call this to try to clear accessibility focus of this view.
6678     *
6679     * See also {@link #focusSearch(int)}, which is what you call to say that you
6680     * have focus, and you want your parent to look for the next one.
6681     *
6682     * @hide
6683     */
6684    public void clearAccessibilityFocus() {
6685        clearAccessibilityFocusNoCallbacks();
6686        // Clear the global reference of accessibility focus if this
6687        // view or any of its descendants had accessibility focus.
6688        ViewRootImpl viewRootImpl = getViewRootImpl();
6689        if (viewRootImpl != null) {
6690            View focusHost = viewRootImpl.getAccessibilityFocusedHost();
6691            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
6692                viewRootImpl.setAccessibilityFocus(null, null);
6693            }
6694        }
6695    }
6696
6697    private void sendAccessibilityHoverEvent(int eventType) {
6698        // Since we are not delivering to a client accessibility events from not
6699        // important views (unless the clinet request that) we need to fire the
6700        // event from the deepest view exposed to the client. As a consequence if
6701        // the user crosses a not exposed view the client will see enter and exit
6702        // of the exposed predecessor followed by and enter and exit of that same
6703        // predecessor when entering and exiting the not exposed descendant. This
6704        // is fine since the client has a clear idea which view is hovered at the
6705        // price of a couple more events being sent. This is a simple and
6706        // working solution.
6707        View source = this;
6708        while (true) {
6709            if (source.includeForAccessibility()) {
6710                source.sendAccessibilityEvent(eventType);
6711                return;
6712            }
6713            ViewParent parent = source.getParent();
6714            if (parent instanceof View) {
6715                source = (View) parent;
6716            } else {
6717                return;
6718            }
6719        }
6720    }
6721
6722    /**
6723     * Clears accessibility focus without calling any callback methods
6724     * normally invoked in {@link #clearAccessibilityFocus()}. This method
6725     * is used for clearing accessibility focus when giving this focus to
6726     * another view.
6727     */
6728    void clearAccessibilityFocusNoCallbacks() {
6729        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
6730            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
6731            invalidate();
6732            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
6733        }
6734    }
6735
6736    /**
6737     * Call this to try to give focus to a specific view or to one of its
6738     * descendants.
6739     *
6740     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6741     * false), or if it is focusable and it is not focusable in touch mode
6742     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6743     *
6744     * See also {@link #focusSearch(int)}, which is what you call to say that you
6745     * have focus, and you want your parent to look for the next one.
6746     *
6747     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
6748     * {@link #FOCUS_DOWN} and <code>null</code>.
6749     *
6750     * @return Whether this view or one of its descendants actually took focus.
6751     */
6752    public final boolean requestFocus() {
6753        return requestFocus(View.FOCUS_DOWN);
6754    }
6755
6756    /**
6757     * Call this to try to give focus to a specific view or to one of its
6758     * descendants and give it a hint about what direction focus is heading.
6759     *
6760     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6761     * false), or if it is focusable and it is not focusable in touch mode
6762     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6763     *
6764     * See also {@link #focusSearch(int)}, which is what you call to say that you
6765     * have focus, and you want your parent to look for the next one.
6766     *
6767     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
6768     * <code>null</code> set for the previously focused rectangle.
6769     *
6770     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6771     * @return Whether this view or one of its descendants actually took focus.
6772     */
6773    public final boolean requestFocus(int direction) {
6774        return requestFocus(direction, null);
6775    }
6776
6777    /**
6778     * Call this to try to give focus to a specific view or to one of its descendants
6779     * and give it hints about the direction and a specific rectangle that the focus
6780     * is coming from.  The rectangle can help give larger views a finer grained hint
6781     * about where focus is coming from, and therefore, where to show selection, or
6782     * forward focus change internally.
6783     *
6784     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6785     * false), or if it is focusable and it is not focusable in touch mode
6786     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6787     *
6788     * A View will not take focus if it is not visible.
6789     *
6790     * A View will not take focus if one of its parents has
6791     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
6792     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
6793     *
6794     * See also {@link #focusSearch(int)}, which is what you call to say that you
6795     * have focus, and you want your parent to look for the next one.
6796     *
6797     * You may wish to override this method if your custom {@link View} has an internal
6798     * {@link View} that it wishes to forward the request to.
6799     *
6800     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6801     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
6802     *        to give a finer grained hint about where focus is coming from.  May be null
6803     *        if there is no hint.
6804     * @return Whether this view or one of its descendants actually took focus.
6805     */
6806    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
6807        return requestFocusNoSearch(direction, previouslyFocusedRect);
6808    }
6809
6810    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
6811        // need to be focusable
6812        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
6813                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6814            return false;
6815        }
6816
6817        // need to be focusable in touch mode if in touch mode
6818        if (isInTouchMode() &&
6819            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
6820               return false;
6821        }
6822
6823        // need to not have any parents blocking us
6824        if (hasAncestorThatBlocksDescendantFocus()) {
6825            return false;
6826        }
6827
6828        handleFocusGainInternal(direction, previouslyFocusedRect);
6829        return true;
6830    }
6831
6832    /**
6833     * Call this to try to give focus to a specific view or to one of its descendants. This is a
6834     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
6835     * touch mode to request focus when they are touched.
6836     *
6837     * @return Whether this view or one of its descendants actually took focus.
6838     *
6839     * @see #isInTouchMode()
6840     *
6841     */
6842    public final boolean requestFocusFromTouch() {
6843        // Leave touch mode if we need to
6844        if (isInTouchMode()) {
6845            ViewRootImpl viewRoot = getViewRootImpl();
6846            if (viewRoot != null) {
6847                viewRoot.ensureTouchMode(false);
6848            }
6849        }
6850        return requestFocus(View.FOCUS_DOWN);
6851    }
6852
6853    /**
6854     * @return Whether any ancestor of this view blocks descendant focus.
6855     */
6856    private boolean hasAncestorThatBlocksDescendantFocus() {
6857        ViewParent ancestor = mParent;
6858        while (ancestor instanceof ViewGroup) {
6859            final ViewGroup vgAncestor = (ViewGroup) ancestor;
6860            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
6861                return true;
6862            } else {
6863                ancestor = vgAncestor.getParent();
6864            }
6865        }
6866        return false;
6867    }
6868
6869    /**
6870     * Gets the mode for determining whether this View is important for accessibility
6871     * which is if it fires accessibility events and if it is reported to
6872     * accessibility services that query the screen.
6873     *
6874     * @return The mode for determining whether a View is important for accessibility.
6875     *
6876     * @attr ref android.R.styleable#View_importantForAccessibility
6877     *
6878     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
6879     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
6880     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
6881     */
6882    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
6883            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
6884            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
6885            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no")
6886        })
6887    public int getImportantForAccessibility() {
6888        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
6889                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
6890    }
6891
6892    /**
6893     * Sets how to determine whether this view is important for accessibility
6894     * which is if it fires accessibility events and if it is reported to
6895     * accessibility services that query the screen.
6896     *
6897     * @param mode How to determine whether this view is important for accessibility.
6898     *
6899     * @attr ref android.R.styleable#View_importantForAccessibility
6900     *
6901     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
6902     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
6903     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
6904     */
6905    public void setImportantForAccessibility(int mode) {
6906        final boolean oldIncludeForAccessibility = includeForAccessibility();
6907        if (mode != getImportantForAccessibility()) {
6908            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
6909            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
6910                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
6911            if (oldIncludeForAccessibility != includeForAccessibility()) {
6912                notifySubtreeAccessibilityStateChangedIfNeeded();
6913            } else {
6914                notifyViewAccessibilityStateChangedIfNeeded();
6915            }
6916        }
6917    }
6918
6919    /**
6920     * Gets whether this view should be exposed for accessibility.
6921     *
6922     * @return Whether the view is exposed for accessibility.
6923     *
6924     * @hide
6925     */
6926    public boolean isImportantForAccessibility() {
6927        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
6928                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
6929        switch (mode) {
6930            case IMPORTANT_FOR_ACCESSIBILITY_YES:
6931                return true;
6932            case IMPORTANT_FOR_ACCESSIBILITY_NO:
6933                return false;
6934            case IMPORTANT_FOR_ACCESSIBILITY_AUTO:
6935                return isActionableForAccessibility() || hasListenersForAccessibility()
6936                        || getAccessibilityNodeProvider() != null;
6937            default:
6938                throw new IllegalArgumentException("Unknow important for accessibility mode: "
6939                        + mode);
6940        }
6941    }
6942
6943    /**
6944     * Gets the parent for accessibility purposes. Note that the parent for
6945     * accessibility is not necessary the immediate parent. It is the first
6946     * predecessor that is important for accessibility.
6947     *
6948     * @return The parent for accessibility purposes.
6949     */
6950    public ViewParent getParentForAccessibility() {
6951        if (mParent instanceof View) {
6952            View parentView = (View) mParent;
6953            if (parentView.includeForAccessibility()) {
6954                return mParent;
6955            } else {
6956                return mParent.getParentForAccessibility();
6957            }
6958        }
6959        return null;
6960    }
6961
6962    /**
6963     * Adds the children of a given View for accessibility. Since some Views are
6964     * not important for accessibility the children for accessibility are not
6965     * necessarily direct children of the view, rather they are the first level of
6966     * descendants important for accessibility.
6967     *
6968     * @param children The list of children for accessibility.
6969     */
6970    public void addChildrenForAccessibility(ArrayList<View> children) {
6971        if (includeForAccessibility()) {
6972            children.add(this);
6973        }
6974    }
6975
6976    /**
6977     * Whether to regard this view for accessibility. A view is regarded for
6978     * accessibility if it is important for accessibility or the querying
6979     * accessibility service has explicitly requested that view not
6980     * important for accessibility are regarded.
6981     *
6982     * @return Whether to regard the view for accessibility.
6983     *
6984     * @hide
6985     */
6986    public boolean includeForAccessibility() {
6987        //noinspection SimplifiableIfStatement
6988        if (mAttachInfo != null) {
6989            return (mAttachInfo.mAccessibilityFetchFlags
6990                    & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0
6991                    || isImportantForAccessibility();
6992        }
6993        return false;
6994    }
6995
6996    /**
6997     * Returns whether the View is considered actionable from
6998     * accessibility perspective. Such view are important for
6999     * accessibility.
7000     *
7001     * @return True if the view is actionable for accessibility.
7002     *
7003     * @hide
7004     */
7005    public boolean isActionableForAccessibility() {
7006        return (isClickable() || isLongClickable() || isFocusable());
7007    }
7008
7009    /**
7010     * Returns whether the View has registered callbacks wich makes it
7011     * important for accessibility.
7012     *
7013     * @return True if the view is actionable for accessibility.
7014     */
7015    private boolean hasListenersForAccessibility() {
7016        ListenerInfo info = getListenerInfo();
7017        return mTouchDelegate != null || info.mOnKeyListener != null
7018                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
7019                || info.mOnHoverListener != null || info.mOnDragListener != null;
7020    }
7021
7022    /**
7023     * Notifies that the accessibility state of this view changed. The change
7024     * is local to this view and does not represent structural changes such
7025     * as children and parent. For example, the view became focusable. The
7026     * notification is at at most once every
7027     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
7028     * to avoid unnecessary load to the system. Also once a view has a pending
7029     * notifucation this method is a NOP until the notification has been sent.
7030     *
7031     * @hide
7032     */
7033    public void notifyViewAccessibilityStateChangedIfNeeded() {
7034        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
7035            return;
7036        }
7037        if (mSendViewStateChangedAccessibilityEvent == null) {
7038            mSendViewStateChangedAccessibilityEvent =
7039                    new SendViewStateChangedAccessibilityEvent();
7040        }
7041        mSendViewStateChangedAccessibilityEvent.runOrPost();
7042    }
7043
7044    /**
7045     * Notifies that the accessibility state of this view changed. The change
7046     * is *not* local to this view and does represent structural changes such
7047     * as children and parent. For example, the view size changed. The
7048     * notification is at at most once every
7049     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
7050     * to avoid unnecessary load to the system. Also once a view has a pending
7051     * notifucation this method is a NOP until the notification has been sent.
7052     *
7053     * @hide
7054     */
7055    public void notifySubtreeAccessibilityStateChangedIfNeeded() {
7056        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
7057            return;
7058        }
7059        if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) {
7060            mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
7061            if (mParent != null) {
7062                try {
7063                    mParent.childAccessibilityStateChanged(this);
7064                } catch (AbstractMethodError e) {
7065                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
7066                            " does not fully implement ViewParent", e);
7067                }
7068            }
7069        }
7070    }
7071
7072    /**
7073     * Reset the flag indicating the accessibility state of the subtree rooted
7074     * at this view changed.
7075     */
7076    void resetSubtreeAccessibilityStateChanged() {
7077        mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
7078    }
7079
7080    /**
7081     * Performs the specified accessibility action on the view. For
7082     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
7083     * <p>
7084     * If an {@link AccessibilityDelegate} has been specified via calling
7085     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
7086     * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
7087     * is responsible for handling this call.
7088     * </p>
7089     *
7090     * @param action The action to perform.
7091     * @param arguments Optional action arguments.
7092     * @return Whether the action was performed.
7093     */
7094    public boolean performAccessibilityAction(int action, Bundle arguments) {
7095      if (mAccessibilityDelegate != null) {
7096          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
7097      } else {
7098          return performAccessibilityActionInternal(action, arguments);
7099      }
7100    }
7101
7102   /**
7103    * @see #performAccessibilityAction(int, Bundle)
7104    *
7105    * Note: Called from the default {@link AccessibilityDelegate}.
7106    */
7107    boolean performAccessibilityActionInternal(int action, Bundle arguments) {
7108        switch (action) {
7109            case AccessibilityNodeInfo.ACTION_CLICK: {
7110                if (isClickable()) {
7111                    performClick();
7112                    return true;
7113                }
7114            } break;
7115            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
7116                if (isLongClickable()) {
7117                    performLongClick();
7118                    return true;
7119                }
7120            } break;
7121            case AccessibilityNodeInfo.ACTION_FOCUS: {
7122                if (!hasFocus()) {
7123                    // Get out of touch mode since accessibility
7124                    // wants to move focus around.
7125                    getViewRootImpl().ensureTouchMode(false);
7126                    return requestFocus();
7127                }
7128            } break;
7129            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
7130                if (hasFocus()) {
7131                    clearFocus();
7132                    return !isFocused();
7133                }
7134            } break;
7135            case AccessibilityNodeInfo.ACTION_SELECT: {
7136                if (!isSelected()) {
7137                    setSelected(true);
7138                    return isSelected();
7139                }
7140            } break;
7141            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
7142                if (isSelected()) {
7143                    setSelected(false);
7144                    return !isSelected();
7145                }
7146            } break;
7147            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
7148                if (!isAccessibilityFocused()) {
7149                    return requestAccessibilityFocus();
7150                }
7151            } break;
7152            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
7153                if (isAccessibilityFocused()) {
7154                    clearAccessibilityFocus();
7155                    return true;
7156                }
7157            } break;
7158            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
7159                if (arguments != null) {
7160                    final int granularity = arguments.getInt(
7161                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
7162                    final boolean extendSelection = arguments.getBoolean(
7163                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
7164                    return traverseAtGranularity(granularity, true, extendSelection);
7165                }
7166            } break;
7167            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
7168                if (arguments != null) {
7169                    final int granularity = arguments.getInt(
7170                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
7171                    final boolean extendSelection = arguments.getBoolean(
7172                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
7173                    return traverseAtGranularity(granularity, false, extendSelection);
7174                }
7175            } break;
7176            case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
7177                CharSequence text = getIterableTextForAccessibility();
7178                if (text == null) {
7179                    return false;
7180                }
7181                final int start = (arguments != null) ? arguments.getInt(
7182                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1;
7183                final int end = (arguments != null) ? arguments.getInt(
7184                AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1;
7185                // Only cursor position can be specified (selection length == 0)
7186                if ((getAccessibilitySelectionStart() != start
7187                        || getAccessibilitySelectionEnd() != end)
7188                        && (start == end)) {
7189                    setAccessibilitySelection(start, end);
7190                    notifyViewAccessibilityStateChangedIfNeeded();
7191                    return true;
7192                }
7193            } break;
7194        }
7195        return false;
7196    }
7197
7198    private boolean traverseAtGranularity(int granularity, boolean forward,
7199            boolean extendSelection) {
7200        CharSequence text = getIterableTextForAccessibility();
7201        if (text == null || text.length() == 0) {
7202            return false;
7203        }
7204        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
7205        if (iterator == null) {
7206            return false;
7207        }
7208        int current = getAccessibilitySelectionEnd();
7209        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7210            current = forward ? 0 : text.length();
7211        }
7212        final int[] range = forward ? iterator.following(current) : iterator.preceding(current);
7213        if (range == null) {
7214            return false;
7215        }
7216        final int segmentStart = range[0];
7217        final int segmentEnd = range[1];
7218        int selectionStart;
7219        int selectionEnd;
7220        if (extendSelection && isAccessibilitySelectionExtendable()) {
7221            selectionStart = getAccessibilitySelectionStart();
7222            if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7223                selectionStart = forward ? segmentStart : segmentEnd;
7224            }
7225            selectionEnd = forward ? segmentEnd : segmentStart;
7226        } else {
7227            selectionStart = selectionEnd= forward ? segmentEnd : segmentStart;
7228        }
7229        setAccessibilitySelection(selectionStart, selectionEnd);
7230        final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY
7231                : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY;
7232        sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd);
7233        return true;
7234    }
7235
7236    /**
7237     * Gets the text reported for accessibility purposes.
7238     *
7239     * @return The accessibility text.
7240     *
7241     * @hide
7242     */
7243    public CharSequence getIterableTextForAccessibility() {
7244        return getContentDescription();
7245    }
7246
7247    /**
7248     * Gets whether accessibility selection can be extended.
7249     *
7250     * @return If selection is extensible.
7251     *
7252     * @hide
7253     */
7254    public boolean isAccessibilitySelectionExtendable() {
7255        return false;
7256    }
7257
7258    /**
7259     * @hide
7260     */
7261    public int getAccessibilitySelectionStart() {
7262        return mAccessibilityCursorPosition;
7263    }
7264
7265    /**
7266     * @hide
7267     */
7268    public int getAccessibilitySelectionEnd() {
7269        return getAccessibilitySelectionStart();
7270    }
7271
7272    /**
7273     * @hide
7274     */
7275    public void setAccessibilitySelection(int start, int end) {
7276        if (start ==  end && end == mAccessibilityCursorPosition) {
7277            return;
7278        }
7279        if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) {
7280            mAccessibilityCursorPosition = start;
7281        } else {
7282            mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
7283        }
7284        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
7285    }
7286
7287    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
7288            int fromIndex, int toIndex) {
7289        if (mParent == null) {
7290            return;
7291        }
7292        AccessibilityEvent event = AccessibilityEvent.obtain(
7293                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
7294        onInitializeAccessibilityEvent(event);
7295        onPopulateAccessibilityEvent(event);
7296        event.setFromIndex(fromIndex);
7297        event.setToIndex(toIndex);
7298        event.setAction(action);
7299        event.setMovementGranularity(granularity);
7300        mParent.requestSendAccessibilityEvent(this, event);
7301    }
7302
7303    /**
7304     * @hide
7305     */
7306    public TextSegmentIterator getIteratorForGranularity(int granularity) {
7307        switch (granularity) {
7308            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
7309                CharSequence text = getIterableTextForAccessibility();
7310                if (text != null && text.length() > 0) {
7311                    CharacterTextSegmentIterator iterator =
7312                        CharacterTextSegmentIterator.getInstance(
7313                                mContext.getResources().getConfiguration().locale);
7314                    iterator.initialize(text.toString());
7315                    return iterator;
7316                }
7317            } break;
7318            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
7319                CharSequence text = getIterableTextForAccessibility();
7320                if (text != null && text.length() > 0) {
7321                    WordTextSegmentIterator iterator =
7322                        WordTextSegmentIterator.getInstance(
7323                                mContext.getResources().getConfiguration().locale);
7324                    iterator.initialize(text.toString());
7325                    return iterator;
7326                }
7327            } break;
7328            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
7329                CharSequence text = getIterableTextForAccessibility();
7330                if (text != null && text.length() > 0) {
7331                    ParagraphTextSegmentIterator iterator =
7332                        ParagraphTextSegmentIterator.getInstance();
7333                    iterator.initialize(text.toString());
7334                    return iterator;
7335                }
7336            } break;
7337        }
7338        return null;
7339    }
7340
7341    /**
7342     * @hide
7343     */
7344    public void dispatchStartTemporaryDetach() {
7345        clearAccessibilityFocus();
7346        clearDisplayList();
7347
7348        onStartTemporaryDetach();
7349    }
7350
7351    /**
7352     * This is called when a container is going to temporarily detach a child, with
7353     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
7354     * It will either be followed by {@link #onFinishTemporaryDetach()} or
7355     * {@link #onDetachedFromWindow()} when the container is done.
7356     */
7357    public void onStartTemporaryDetach() {
7358        removeUnsetPressCallback();
7359        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
7360    }
7361
7362    /**
7363     * @hide
7364     */
7365    public void dispatchFinishTemporaryDetach() {
7366        onFinishTemporaryDetach();
7367    }
7368
7369    /**
7370     * Called after {@link #onStartTemporaryDetach} when the container is done
7371     * changing the view.
7372     */
7373    public void onFinishTemporaryDetach() {
7374    }
7375
7376    /**
7377     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
7378     * for this view's window.  Returns null if the view is not currently attached
7379     * to the window.  Normally you will not need to use this directly, but
7380     * just use the standard high-level event callbacks like
7381     * {@link #onKeyDown(int, KeyEvent)}.
7382     */
7383    public KeyEvent.DispatcherState getKeyDispatcherState() {
7384        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
7385    }
7386
7387    /**
7388     * Dispatch a key event before it is processed by any input method
7389     * associated with the view hierarchy.  This can be used to intercept
7390     * key events in special situations before the IME consumes them; a
7391     * typical example would be handling the BACK key to update the application's
7392     * UI instead of allowing the IME to see it and close itself.
7393     *
7394     * @param event The key event to be dispatched.
7395     * @return True if the event was handled, false otherwise.
7396     */
7397    public boolean dispatchKeyEventPreIme(KeyEvent event) {
7398        return onKeyPreIme(event.getKeyCode(), event);
7399    }
7400
7401    /**
7402     * Dispatch a key event to the next view on the focus path. This path runs
7403     * from the top of the view tree down to the currently focused view. If this
7404     * view has focus, it will dispatch to itself. Otherwise it will dispatch
7405     * the next node down the focus path. This method also fires any key
7406     * listeners.
7407     *
7408     * @param event The key event to be dispatched.
7409     * @return True if the event was handled, false otherwise.
7410     */
7411    public boolean dispatchKeyEvent(KeyEvent event) {
7412        if (mInputEventConsistencyVerifier != null) {
7413            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
7414        }
7415
7416        // Give any attached key listener a first crack at the event.
7417        //noinspection SimplifiableIfStatement
7418        ListenerInfo li = mListenerInfo;
7419        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
7420                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
7421            return true;
7422        }
7423
7424        if (event.dispatch(this, mAttachInfo != null
7425                ? mAttachInfo.mKeyDispatchState : null, this)) {
7426            return true;
7427        }
7428
7429        if (mInputEventConsistencyVerifier != null) {
7430            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7431        }
7432        return false;
7433    }
7434
7435    /**
7436     * Dispatches a key shortcut event.
7437     *
7438     * @param event The key event to be dispatched.
7439     * @return True if the event was handled by the view, false otherwise.
7440     */
7441    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
7442        return onKeyShortcut(event.getKeyCode(), event);
7443    }
7444
7445    /**
7446     * Pass the touch screen motion event down to the target view, or this
7447     * view if it is the target.
7448     *
7449     * @param event The motion event to be dispatched.
7450     * @return True if the event was handled by the view, false otherwise.
7451     */
7452    public boolean dispatchTouchEvent(MotionEvent event) {
7453        if (mInputEventConsistencyVerifier != null) {
7454            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
7455        }
7456
7457        if (onFilterTouchEventForSecurity(event)) {
7458            //noinspection SimplifiableIfStatement
7459            ListenerInfo li = mListenerInfo;
7460            if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
7461                    && li.mOnTouchListener.onTouch(this, event)) {
7462                return true;
7463            }
7464
7465            if (onTouchEvent(event)) {
7466                return true;
7467            }
7468        }
7469
7470        if (mInputEventConsistencyVerifier != null) {
7471            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7472        }
7473        return false;
7474    }
7475
7476    /**
7477     * Filter the touch event to apply security policies.
7478     *
7479     * @param event The motion event to be filtered.
7480     * @return True if the event should be dispatched, false if the event should be dropped.
7481     *
7482     * @see #getFilterTouchesWhenObscured
7483     */
7484    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
7485        //noinspection RedundantIfStatement
7486        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
7487                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
7488            // Window is obscured, drop this touch.
7489            return false;
7490        }
7491        return true;
7492    }
7493
7494    /**
7495     * Pass a trackball motion event down to the focused view.
7496     *
7497     * @param event The motion event to be dispatched.
7498     * @return True if the event was handled by the view, false otherwise.
7499     */
7500    public boolean dispatchTrackballEvent(MotionEvent event) {
7501        if (mInputEventConsistencyVerifier != null) {
7502            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
7503        }
7504
7505        return onTrackballEvent(event);
7506    }
7507
7508    /**
7509     * Dispatch a generic motion event.
7510     * <p>
7511     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
7512     * are delivered to the view under the pointer.  All other generic motion events are
7513     * delivered to the focused view.  Hover events are handled specially and are delivered
7514     * to {@link #onHoverEvent(MotionEvent)}.
7515     * </p>
7516     *
7517     * @param event The motion event to be dispatched.
7518     * @return True if the event was handled by the view, false otherwise.
7519     */
7520    public boolean dispatchGenericMotionEvent(MotionEvent event) {
7521        if (mInputEventConsistencyVerifier != null) {
7522            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
7523        }
7524
7525        final int source = event.getSource();
7526        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
7527            final int action = event.getAction();
7528            if (action == MotionEvent.ACTION_HOVER_ENTER
7529                    || action == MotionEvent.ACTION_HOVER_MOVE
7530                    || action == MotionEvent.ACTION_HOVER_EXIT) {
7531                if (dispatchHoverEvent(event)) {
7532                    return true;
7533                }
7534            } else if (dispatchGenericPointerEvent(event)) {
7535                return true;
7536            }
7537        } else if (dispatchGenericFocusedEvent(event)) {
7538            return true;
7539        }
7540
7541        if (dispatchGenericMotionEventInternal(event)) {
7542            return true;
7543        }
7544
7545        if (mInputEventConsistencyVerifier != null) {
7546            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7547        }
7548        return false;
7549    }
7550
7551    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
7552        //noinspection SimplifiableIfStatement
7553        ListenerInfo li = mListenerInfo;
7554        if (li != null && li.mOnGenericMotionListener != null
7555                && (mViewFlags & ENABLED_MASK) == ENABLED
7556                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
7557            return true;
7558        }
7559
7560        if (onGenericMotionEvent(event)) {
7561            return true;
7562        }
7563
7564        if (mInputEventConsistencyVerifier != null) {
7565            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7566        }
7567        return false;
7568    }
7569
7570    /**
7571     * Dispatch a hover event.
7572     * <p>
7573     * Do not call this method directly.
7574     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7575     * </p>
7576     *
7577     * @param event The motion event to be dispatched.
7578     * @return True if the event was handled by the view, false otherwise.
7579     */
7580    protected boolean dispatchHoverEvent(MotionEvent event) {
7581        ListenerInfo li = mListenerInfo;
7582        //noinspection SimplifiableIfStatement
7583        if (li != null && li.mOnHoverListener != null
7584                && (mViewFlags & ENABLED_MASK) == ENABLED
7585                && li.mOnHoverListener.onHover(this, event)) {
7586            return true;
7587        }
7588
7589        return onHoverEvent(event);
7590    }
7591
7592    /**
7593     * Returns true if the view has a child to which it has recently sent
7594     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
7595     * it does not have a hovered child, then it must be the innermost hovered view.
7596     * @hide
7597     */
7598    protected boolean hasHoveredChild() {
7599        return false;
7600    }
7601
7602    /**
7603     * Dispatch a generic motion event to the view under the first pointer.
7604     * <p>
7605     * Do not call this method directly.
7606     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7607     * </p>
7608     *
7609     * @param event The motion event to be dispatched.
7610     * @return True if the event was handled by the view, false otherwise.
7611     */
7612    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
7613        return false;
7614    }
7615
7616    /**
7617     * Dispatch a generic motion event to the currently focused view.
7618     * <p>
7619     * Do not call this method directly.
7620     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7621     * </p>
7622     *
7623     * @param event The motion event to be dispatched.
7624     * @return True if the event was handled by the view, false otherwise.
7625     */
7626    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
7627        return false;
7628    }
7629
7630    /**
7631     * Dispatch a pointer event.
7632     * <p>
7633     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
7634     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
7635     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
7636     * and should not be expected to handle other pointing device features.
7637     * </p>
7638     *
7639     * @param event The motion event to be dispatched.
7640     * @return True if the event was handled by the view, false otherwise.
7641     * @hide
7642     */
7643    public final boolean dispatchPointerEvent(MotionEvent event) {
7644        if (event.isTouchEvent()) {
7645            return dispatchTouchEvent(event);
7646        } else {
7647            return dispatchGenericMotionEvent(event);
7648        }
7649    }
7650
7651    /**
7652     * Called when the window containing this view gains or loses window focus.
7653     * ViewGroups should override to route to their children.
7654     *
7655     * @param hasFocus True if the window containing this view now has focus,
7656     *        false otherwise.
7657     */
7658    public void dispatchWindowFocusChanged(boolean hasFocus) {
7659        onWindowFocusChanged(hasFocus);
7660    }
7661
7662    /**
7663     * Called when the window containing this view gains or loses focus.  Note
7664     * that this is separate from view focus: to receive key events, both
7665     * your view and its window must have focus.  If a window is displayed
7666     * on top of yours that takes input focus, then your own window will lose
7667     * focus but the view focus will remain unchanged.
7668     *
7669     * @param hasWindowFocus True if the window containing this view now has
7670     *        focus, false otherwise.
7671     */
7672    public void onWindowFocusChanged(boolean hasWindowFocus) {
7673        InputMethodManager imm = InputMethodManager.peekInstance();
7674        if (!hasWindowFocus) {
7675            if (isPressed()) {
7676                setPressed(false);
7677            }
7678            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
7679                imm.focusOut(this);
7680            }
7681            removeLongPressCallback();
7682            removeTapCallback();
7683            onFocusLost();
7684        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
7685            imm.focusIn(this);
7686        }
7687        refreshDrawableState();
7688    }
7689
7690    /**
7691     * Returns true if this view is in a window that currently has window focus.
7692     * Note that this is not the same as the view itself having focus.
7693     *
7694     * @return True if this view is in a window that currently has window focus.
7695     */
7696    public boolean hasWindowFocus() {
7697        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
7698    }
7699
7700    /**
7701     * Dispatch a view visibility change down the view hierarchy.
7702     * ViewGroups should override to route to their children.
7703     * @param changedView The view whose visibility changed. Could be 'this' or
7704     * an ancestor view.
7705     * @param visibility The new visibility of changedView: {@link #VISIBLE},
7706     * {@link #INVISIBLE} or {@link #GONE}.
7707     */
7708    protected void dispatchVisibilityChanged(View changedView, int visibility) {
7709        onVisibilityChanged(changedView, visibility);
7710    }
7711
7712    /**
7713     * Called when the visibility of the view or an ancestor of the view is changed.
7714     * @param changedView The view whose visibility changed. Could be 'this' or
7715     * an ancestor view.
7716     * @param visibility The new visibility of changedView: {@link #VISIBLE},
7717     * {@link #INVISIBLE} or {@link #GONE}.
7718     */
7719    protected void onVisibilityChanged(View changedView, int visibility) {
7720        if (visibility == VISIBLE) {
7721            if (mAttachInfo != null) {
7722                initialAwakenScrollBars();
7723            } else {
7724                mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
7725            }
7726        }
7727    }
7728
7729    /**
7730     * Dispatch a hint about whether this view is displayed. For instance, when
7731     * a View moves out of the screen, it might receives a display hint indicating
7732     * the view is not displayed. Applications should not <em>rely</em> on this hint
7733     * as there is no guarantee that they will receive one.
7734     *
7735     * @param hint A hint about whether or not this view is displayed:
7736     * {@link #VISIBLE} or {@link #INVISIBLE}.
7737     */
7738    public void dispatchDisplayHint(int hint) {
7739        onDisplayHint(hint);
7740    }
7741
7742    /**
7743     * Gives this view a hint about whether is displayed or not. For instance, when
7744     * a View moves out of the screen, it might receives a display hint indicating
7745     * the view is not displayed. Applications should not <em>rely</em> on this hint
7746     * as there is no guarantee that they will receive one.
7747     *
7748     * @param hint A hint about whether or not this view is displayed:
7749     * {@link #VISIBLE} or {@link #INVISIBLE}.
7750     */
7751    protected void onDisplayHint(int hint) {
7752    }
7753
7754    /**
7755     * Dispatch a window visibility change down the view hierarchy.
7756     * ViewGroups should override to route to their children.
7757     *
7758     * @param visibility The new visibility of the window.
7759     *
7760     * @see #onWindowVisibilityChanged(int)
7761     */
7762    public void dispatchWindowVisibilityChanged(int visibility) {
7763        onWindowVisibilityChanged(visibility);
7764    }
7765
7766    /**
7767     * Called when the window containing has change its visibility
7768     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
7769     * that this tells you whether or not your window is being made visible
7770     * to the window manager; this does <em>not</em> tell you whether or not
7771     * your window is obscured by other windows on the screen, even if it
7772     * is itself visible.
7773     *
7774     * @param visibility The new visibility of the window.
7775     */
7776    protected void onWindowVisibilityChanged(int visibility) {
7777        if (visibility == VISIBLE) {
7778            initialAwakenScrollBars();
7779        }
7780    }
7781
7782    /**
7783     * Returns the current visibility of the window this view is attached to
7784     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
7785     *
7786     * @return Returns the current visibility of the view's window.
7787     */
7788    public int getWindowVisibility() {
7789        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
7790    }
7791
7792    /**
7793     * Retrieve the overall visible display size in which the window this view is
7794     * attached to has been positioned in.  This takes into account screen
7795     * decorations above the window, for both cases where the window itself
7796     * is being position inside of them or the window is being placed under
7797     * then and covered insets are used for the window to position its content
7798     * inside.  In effect, this tells you the available area where content can
7799     * be placed and remain visible to users.
7800     *
7801     * <p>This function requires an IPC back to the window manager to retrieve
7802     * the requested information, so should not be used in performance critical
7803     * code like drawing.
7804     *
7805     * @param outRect Filled in with the visible display frame.  If the view
7806     * is not attached to a window, this is simply the raw display size.
7807     */
7808    public void getWindowVisibleDisplayFrame(Rect outRect) {
7809        if (mAttachInfo != null) {
7810            try {
7811                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
7812            } catch (RemoteException e) {
7813                return;
7814            }
7815            // XXX This is really broken, and probably all needs to be done
7816            // in the window manager, and we need to know more about whether
7817            // we want the area behind or in front of the IME.
7818            final Rect insets = mAttachInfo.mVisibleInsets;
7819            outRect.left += insets.left;
7820            outRect.top += insets.top;
7821            outRect.right -= insets.right;
7822            outRect.bottom -= insets.bottom;
7823            return;
7824        }
7825        // The view is not attached to a display so we don't have a context.
7826        // Make a best guess about the display size.
7827        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
7828        d.getRectSize(outRect);
7829    }
7830
7831    /**
7832     * Dispatch a notification about a resource configuration change down
7833     * the view hierarchy.
7834     * ViewGroups should override to route to their children.
7835     *
7836     * @param newConfig The new resource configuration.
7837     *
7838     * @see #onConfigurationChanged(android.content.res.Configuration)
7839     */
7840    public void dispatchConfigurationChanged(Configuration newConfig) {
7841        onConfigurationChanged(newConfig);
7842    }
7843
7844    /**
7845     * Called when the current configuration of the resources being used
7846     * by the application have changed.  You can use this to decide when
7847     * to reload resources that can changed based on orientation and other
7848     * configuration characterstics.  You only need to use this if you are
7849     * not relying on the normal {@link android.app.Activity} mechanism of
7850     * recreating the activity instance upon a configuration change.
7851     *
7852     * @param newConfig The new resource configuration.
7853     */
7854    protected void onConfigurationChanged(Configuration newConfig) {
7855    }
7856
7857    /**
7858     * Private function to aggregate all per-view attributes in to the view
7859     * root.
7860     */
7861    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
7862        performCollectViewAttributes(attachInfo, visibility);
7863    }
7864
7865    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
7866        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
7867            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
7868                attachInfo.mKeepScreenOn = true;
7869            }
7870            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
7871            ListenerInfo li = mListenerInfo;
7872            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
7873                attachInfo.mHasSystemUiListeners = true;
7874            }
7875        }
7876    }
7877
7878    void needGlobalAttributesUpdate(boolean force) {
7879        final AttachInfo ai = mAttachInfo;
7880        if (ai != null && !ai.mRecomputeGlobalAttributes) {
7881            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
7882                    || ai.mHasSystemUiListeners) {
7883                ai.mRecomputeGlobalAttributes = true;
7884            }
7885        }
7886    }
7887
7888    /**
7889     * Returns whether the device is currently in touch mode.  Touch mode is entered
7890     * once the user begins interacting with the device by touch, and affects various
7891     * things like whether focus is always visible to the user.
7892     *
7893     * @return Whether the device is in touch mode.
7894     */
7895    @ViewDebug.ExportedProperty
7896    public boolean isInTouchMode() {
7897        if (mAttachInfo != null) {
7898            return mAttachInfo.mInTouchMode;
7899        } else {
7900            return ViewRootImpl.isInTouchMode();
7901        }
7902    }
7903
7904    /**
7905     * Returns the context the view is running in, through which it can
7906     * access the current theme, resources, etc.
7907     *
7908     * @return The view's Context.
7909     */
7910    @ViewDebug.CapturedViewProperty
7911    public final Context getContext() {
7912        return mContext;
7913    }
7914
7915    /**
7916     * Handle a key event before it is processed by any input method
7917     * associated with the view hierarchy.  This can be used to intercept
7918     * key events in special situations before the IME consumes them; a
7919     * typical example would be handling the BACK key to update the application's
7920     * UI instead of allowing the IME to see it and close itself.
7921     *
7922     * @param keyCode The value in event.getKeyCode().
7923     * @param event Description of the key event.
7924     * @return If you handled the event, return true. If you want to allow the
7925     *         event to be handled by the next receiver, return false.
7926     */
7927    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
7928        return false;
7929    }
7930
7931    /**
7932     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
7933     * KeyEvent.Callback.onKeyDown()}: perform press of the view
7934     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
7935     * is released, if the view is enabled and clickable.
7936     *
7937     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7938     * although some may elect to do so in some situations. Do not rely on this to
7939     * catch software key presses.
7940     *
7941     * @param keyCode A key code that represents the button pressed, from
7942     *                {@link android.view.KeyEvent}.
7943     * @param event   The KeyEvent object that defines the button action.
7944     */
7945    public boolean onKeyDown(int keyCode, KeyEvent event) {
7946        boolean result = false;
7947
7948        if (KeyEvent.isConfirmKey(event.getKeyCode())) {
7949            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7950                return true;
7951            }
7952            // Long clickable items don't necessarily have to be clickable
7953            if (((mViewFlags & CLICKABLE) == CLICKABLE ||
7954                    (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
7955                    (event.getRepeatCount() == 0)) {
7956                setPressed(true);
7957                checkForLongClick(0);
7958                return true;
7959            }
7960        }
7961        return result;
7962    }
7963
7964    /**
7965     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
7966     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
7967     * the event).
7968     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7969     * although some may elect to do so in some situations. Do not rely on this to
7970     * catch software key presses.
7971     */
7972    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
7973        return false;
7974    }
7975
7976    /**
7977     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
7978     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
7979     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
7980     * {@link KeyEvent#KEYCODE_ENTER} is released.
7981     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7982     * although some may elect to do so in some situations. Do not rely on this to
7983     * catch software key presses.
7984     *
7985     * @param keyCode A key code that represents the button pressed, from
7986     *                {@link android.view.KeyEvent}.
7987     * @param event   The KeyEvent object that defines the button action.
7988     */
7989    public boolean onKeyUp(int keyCode, KeyEvent event) {
7990        boolean result = false;
7991
7992        switch (keyCode) {
7993            case KeyEvent.KEYCODE_DPAD_CENTER:
7994            case KeyEvent.KEYCODE_ENTER: {
7995                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7996                    return true;
7997                }
7998                if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
7999                    setPressed(false);
8000
8001                    if (!mHasPerformedLongPress) {
8002                        // This is a tap, so remove the longpress check
8003                        removeLongPressCallback();
8004
8005                        result = performClick();
8006                    }
8007                }
8008                break;
8009            }
8010        }
8011        return result;
8012    }
8013
8014    /**
8015     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
8016     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
8017     * the event).
8018     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8019     * although some may elect to do so in some situations. Do not rely on this to
8020     * catch software key presses.
8021     *
8022     * @param keyCode     A key code that represents the button pressed, from
8023     *                    {@link android.view.KeyEvent}.
8024     * @param repeatCount The number of times the action was made.
8025     * @param event       The KeyEvent object that defines the button action.
8026     */
8027    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
8028        return false;
8029    }
8030
8031    /**
8032     * Called on the focused view when a key shortcut event is not handled.
8033     * Override this method to implement local key shortcuts for the View.
8034     * Key shortcuts can also be implemented by setting the
8035     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
8036     *
8037     * @param keyCode The value in event.getKeyCode().
8038     * @param event Description of the key event.
8039     * @return If you handled the event, return true. If you want to allow the
8040     *         event to be handled by the next receiver, return false.
8041     */
8042    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
8043        return false;
8044    }
8045
8046    /**
8047     * Check whether the called view is a text editor, in which case it
8048     * would make sense to automatically display a soft input window for
8049     * it.  Subclasses should override this if they implement
8050     * {@link #onCreateInputConnection(EditorInfo)} to return true if
8051     * a call on that method would return a non-null InputConnection, and
8052     * they are really a first-class editor that the user would normally
8053     * start typing on when the go into a window containing your view.
8054     *
8055     * <p>The default implementation always returns false.  This does
8056     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
8057     * will not be called or the user can not otherwise perform edits on your
8058     * view; it is just a hint to the system that this is not the primary
8059     * purpose of this view.
8060     *
8061     * @return Returns true if this view is a text editor, else false.
8062     */
8063    public boolean onCheckIsTextEditor() {
8064        return false;
8065    }
8066
8067    /**
8068     * Create a new InputConnection for an InputMethod to interact
8069     * with the view.  The default implementation returns null, since it doesn't
8070     * support input methods.  You can override this to implement such support.
8071     * This is only needed for views that take focus and text input.
8072     *
8073     * <p>When implementing this, you probably also want to implement
8074     * {@link #onCheckIsTextEditor()} to indicate you will return a
8075     * non-null InputConnection.
8076     *
8077     * @param outAttrs Fill in with attribute information about the connection.
8078     */
8079    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
8080        return null;
8081    }
8082
8083    /**
8084     * Called by the {@link android.view.inputmethod.InputMethodManager}
8085     * when a view who is not the current
8086     * input connection target is trying to make a call on the manager.  The
8087     * default implementation returns false; you can override this to return
8088     * true for certain views if you are performing InputConnection proxying
8089     * to them.
8090     * @param view The View that is making the InputMethodManager call.
8091     * @return Return true to allow the call, false to reject.
8092     */
8093    public boolean checkInputConnectionProxy(View view) {
8094        return false;
8095    }
8096
8097    /**
8098     * Show the context menu for this view. It is not safe to hold on to the
8099     * menu after returning from this method.
8100     *
8101     * You should normally not overload this method. Overload
8102     * {@link #onCreateContextMenu(ContextMenu)} or define an
8103     * {@link OnCreateContextMenuListener} to add items to the context menu.
8104     *
8105     * @param menu The context menu to populate
8106     */
8107    public void createContextMenu(ContextMenu menu) {
8108        ContextMenuInfo menuInfo = getContextMenuInfo();
8109
8110        // Sets the current menu info so all items added to menu will have
8111        // my extra info set.
8112        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
8113
8114        onCreateContextMenu(menu);
8115        ListenerInfo li = mListenerInfo;
8116        if (li != null && li.mOnCreateContextMenuListener != null) {
8117            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
8118        }
8119
8120        // Clear the extra information so subsequent items that aren't mine don't
8121        // have my extra info.
8122        ((MenuBuilder)menu).setCurrentMenuInfo(null);
8123
8124        if (mParent != null) {
8125            mParent.createContextMenu(menu);
8126        }
8127    }
8128
8129    /**
8130     * Views should implement this if they have extra information to associate
8131     * with the context menu. The return result is supplied as a parameter to
8132     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
8133     * callback.
8134     *
8135     * @return Extra information about the item for which the context menu
8136     *         should be shown. This information will vary across different
8137     *         subclasses of View.
8138     */
8139    protected ContextMenuInfo getContextMenuInfo() {
8140        return null;
8141    }
8142
8143    /**
8144     * Views should implement this if the view itself is going to add items to
8145     * the context menu.
8146     *
8147     * @param menu the context menu to populate
8148     */
8149    protected void onCreateContextMenu(ContextMenu menu) {
8150    }
8151
8152    /**
8153     * Implement this method to handle trackball motion events.  The
8154     * <em>relative</em> movement of the trackball since the last event
8155     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
8156     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
8157     * that a movement of 1 corresponds to the user pressing one DPAD key (so
8158     * they will often be fractional values, representing the more fine-grained
8159     * movement information available from a trackball).
8160     *
8161     * @param event The motion event.
8162     * @return True if the event was handled, false otherwise.
8163     */
8164    public boolean onTrackballEvent(MotionEvent event) {
8165        return false;
8166    }
8167
8168    /**
8169     * Implement this method to handle generic motion events.
8170     * <p>
8171     * Generic motion events describe joystick movements, mouse hovers, track pad
8172     * touches, scroll wheel movements and other input events.  The
8173     * {@link MotionEvent#getSource() source} of the motion event specifies
8174     * the class of input that was received.  Implementations of this method
8175     * must examine the bits in the source before processing the event.
8176     * The following code example shows how this is done.
8177     * </p><p>
8178     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
8179     * are delivered to the view under the pointer.  All other generic motion events are
8180     * delivered to the focused view.
8181     * </p>
8182     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
8183     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {
8184     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
8185     *             // process the joystick movement...
8186     *             return true;
8187     *         }
8188     *     }
8189     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
8190     *         switch (event.getAction()) {
8191     *             case MotionEvent.ACTION_HOVER_MOVE:
8192     *                 // process the mouse hover movement...
8193     *                 return true;
8194     *             case MotionEvent.ACTION_SCROLL:
8195     *                 // process the scroll wheel movement...
8196     *                 return true;
8197     *         }
8198     *     }
8199     *     return super.onGenericMotionEvent(event);
8200     * }</pre>
8201     *
8202     * @param event The generic motion event being processed.
8203     * @return True if the event was handled, false otherwise.
8204     */
8205    public boolean onGenericMotionEvent(MotionEvent event) {
8206        return false;
8207    }
8208
8209    /**
8210     * Implement this method to handle hover events.
8211     * <p>
8212     * This method is called whenever a pointer is hovering into, over, or out of the
8213     * bounds of a view and the view is not currently being touched.
8214     * Hover events are represented as pointer events with action
8215     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
8216     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
8217     * </p>
8218     * <ul>
8219     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
8220     * when the pointer enters the bounds of the view.</li>
8221     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
8222     * when the pointer has already entered the bounds of the view and has moved.</li>
8223     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
8224     * when the pointer has exited the bounds of the view or when the pointer is
8225     * about to go down due to a button click, tap, or similar user action that
8226     * causes the view to be touched.</li>
8227     * </ul>
8228     * <p>
8229     * The view should implement this method to return true to indicate that it is
8230     * handling the hover event, such as by changing its drawable state.
8231     * </p><p>
8232     * The default implementation calls {@link #setHovered} to update the hovered state
8233     * of the view when a hover enter or hover exit event is received, if the view
8234     * is enabled and is clickable.  The default implementation also sends hover
8235     * accessibility events.
8236     * </p>
8237     *
8238     * @param event The motion event that describes the hover.
8239     * @return True if the view handled the hover event.
8240     *
8241     * @see #isHovered
8242     * @see #setHovered
8243     * @see #onHoverChanged
8244     */
8245    public boolean onHoverEvent(MotionEvent event) {
8246        // The root view may receive hover (or touch) events that are outside the bounds of
8247        // the window.  This code ensures that we only send accessibility events for
8248        // hovers that are actually within the bounds of the root view.
8249        final int action = event.getActionMasked();
8250        if (!mSendingHoverAccessibilityEvents) {
8251            if ((action == MotionEvent.ACTION_HOVER_ENTER
8252                    || action == MotionEvent.ACTION_HOVER_MOVE)
8253                    && !hasHoveredChild()
8254                    && pointInView(event.getX(), event.getY())) {
8255                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
8256                mSendingHoverAccessibilityEvents = true;
8257            }
8258        } else {
8259            if (action == MotionEvent.ACTION_HOVER_EXIT
8260                    || (action == MotionEvent.ACTION_MOVE
8261                            && !pointInView(event.getX(), event.getY()))) {
8262                mSendingHoverAccessibilityEvents = false;
8263                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
8264                // If the window does not have input focus we take away accessibility
8265                // focus as soon as the user stop hovering over the view.
8266                if (mAttachInfo != null && !mAttachInfo.mHasWindowFocus) {
8267                    getViewRootImpl().setAccessibilityFocus(null, null);
8268                }
8269            }
8270        }
8271
8272        if (isHoverable()) {
8273            switch (action) {
8274                case MotionEvent.ACTION_HOVER_ENTER:
8275                    setHovered(true);
8276                    break;
8277                case MotionEvent.ACTION_HOVER_EXIT:
8278                    setHovered(false);
8279                    break;
8280            }
8281
8282            // Dispatch the event to onGenericMotionEvent before returning true.
8283            // This is to provide compatibility with existing applications that
8284            // handled HOVER_MOVE events in onGenericMotionEvent and that would
8285            // break because of the new default handling for hoverable views
8286            // in onHoverEvent.
8287            // Note that onGenericMotionEvent will be called by default when
8288            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
8289            dispatchGenericMotionEventInternal(event);
8290            // The event was already handled by calling setHovered(), so always
8291            // return true.
8292            return true;
8293        }
8294
8295        return false;
8296    }
8297
8298    /**
8299     * Returns true if the view should handle {@link #onHoverEvent}
8300     * by calling {@link #setHovered} to change its hovered state.
8301     *
8302     * @return True if the view is hoverable.
8303     */
8304    private boolean isHoverable() {
8305        final int viewFlags = mViewFlags;
8306        if ((viewFlags & ENABLED_MASK) == DISABLED) {
8307            return false;
8308        }
8309
8310        return (viewFlags & CLICKABLE) == CLICKABLE
8311                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
8312    }
8313
8314    /**
8315     * Returns true if the view is currently hovered.
8316     *
8317     * @return True if the view is currently hovered.
8318     *
8319     * @see #setHovered
8320     * @see #onHoverChanged
8321     */
8322    @ViewDebug.ExportedProperty
8323    public boolean isHovered() {
8324        return (mPrivateFlags & PFLAG_HOVERED) != 0;
8325    }
8326
8327    /**
8328     * Sets whether the view is currently hovered.
8329     * <p>
8330     * Calling this method also changes the drawable state of the view.  This
8331     * enables the view to react to hover by using different drawable resources
8332     * to change its appearance.
8333     * </p><p>
8334     * The {@link #onHoverChanged} method is called when the hovered state changes.
8335     * </p>
8336     *
8337     * @param hovered True if the view is hovered.
8338     *
8339     * @see #isHovered
8340     * @see #onHoverChanged
8341     */
8342    public void setHovered(boolean hovered) {
8343        if (hovered) {
8344            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
8345                mPrivateFlags |= PFLAG_HOVERED;
8346                refreshDrawableState();
8347                onHoverChanged(true);
8348            }
8349        } else {
8350            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
8351                mPrivateFlags &= ~PFLAG_HOVERED;
8352                refreshDrawableState();
8353                onHoverChanged(false);
8354            }
8355        }
8356    }
8357
8358    /**
8359     * Implement this method to handle hover state changes.
8360     * <p>
8361     * This method is called whenever the hover state changes as a result of a
8362     * call to {@link #setHovered}.
8363     * </p>
8364     *
8365     * @param hovered The current hover state, as returned by {@link #isHovered}.
8366     *
8367     * @see #isHovered
8368     * @see #setHovered
8369     */
8370    public void onHoverChanged(boolean hovered) {
8371    }
8372
8373    /**
8374     * Implement this method to handle touch screen motion events.
8375     *
8376     * @param event The motion event.
8377     * @return True if the event was handled, false otherwise.
8378     */
8379    public boolean onTouchEvent(MotionEvent event) {
8380        final int viewFlags = mViewFlags;
8381
8382        if ((viewFlags & ENABLED_MASK) == DISABLED) {
8383            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
8384                setPressed(false);
8385            }
8386            // A disabled view that is clickable still consumes the touch
8387            // events, it just doesn't respond to them.
8388            return (((viewFlags & CLICKABLE) == CLICKABLE ||
8389                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
8390        }
8391
8392        if (mTouchDelegate != null) {
8393            if (mTouchDelegate.onTouchEvent(event)) {
8394                return true;
8395            }
8396        }
8397
8398        if (((viewFlags & CLICKABLE) == CLICKABLE ||
8399                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
8400            switch (event.getAction()) {
8401                case MotionEvent.ACTION_UP:
8402                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
8403                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
8404                        // take focus if we don't have it already and we should in
8405                        // touch mode.
8406                        boolean focusTaken = false;
8407                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
8408                            focusTaken = requestFocus();
8409                        }
8410
8411                        if (prepressed) {
8412                            // The button is being released before we actually
8413                            // showed it as pressed.  Make it show the pressed
8414                            // state now (before scheduling the click) to ensure
8415                            // the user sees it.
8416                            setPressed(true);
8417                       }
8418
8419                        if (!mHasPerformedLongPress) {
8420                            // This is a tap, so remove the longpress check
8421                            removeLongPressCallback();
8422
8423                            // Only perform take click actions if we were in the pressed state
8424                            if (!focusTaken) {
8425                                // Use a Runnable and post this rather than calling
8426                                // performClick directly. This lets other visual state
8427                                // of the view update before click actions start.
8428                                if (mPerformClick == null) {
8429                                    mPerformClick = new PerformClick();
8430                                }
8431                                if (!post(mPerformClick)) {
8432                                    performClick();
8433                                }
8434                            }
8435                        }
8436
8437                        if (mUnsetPressedState == null) {
8438                            mUnsetPressedState = new UnsetPressedState();
8439                        }
8440
8441                        if (prepressed) {
8442                            postDelayed(mUnsetPressedState,
8443                                    ViewConfiguration.getPressedStateDuration());
8444                        } else if (!post(mUnsetPressedState)) {
8445                            // If the post failed, unpress right now
8446                            mUnsetPressedState.run();
8447                        }
8448                        removeTapCallback();
8449                    }
8450                    break;
8451
8452                case MotionEvent.ACTION_DOWN:
8453                    mHasPerformedLongPress = false;
8454
8455                    if (performButtonActionOnTouchDown(event)) {
8456                        break;
8457                    }
8458
8459                    // Walk up the hierarchy to determine if we're inside a scrolling container.
8460                    boolean isInScrollingContainer = isInScrollingContainer();
8461
8462                    // For views inside a scrolling container, delay the pressed feedback for
8463                    // a short period in case this is a scroll.
8464                    if (isInScrollingContainer) {
8465                        mPrivateFlags |= PFLAG_PREPRESSED;
8466                        if (mPendingCheckForTap == null) {
8467                            mPendingCheckForTap = new CheckForTap();
8468                        }
8469                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
8470                    } else {
8471                        // Not inside a scrolling container, so show the feedback right away
8472                        setPressed(true);
8473                        checkForLongClick(0);
8474                    }
8475                    break;
8476
8477                case MotionEvent.ACTION_CANCEL:
8478                    setPressed(false);
8479                    removeTapCallback();
8480                    removeLongPressCallback();
8481                    break;
8482
8483                case MotionEvent.ACTION_MOVE:
8484                    final int x = (int) event.getX();
8485                    final int y = (int) event.getY();
8486
8487                    // Be lenient about moving outside of buttons
8488                    if (!pointInView(x, y, mTouchSlop)) {
8489                        // Outside button
8490                        removeTapCallback();
8491                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
8492                            // Remove any future long press/tap checks
8493                            removeLongPressCallback();
8494
8495                            setPressed(false);
8496                        }
8497                    }
8498                    break;
8499            }
8500            return true;
8501        }
8502
8503        return false;
8504    }
8505
8506    /**
8507     * @hide
8508     */
8509    public boolean isInScrollingContainer() {
8510        ViewParent p = getParent();
8511        while (p != null && p instanceof ViewGroup) {
8512            if (((ViewGroup) p).shouldDelayChildPressedState()) {
8513                return true;
8514            }
8515            p = p.getParent();
8516        }
8517        return false;
8518    }
8519
8520    /**
8521     * Remove the longpress detection timer.
8522     */
8523    private void removeLongPressCallback() {
8524        if (mPendingCheckForLongPress != null) {
8525          removeCallbacks(mPendingCheckForLongPress);
8526        }
8527    }
8528
8529    /**
8530     * Remove the pending click action
8531     */
8532    private void removePerformClickCallback() {
8533        if (mPerformClick != null) {
8534            removeCallbacks(mPerformClick);
8535        }
8536    }
8537
8538    /**
8539     * Remove the prepress detection timer.
8540     */
8541    private void removeUnsetPressCallback() {
8542        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
8543            setPressed(false);
8544            removeCallbacks(mUnsetPressedState);
8545        }
8546    }
8547
8548    /**
8549     * Remove the tap detection timer.
8550     */
8551    private void removeTapCallback() {
8552        if (mPendingCheckForTap != null) {
8553            mPrivateFlags &= ~PFLAG_PREPRESSED;
8554            removeCallbacks(mPendingCheckForTap);
8555        }
8556    }
8557
8558    /**
8559     * Cancels a pending long press.  Your subclass can use this if you
8560     * want the context menu to come up if the user presses and holds
8561     * at the same place, but you don't want it to come up if they press
8562     * and then move around enough to cause scrolling.
8563     */
8564    public void cancelLongPress() {
8565        removeLongPressCallback();
8566
8567        /*
8568         * The prepressed state handled by the tap callback is a display
8569         * construct, but the tap callback will post a long press callback
8570         * less its own timeout. Remove it here.
8571         */
8572        removeTapCallback();
8573    }
8574
8575    /**
8576     * Remove the pending callback for sending a
8577     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
8578     */
8579    private void removeSendViewScrolledAccessibilityEventCallback() {
8580        if (mSendViewScrolledAccessibilityEvent != null) {
8581            removeCallbacks(mSendViewScrolledAccessibilityEvent);
8582            mSendViewScrolledAccessibilityEvent.mIsPending = false;
8583        }
8584    }
8585
8586    /**
8587     * Sets the TouchDelegate for this View.
8588     */
8589    public void setTouchDelegate(TouchDelegate delegate) {
8590        mTouchDelegate = delegate;
8591    }
8592
8593    /**
8594     * Gets the TouchDelegate for this View.
8595     */
8596    public TouchDelegate getTouchDelegate() {
8597        return mTouchDelegate;
8598    }
8599
8600    /**
8601     * Set flags controlling behavior of this view.
8602     *
8603     * @param flags Constant indicating the value which should be set
8604     * @param mask Constant indicating the bit range that should be changed
8605     */
8606    void setFlags(int flags, int mask) {
8607        final boolean accessibilityEnabled =
8608                AccessibilityManager.getInstance(mContext).isEnabled();
8609        final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility();
8610
8611        int old = mViewFlags;
8612        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
8613
8614        int changed = mViewFlags ^ old;
8615        if (changed == 0) {
8616            return;
8617        }
8618        int privateFlags = mPrivateFlags;
8619
8620        /* Check if the FOCUSABLE bit has changed */
8621        if (((changed & FOCUSABLE_MASK) != 0) &&
8622                ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) {
8623            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
8624                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
8625                /* Give up focus if we are no longer focusable */
8626                clearFocus();
8627            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
8628                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
8629                /*
8630                 * Tell the view system that we are now available to take focus
8631                 * if no one else already has it.
8632                 */
8633                if (mParent != null) mParent.focusableViewAvailable(this);
8634            }
8635        }
8636
8637        final int newVisibility = flags & VISIBILITY_MASK;
8638        if (newVisibility == VISIBLE) {
8639            if ((changed & VISIBILITY_MASK) != 0) {
8640                /*
8641                 * If this view is becoming visible, invalidate it in case it changed while
8642                 * it was not visible. Marking it drawn ensures that the invalidation will
8643                 * go through.
8644                 */
8645                mPrivateFlags |= PFLAG_DRAWN;
8646                invalidate(true);
8647
8648                needGlobalAttributesUpdate(true);
8649
8650                // a view becoming visible is worth notifying the parent
8651                // about in case nothing has focus.  even if this specific view
8652                // isn't focusable, it may contain something that is, so let
8653                // the root view try to give this focus if nothing else does.
8654                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
8655                    mParent.focusableViewAvailable(this);
8656                }
8657            }
8658        }
8659
8660        /* Check if the GONE bit has changed */
8661        if ((changed & GONE) != 0) {
8662            needGlobalAttributesUpdate(false);
8663            requestLayout();
8664
8665            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
8666                if (hasFocus()) clearFocus();
8667                clearAccessibilityFocus();
8668                destroyDrawingCache();
8669                if (mParent instanceof View) {
8670                    // GONE views noop invalidation, so invalidate the parent
8671                    ((View) mParent).invalidate(true);
8672                }
8673                // Mark the view drawn to ensure that it gets invalidated properly the next
8674                // time it is visible and gets invalidated
8675                mPrivateFlags |= PFLAG_DRAWN;
8676            }
8677            if (mAttachInfo != null) {
8678                mAttachInfo.mViewVisibilityChanged = true;
8679            }
8680        }
8681
8682        /* Check if the VISIBLE bit has changed */
8683        if ((changed & INVISIBLE) != 0) {
8684            needGlobalAttributesUpdate(false);
8685            /*
8686             * If this view is becoming invisible, set the DRAWN flag so that
8687             * the next invalidate() will not be skipped.
8688             */
8689            mPrivateFlags |= PFLAG_DRAWN;
8690
8691            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
8692                // root view becoming invisible shouldn't clear focus and accessibility focus
8693                if (getRootView() != this) {
8694                    clearFocus();
8695                    clearAccessibilityFocus();
8696                }
8697            }
8698            if (mAttachInfo != null) {
8699                mAttachInfo.mViewVisibilityChanged = true;
8700            }
8701        }
8702
8703        if ((changed & VISIBILITY_MASK) != 0) {
8704            // If the view is invisible, cleanup its display list to free up resources
8705            if (newVisibility != VISIBLE) {
8706                cleanupDraw();
8707            }
8708
8709            if (mParent instanceof ViewGroup) {
8710                ((ViewGroup) mParent).onChildVisibilityChanged(this,
8711                        (changed & VISIBILITY_MASK), newVisibility);
8712                ((View) mParent).invalidate(true);
8713            } else if (mParent != null) {
8714                mParent.invalidateChild(this, null);
8715            }
8716            dispatchVisibilityChanged(this, newVisibility);
8717        }
8718
8719        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
8720            destroyDrawingCache();
8721        }
8722
8723        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
8724            destroyDrawingCache();
8725            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
8726            invalidateParentCaches();
8727        }
8728
8729        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
8730            destroyDrawingCache();
8731            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
8732        }
8733
8734        if ((changed & DRAW_MASK) != 0) {
8735            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
8736                if (mBackground != null) {
8737                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
8738                    mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
8739                } else {
8740                    mPrivateFlags |= PFLAG_SKIP_DRAW;
8741                }
8742            } else {
8743                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
8744            }
8745            requestLayout();
8746            invalidate(true);
8747        }
8748
8749        if ((changed & KEEP_SCREEN_ON) != 0) {
8750            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
8751                mParent.recomputeViewAttributes(this);
8752            }
8753        }
8754
8755        if (accessibilityEnabled) {
8756            if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0
8757                    || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0) {
8758                if (oldIncludeForAccessibility != includeForAccessibility()) {
8759                    notifySubtreeAccessibilityStateChangedIfNeeded();
8760                } else {
8761                    notifyViewAccessibilityStateChangedIfNeeded();
8762                }
8763            }
8764            if ((changed & ENABLED_MASK) != 0) {
8765                notifyViewAccessibilityStateChangedIfNeeded();
8766            }
8767        }
8768    }
8769
8770    /**
8771     * Change the view's z order in the tree, so it's on top of other sibling
8772     * views. This ordering change may affect layout, if the parent container
8773     * uses an order-dependent layout scheme (e.g., LinearLayout). This
8774     * method should be followed by calls to {@link #requestLayout()} and
8775     * {@link View#invalidate()} on the parent.
8776     *
8777     * @see ViewGroup#bringChildToFront(View)
8778     */
8779    public void bringToFront() {
8780        if (mParent != null) {
8781            mParent.bringChildToFront(this);
8782        }
8783    }
8784
8785    /**
8786     * This is called in response to an internal scroll in this view (i.e., the
8787     * view scrolled its own contents). This is typically as a result of
8788     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
8789     * called.
8790     *
8791     * @param l Current horizontal scroll origin.
8792     * @param t Current vertical scroll origin.
8793     * @param oldl Previous horizontal scroll origin.
8794     * @param oldt Previous vertical scroll origin.
8795     */
8796    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
8797        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
8798            postSendViewScrolledAccessibilityEventCallback();
8799        }
8800
8801        mBackgroundSizeChanged = true;
8802
8803        final AttachInfo ai = mAttachInfo;
8804        if (ai != null) {
8805            ai.mViewScrollChanged = true;
8806        }
8807    }
8808
8809    /**
8810     * Interface definition for a callback to be invoked when the layout bounds of a view
8811     * changes due to layout processing.
8812     */
8813    public interface OnLayoutChangeListener {
8814        /**
8815         * Called when the focus state of a view has changed.
8816         *
8817         * @param v The view whose state has changed.
8818         * @param left The new value of the view's left property.
8819         * @param top The new value of the view's top property.
8820         * @param right The new value of the view's right property.
8821         * @param bottom The new value of the view's bottom property.
8822         * @param oldLeft The previous value of the view's left property.
8823         * @param oldTop The previous value of the view's top property.
8824         * @param oldRight The previous value of the view's right property.
8825         * @param oldBottom The previous value of the view's bottom property.
8826         */
8827        void onLayoutChange(View v, int left, int top, int right, int bottom,
8828            int oldLeft, int oldTop, int oldRight, int oldBottom);
8829    }
8830
8831    /**
8832     * This is called during layout when the size of this view has changed. If
8833     * you were just added to the view hierarchy, you're called with the old
8834     * values of 0.
8835     *
8836     * @param w Current width of this view.
8837     * @param h Current height of this view.
8838     * @param oldw Old width of this view.
8839     * @param oldh Old height of this view.
8840     */
8841    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
8842    }
8843
8844    /**
8845     * Called by draw to draw the child views. This may be overridden
8846     * by derived classes to gain control just before its children are drawn
8847     * (but after its own view has been drawn).
8848     * @param canvas the canvas on which to draw the view
8849     */
8850    protected void dispatchDraw(Canvas canvas) {
8851
8852    }
8853
8854    /**
8855     * Gets the parent of this view. Note that the parent is a
8856     * ViewParent and not necessarily a View.
8857     *
8858     * @return Parent of this view.
8859     */
8860    public final ViewParent getParent() {
8861        return mParent;
8862    }
8863
8864    /**
8865     * Set the horizontal scrolled position of your view. This will cause a call to
8866     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8867     * invalidated.
8868     * @param value the x position to scroll to
8869     */
8870    public void setScrollX(int value) {
8871        scrollTo(value, mScrollY);
8872    }
8873
8874    /**
8875     * Set the vertical scrolled position of your view. This will cause a call to
8876     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8877     * invalidated.
8878     * @param value the y position to scroll to
8879     */
8880    public void setScrollY(int value) {
8881        scrollTo(mScrollX, value);
8882    }
8883
8884    /**
8885     * Return the scrolled left position of this view. This is the left edge of
8886     * the displayed part of your view. You do not need to draw any pixels
8887     * farther left, since those are outside of the frame of your view on
8888     * screen.
8889     *
8890     * @return The left edge of the displayed part of your view, in pixels.
8891     */
8892    public final int getScrollX() {
8893        return mScrollX;
8894    }
8895
8896    /**
8897     * Return the scrolled top position of this view. This is the top edge of
8898     * the displayed part of your view. You do not need to draw any pixels above
8899     * it, since those are outside of the frame of your view on screen.
8900     *
8901     * @return The top edge of the displayed part of your view, in pixels.
8902     */
8903    public final int getScrollY() {
8904        return mScrollY;
8905    }
8906
8907    /**
8908     * Return the width of the your view.
8909     *
8910     * @return The width of your view, in pixels.
8911     */
8912    @ViewDebug.ExportedProperty(category = "layout")
8913    public final int getWidth() {
8914        return mRight - mLeft;
8915    }
8916
8917    /**
8918     * Return the height of your view.
8919     *
8920     * @return The height of your view, in pixels.
8921     */
8922    @ViewDebug.ExportedProperty(category = "layout")
8923    public final int getHeight() {
8924        return mBottom - mTop;
8925    }
8926
8927    /**
8928     * Return the visible drawing bounds of your view. Fills in the output
8929     * rectangle with the values from getScrollX(), getScrollY(),
8930     * getWidth(), and getHeight(). These bounds do not account for any
8931     * transformation properties currently set on the view, such as
8932     * {@link #setScaleX(float)} or {@link #setRotation(float)}.
8933     *
8934     * @param outRect The (scrolled) drawing bounds of the view.
8935     */
8936    public void getDrawingRect(Rect outRect) {
8937        outRect.left = mScrollX;
8938        outRect.top = mScrollY;
8939        outRect.right = mScrollX + (mRight - mLeft);
8940        outRect.bottom = mScrollY + (mBottom - mTop);
8941    }
8942
8943    /**
8944     * Like {@link #getMeasuredWidthAndState()}, but only returns the
8945     * raw width component (that is the result is masked by
8946     * {@link #MEASURED_SIZE_MASK}).
8947     *
8948     * @return The raw measured width of this view.
8949     */
8950    public final int getMeasuredWidth() {
8951        return mMeasuredWidth & MEASURED_SIZE_MASK;
8952    }
8953
8954    /**
8955     * Return the full width measurement information for this view as computed
8956     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
8957     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
8958     * This should be used during measurement and layout calculations only. Use
8959     * {@link #getWidth()} to see how wide a view is after layout.
8960     *
8961     * @return The measured width of this view as a bit mask.
8962     */
8963    public final int getMeasuredWidthAndState() {
8964        return mMeasuredWidth;
8965    }
8966
8967    /**
8968     * Like {@link #getMeasuredHeightAndState()}, but only returns the
8969     * raw width component (that is the result is masked by
8970     * {@link #MEASURED_SIZE_MASK}).
8971     *
8972     * @return The raw measured height of this view.
8973     */
8974    public final int getMeasuredHeight() {
8975        return mMeasuredHeight & MEASURED_SIZE_MASK;
8976    }
8977
8978    /**
8979     * Return the full height measurement information for this view as computed
8980     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
8981     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
8982     * This should be used during measurement and layout calculations only. Use
8983     * {@link #getHeight()} to see how wide a view is after layout.
8984     *
8985     * @return The measured width of this view as a bit mask.
8986     */
8987    public final int getMeasuredHeightAndState() {
8988        return mMeasuredHeight;
8989    }
8990
8991    /**
8992     * Return only the state bits of {@link #getMeasuredWidthAndState()}
8993     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
8994     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
8995     * and the height component is at the shifted bits
8996     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
8997     */
8998    public final int getMeasuredState() {
8999        return (mMeasuredWidth&MEASURED_STATE_MASK)
9000                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
9001                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
9002    }
9003
9004    /**
9005     * The transform matrix of this view, which is calculated based on the current
9006     * roation, scale, and pivot properties.
9007     *
9008     * @see #getRotation()
9009     * @see #getScaleX()
9010     * @see #getScaleY()
9011     * @see #getPivotX()
9012     * @see #getPivotY()
9013     * @return The current transform matrix for the view
9014     */
9015    public Matrix getMatrix() {
9016        if (mTransformationInfo != null) {
9017            updateMatrix();
9018            return mTransformationInfo.mMatrix;
9019        }
9020        return Matrix.IDENTITY_MATRIX;
9021    }
9022
9023    /**
9024     * Utility function to determine if the value is far enough away from zero to be
9025     * considered non-zero.
9026     * @param value A floating point value to check for zero-ness
9027     * @return whether the passed-in value is far enough away from zero to be considered non-zero
9028     */
9029    private static boolean nonzero(float value) {
9030        return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
9031    }
9032
9033    /**
9034     * Returns true if the transform matrix is the identity matrix.
9035     * Recomputes the matrix if necessary.
9036     *
9037     * @return True if the transform matrix is the identity matrix, false otherwise.
9038     */
9039    final boolean hasIdentityMatrix() {
9040        if (mTransformationInfo != null) {
9041            updateMatrix();
9042            return mTransformationInfo.mMatrixIsIdentity;
9043        }
9044        return true;
9045    }
9046
9047    void ensureTransformationInfo() {
9048        if (mTransformationInfo == null) {
9049            mTransformationInfo = new TransformationInfo();
9050        }
9051    }
9052
9053    /**
9054     * Recomputes the transform matrix if necessary.
9055     */
9056    private void updateMatrix() {
9057        final TransformationInfo info = mTransformationInfo;
9058        if (info == null) {
9059            return;
9060        }
9061        if (info.mMatrixDirty) {
9062            // transform-related properties have changed since the last time someone
9063            // asked for the matrix; recalculate it with the current values
9064
9065            // Figure out if we need to update the pivot point
9066            if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9067                if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) {
9068                    info.mPrevWidth = mRight - mLeft;
9069                    info.mPrevHeight = mBottom - mTop;
9070                    info.mPivotX = info.mPrevWidth / 2f;
9071                    info.mPivotY = info.mPrevHeight / 2f;
9072                }
9073            }
9074            info.mMatrix.reset();
9075            if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) {
9076                info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY);
9077                info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY);
9078                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
9079            } else {
9080                if (info.mCamera == null) {
9081                    info.mCamera = new Camera();
9082                    info.matrix3D = new Matrix();
9083                }
9084                info.mCamera.save();
9085                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
9086                info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation);
9087                info.mCamera.getMatrix(info.matrix3D);
9088                info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY);
9089                info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX,
9090                        info.mPivotY + info.mTranslationY);
9091                info.mMatrix.postConcat(info.matrix3D);
9092                info.mCamera.restore();
9093            }
9094            info.mMatrixDirty = false;
9095            info.mMatrixIsIdentity = info.mMatrix.isIdentity();
9096            info.mInverseMatrixDirty = true;
9097        }
9098    }
9099
9100   /**
9101     * Utility method to retrieve the inverse of the current mMatrix property.
9102     * We cache the matrix to avoid recalculating it when transform properties
9103     * have not changed.
9104     *
9105     * @return The inverse of the current matrix of this view.
9106     */
9107    final Matrix getInverseMatrix() {
9108        final TransformationInfo info = mTransformationInfo;
9109        if (info != null) {
9110            updateMatrix();
9111            if (info.mInverseMatrixDirty) {
9112                if (info.mInverseMatrix == null) {
9113                    info.mInverseMatrix = new Matrix();
9114                }
9115                info.mMatrix.invert(info.mInverseMatrix);
9116                info.mInverseMatrixDirty = false;
9117            }
9118            return info.mInverseMatrix;
9119        }
9120        return Matrix.IDENTITY_MATRIX;
9121    }
9122
9123    /**
9124     * Gets the distance along the Z axis from the camera to this view.
9125     *
9126     * @see #setCameraDistance(float)
9127     *
9128     * @return The distance along the Z axis.
9129     */
9130    public float getCameraDistance() {
9131        ensureTransformationInfo();
9132        final float dpi = mResources.getDisplayMetrics().densityDpi;
9133        final TransformationInfo info = mTransformationInfo;
9134        if (info.mCamera == null) {
9135            info.mCamera = new Camera();
9136            info.matrix3D = new Matrix();
9137        }
9138        return -(info.mCamera.getLocationZ() * dpi);
9139    }
9140
9141    /**
9142     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
9143     * views are drawn) from the camera to this view. The camera's distance
9144     * affects 3D transformations, for instance rotations around the X and Y
9145     * axis. If the rotationX or rotationY properties are changed and this view is
9146     * large (more than half the size of the screen), it is recommended to always
9147     * use a camera distance that's greater than the height (X axis rotation) or
9148     * the width (Y axis rotation) of this view.</p>
9149     *
9150     * <p>The distance of the camera from the view plane can have an affect on the
9151     * perspective distortion of the view when it is rotated around the x or y axis.
9152     * For example, a large distance will result in a large viewing angle, and there
9153     * will not be much perspective distortion of the view as it rotates. A short
9154     * distance may cause much more perspective distortion upon rotation, and can
9155     * also result in some drawing artifacts if the rotated view ends up partially
9156     * behind the camera (which is why the recommendation is to use a distance at
9157     * least as far as the size of the view, if the view is to be rotated.)</p>
9158     *
9159     * <p>The distance is expressed in "depth pixels." The default distance depends
9160     * on the screen density. For instance, on a medium density display, the
9161     * default distance is 1280. On a high density display, the default distance
9162     * is 1920.</p>
9163     *
9164     * <p>If you want to specify a distance that leads to visually consistent
9165     * results across various densities, use the following formula:</p>
9166     * <pre>
9167     * float scale = context.getResources().getDisplayMetrics().density;
9168     * view.setCameraDistance(distance * scale);
9169     * </pre>
9170     *
9171     * <p>The density scale factor of a high density display is 1.5,
9172     * and 1920 = 1280 * 1.5.</p>
9173     *
9174     * @param distance The distance in "depth pixels", if negative the opposite
9175     *        value is used
9176     *
9177     * @see #setRotationX(float)
9178     * @see #setRotationY(float)
9179     */
9180    public void setCameraDistance(float distance) {
9181        invalidateViewProperty(true, false);
9182
9183        ensureTransformationInfo();
9184        final float dpi = mResources.getDisplayMetrics().densityDpi;
9185        final TransformationInfo info = mTransformationInfo;
9186        if (info.mCamera == null) {
9187            info.mCamera = new Camera();
9188            info.matrix3D = new Matrix();
9189        }
9190
9191        info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi);
9192        info.mMatrixDirty = true;
9193
9194        invalidateViewProperty(false, false);
9195        if (mDisplayList != null) {
9196            mDisplayList.setCameraDistance(-Math.abs(distance) / dpi);
9197        }
9198        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9199            // View was rejected last time it was drawn by its parent; this may have changed
9200            invalidateParentIfNeeded();
9201        }
9202    }
9203
9204    /**
9205     * The degrees that the view is rotated around the pivot point.
9206     *
9207     * @see #setRotation(float)
9208     * @see #getPivotX()
9209     * @see #getPivotY()
9210     *
9211     * @return The degrees of rotation.
9212     */
9213    @ViewDebug.ExportedProperty(category = "drawing")
9214    public float getRotation() {
9215        return mTransformationInfo != null ? mTransformationInfo.mRotation : 0;
9216    }
9217
9218    /**
9219     * Sets the degrees that the view is rotated around the pivot point. Increasing values
9220     * result in clockwise rotation.
9221     *
9222     * @param rotation The degrees of rotation.
9223     *
9224     * @see #getRotation()
9225     * @see #getPivotX()
9226     * @see #getPivotY()
9227     * @see #setRotationX(float)
9228     * @see #setRotationY(float)
9229     *
9230     * @attr ref android.R.styleable#View_rotation
9231     */
9232    public void setRotation(float rotation) {
9233        ensureTransformationInfo();
9234        final TransformationInfo info = mTransformationInfo;
9235        if (info.mRotation != rotation) {
9236            // Double-invalidation is necessary to capture view's old and new areas
9237            invalidateViewProperty(true, false);
9238            info.mRotation = rotation;
9239            info.mMatrixDirty = true;
9240            invalidateViewProperty(false, true);
9241            if (mDisplayList != null) {
9242                mDisplayList.setRotation(rotation);
9243            }
9244            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9245                // View was rejected last time it was drawn by its parent; this may have changed
9246                invalidateParentIfNeeded();
9247            }
9248        }
9249    }
9250
9251    /**
9252     * The degrees that the view is rotated around the vertical axis through the pivot point.
9253     *
9254     * @see #getPivotX()
9255     * @see #getPivotY()
9256     * @see #setRotationY(float)
9257     *
9258     * @return The degrees of Y rotation.
9259     */
9260    @ViewDebug.ExportedProperty(category = "drawing")
9261    public float getRotationY() {
9262        return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0;
9263    }
9264
9265    /**
9266     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
9267     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
9268     * down the y axis.
9269     *
9270     * When rotating large views, it is recommended to adjust the camera distance
9271     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
9272     *
9273     * @param rotationY The degrees of Y rotation.
9274     *
9275     * @see #getRotationY()
9276     * @see #getPivotX()
9277     * @see #getPivotY()
9278     * @see #setRotation(float)
9279     * @see #setRotationX(float)
9280     * @see #setCameraDistance(float)
9281     *
9282     * @attr ref android.R.styleable#View_rotationY
9283     */
9284    public void setRotationY(float rotationY) {
9285        ensureTransformationInfo();
9286        final TransformationInfo info = mTransformationInfo;
9287        if (info.mRotationY != rotationY) {
9288            invalidateViewProperty(true, false);
9289            info.mRotationY = rotationY;
9290            info.mMatrixDirty = true;
9291            invalidateViewProperty(false, true);
9292            if (mDisplayList != null) {
9293                mDisplayList.setRotationY(rotationY);
9294            }
9295            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9296                // View was rejected last time it was drawn by its parent; this may have changed
9297                invalidateParentIfNeeded();
9298            }
9299        }
9300    }
9301
9302    /**
9303     * The degrees that the view is rotated around the horizontal axis through the pivot point.
9304     *
9305     * @see #getPivotX()
9306     * @see #getPivotY()
9307     * @see #setRotationX(float)
9308     *
9309     * @return The degrees of X rotation.
9310     */
9311    @ViewDebug.ExportedProperty(category = "drawing")
9312    public float getRotationX() {
9313        return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0;
9314    }
9315
9316    /**
9317     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
9318     * Increasing values result in clockwise rotation from the viewpoint of looking down the
9319     * x axis.
9320     *
9321     * When rotating large views, it is recommended to adjust the camera distance
9322     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
9323     *
9324     * @param rotationX The degrees of X rotation.
9325     *
9326     * @see #getRotationX()
9327     * @see #getPivotX()
9328     * @see #getPivotY()
9329     * @see #setRotation(float)
9330     * @see #setRotationY(float)
9331     * @see #setCameraDistance(float)
9332     *
9333     * @attr ref android.R.styleable#View_rotationX
9334     */
9335    public void setRotationX(float rotationX) {
9336        ensureTransformationInfo();
9337        final TransformationInfo info = mTransformationInfo;
9338        if (info.mRotationX != rotationX) {
9339            invalidateViewProperty(true, false);
9340            info.mRotationX = rotationX;
9341            info.mMatrixDirty = true;
9342            invalidateViewProperty(false, true);
9343            if (mDisplayList != null) {
9344                mDisplayList.setRotationX(rotationX);
9345            }
9346            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9347                // View was rejected last time it was drawn by its parent; this may have changed
9348                invalidateParentIfNeeded();
9349            }
9350        }
9351    }
9352
9353    /**
9354     * The amount that the view is scaled in x around the pivot point, as a proportion of
9355     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
9356     *
9357     * <p>By default, this is 1.0f.
9358     *
9359     * @see #getPivotX()
9360     * @see #getPivotY()
9361     * @return The scaling factor.
9362     */
9363    @ViewDebug.ExportedProperty(category = "drawing")
9364    public float getScaleX() {
9365        return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1;
9366    }
9367
9368    /**
9369     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
9370     * the view's unscaled width. A value of 1 means that no scaling is applied.
9371     *
9372     * @param scaleX The scaling factor.
9373     * @see #getPivotX()
9374     * @see #getPivotY()
9375     *
9376     * @attr ref android.R.styleable#View_scaleX
9377     */
9378    public void setScaleX(float scaleX) {
9379        ensureTransformationInfo();
9380        final TransformationInfo info = mTransformationInfo;
9381        if (info.mScaleX != scaleX) {
9382            invalidateViewProperty(true, false);
9383            info.mScaleX = scaleX;
9384            info.mMatrixDirty = true;
9385            invalidateViewProperty(false, true);
9386            if (mDisplayList != null) {
9387                mDisplayList.setScaleX(scaleX);
9388            }
9389            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9390                // View was rejected last time it was drawn by its parent; this may have changed
9391                invalidateParentIfNeeded();
9392            }
9393        }
9394    }
9395
9396    /**
9397     * The amount that the view is scaled in y around the pivot point, as a proportion of
9398     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
9399     *
9400     * <p>By default, this is 1.0f.
9401     *
9402     * @see #getPivotX()
9403     * @see #getPivotY()
9404     * @return The scaling factor.
9405     */
9406    @ViewDebug.ExportedProperty(category = "drawing")
9407    public float getScaleY() {
9408        return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1;
9409    }
9410
9411    /**
9412     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
9413     * the view's unscaled width. A value of 1 means that no scaling is applied.
9414     *
9415     * @param scaleY The scaling factor.
9416     * @see #getPivotX()
9417     * @see #getPivotY()
9418     *
9419     * @attr ref android.R.styleable#View_scaleY
9420     */
9421    public void setScaleY(float scaleY) {
9422        ensureTransformationInfo();
9423        final TransformationInfo info = mTransformationInfo;
9424        if (info.mScaleY != scaleY) {
9425            invalidateViewProperty(true, false);
9426            info.mScaleY = scaleY;
9427            info.mMatrixDirty = true;
9428            invalidateViewProperty(false, true);
9429            if (mDisplayList != null) {
9430                mDisplayList.setScaleY(scaleY);
9431            }
9432            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9433                // View was rejected last time it was drawn by its parent; this may have changed
9434                invalidateParentIfNeeded();
9435            }
9436        }
9437    }
9438
9439    /**
9440     * The x location of the point around which the view is {@link #setRotation(float) rotated}
9441     * and {@link #setScaleX(float) scaled}.
9442     *
9443     * @see #getRotation()
9444     * @see #getScaleX()
9445     * @see #getScaleY()
9446     * @see #getPivotY()
9447     * @return The x location of the pivot point.
9448     *
9449     * @attr ref android.R.styleable#View_transformPivotX
9450     */
9451    @ViewDebug.ExportedProperty(category = "drawing")
9452    public float getPivotX() {
9453        return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0;
9454    }
9455
9456    /**
9457     * Sets the x location of the point around which the view is
9458     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
9459     * By default, the pivot point is centered on the object.
9460     * Setting this property disables this behavior and causes the view to use only the
9461     * explicitly set pivotX and pivotY values.
9462     *
9463     * @param pivotX The x location of the pivot point.
9464     * @see #getRotation()
9465     * @see #getScaleX()
9466     * @see #getScaleY()
9467     * @see #getPivotY()
9468     *
9469     * @attr ref android.R.styleable#View_transformPivotX
9470     */
9471    public void setPivotX(float pivotX) {
9472        ensureTransformationInfo();
9473        mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET;
9474        final TransformationInfo info = mTransformationInfo;
9475        if (info.mPivotX != pivotX) {
9476            invalidateViewProperty(true, false);
9477            info.mPivotX = pivotX;
9478            info.mMatrixDirty = true;
9479            invalidateViewProperty(false, true);
9480            if (mDisplayList != null) {
9481                mDisplayList.setPivotX(pivotX);
9482            }
9483            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9484                // View was rejected last time it was drawn by its parent; this may have changed
9485                invalidateParentIfNeeded();
9486            }
9487        }
9488    }
9489
9490    /**
9491     * The y location of the point around which the view is {@link #setRotation(float) rotated}
9492     * and {@link #setScaleY(float) scaled}.
9493     *
9494     * @see #getRotation()
9495     * @see #getScaleX()
9496     * @see #getScaleY()
9497     * @see #getPivotY()
9498     * @return The y location of the pivot point.
9499     *
9500     * @attr ref android.R.styleable#View_transformPivotY
9501     */
9502    @ViewDebug.ExportedProperty(category = "drawing")
9503    public float getPivotY() {
9504        return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0;
9505    }
9506
9507    /**
9508     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
9509     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
9510     * Setting this property disables this behavior and causes the view to use only the
9511     * explicitly set pivotX and pivotY values.
9512     *
9513     * @param pivotY The y location of the pivot point.
9514     * @see #getRotation()
9515     * @see #getScaleX()
9516     * @see #getScaleY()
9517     * @see #getPivotY()
9518     *
9519     * @attr ref android.R.styleable#View_transformPivotY
9520     */
9521    public void setPivotY(float pivotY) {
9522        ensureTransformationInfo();
9523        mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET;
9524        final TransformationInfo info = mTransformationInfo;
9525        if (info.mPivotY != pivotY) {
9526            invalidateViewProperty(true, false);
9527            info.mPivotY = pivotY;
9528            info.mMatrixDirty = true;
9529            invalidateViewProperty(false, true);
9530            if (mDisplayList != null) {
9531                mDisplayList.setPivotY(pivotY);
9532            }
9533            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9534                // View was rejected last time it was drawn by its parent; this may have changed
9535                invalidateParentIfNeeded();
9536            }
9537        }
9538    }
9539
9540    /**
9541     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
9542     * completely transparent and 1 means the view is completely opaque.
9543     *
9544     * <p>By default this is 1.0f.
9545     * @return The opacity of the view.
9546     */
9547    @ViewDebug.ExportedProperty(category = "drawing")
9548    public float getAlpha() {
9549        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
9550    }
9551
9552    /**
9553     * Returns whether this View has content which overlaps. This function, intended to be
9554     * overridden by specific View types, is an optimization when alpha is set on a view. If
9555     * rendering overlaps in a view with alpha < 1, that view is drawn to an offscreen buffer
9556     * and then composited it into place, which can be expensive. If the view has no overlapping
9557     * rendering, the view can draw each primitive with the appropriate alpha value directly.
9558     * An example of overlapping rendering is a TextView with a background image, such as a
9559     * Button. An example of non-overlapping rendering is a TextView with no background, or
9560     * an ImageView with only the foreground image. The default implementation returns true;
9561     * subclasses should override if they have cases which can be optimized.
9562     *
9563     * @return true if the content in this view might overlap, false otherwise.
9564     */
9565    public boolean hasOverlappingRendering() {
9566        return true;
9567    }
9568
9569    /**
9570     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
9571     * completely transparent and 1 means the view is completely opaque.</p>
9572     *
9573     * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant
9574     * performance implications, especially for large views. It is best to use the alpha property
9575     * sparingly and transiently, as in the case of fading animations.</p>
9576     *
9577     * <p>For a view with a frequently changing alpha, such as during a fading animation, it is
9578     * strongly recommended for performance reasons to either override
9579     * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a
9580     * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p>
9581     *
9582     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
9583     * responsible for applying the opacity itself.</p>
9584     *
9585     * <p>Note that if the view is backed by a
9586     * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a
9587     * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than
9588     * 1.0 will supercede the alpha of the layer paint.</p>
9589     *
9590     * @param alpha The opacity of the view.
9591     *
9592     * @see #hasOverlappingRendering()
9593     * @see #setLayerType(int, android.graphics.Paint)
9594     *
9595     * @attr ref android.R.styleable#View_alpha
9596     */
9597    public void setAlpha(float alpha) {
9598        ensureTransformationInfo();
9599        if (mTransformationInfo.mAlpha != alpha) {
9600            mTransformationInfo.mAlpha = alpha;
9601            if (onSetAlpha((int) (alpha * 255))) {
9602                mPrivateFlags |= PFLAG_ALPHA_SET;
9603                // subclass is handling alpha - don't optimize rendering cache invalidation
9604                invalidateParentCaches();
9605                invalidate(true);
9606            } else {
9607                mPrivateFlags &= ~PFLAG_ALPHA_SET;
9608                invalidateViewProperty(true, false);
9609                if (mDisplayList != null) {
9610                    mDisplayList.setAlpha(alpha);
9611                }
9612            }
9613        }
9614    }
9615
9616    /**
9617     * Faster version of setAlpha() which performs the same steps except there are
9618     * no calls to invalidate(). The caller of this function should perform proper invalidation
9619     * on the parent and this object. The return value indicates whether the subclass handles
9620     * alpha (the return value for onSetAlpha()).
9621     *
9622     * @param alpha The new value for the alpha property
9623     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
9624     *         the new value for the alpha property is different from the old value
9625     */
9626    boolean setAlphaNoInvalidation(float alpha) {
9627        ensureTransformationInfo();
9628        if (mTransformationInfo.mAlpha != alpha) {
9629            mTransformationInfo.mAlpha = alpha;
9630            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
9631            if (subclassHandlesAlpha) {
9632                mPrivateFlags |= PFLAG_ALPHA_SET;
9633                return true;
9634            } else {
9635                mPrivateFlags &= ~PFLAG_ALPHA_SET;
9636                if (mDisplayList != null) {
9637                    mDisplayList.setAlpha(alpha);
9638                }
9639            }
9640        }
9641        return false;
9642    }
9643
9644    /**
9645     * Top position of this view relative to its parent.
9646     *
9647     * @return The top of this view, in pixels.
9648     */
9649    @ViewDebug.CapturedViewProperty
9650    public final int getTop() {
9651        return mTop;
9652    }
9653
9654    /**
9655     * Sets the top position of this view relative to its parent. This method is meant to be called
9656     * by the layout system and should not generally be called otherwise, because the property
9657     * may be changed at any time by the layout.
9658     *
9659     * @param top The top of this view, in pixels.
9660     */
9661    public final void setTop(int top) {
9662        if (top != mTop) {
9663            updateMatrix();
9664            final boolean matrixIsIdentity = mTransformationInfo == null
9665                    || mTransformationInfo.mMatrixIsIdentity;
9666            if (matrixIsIdentity) {
9667                if (mAttachInfo != null) {
9668                    int minTop;
9669                    int yLoc;
9670                    if (top < mTop) {
9671                        minTop = top;
9672                        yLoc = top - mTop;
9673                    } else {
9674                        minTop = mTop;
9675                        yLoc = 0;
9676                    }
9677                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
9678                }
9679            } else {
9680                // Double-invalidation is necessary to capture view's old and new areas
9681                invalidate(true);
9682            }
9683
9684            int width = mRight - mLeft;
9685            int oldHeight = mBottom - mTop;
9686
9687            mTop = top;
9688            if (mDisplayList != null) {
9689                mDisplayList.setTop(mTop);
9690            }
9691
9692            sizeChange(width, mBottom - mTop, width, oldHeight);
9693
9694            if (!matrixIsIdentity) {
9695                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9696                    // A change in dimension means an auto-centered pivot point changes, too
9697                    mTransformationInfo.mMatrixDirty = true;
9698                }
9699                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
9700                invalidate(true);
9701            }
9702            mBackgroundSizeChanged = true;
9703            invalidateParentIfNeeded();
9704            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9705                // View was rejected last time it was drawn by its parent; this may have changed
9706                invalidateParentIfNeeded();
9707            }
9708        }
9709    }
9710
9711    /**
9712     * Bottom position of this view relative to its parent.
9713     *
9714     * @return The bottom of this view, in pixels.
9715     */
9716    @ViewDebug.CapturedViewProperty
9717    public final int getBottom() {
9718        return mBottom;
9719    }
9720
9721    /**
9722     * True if this view has changed since the last time being drawn.
9723     *
9724     * @return The dirty state of this view.
9725     */
9726    public boolean isDirty() {
9727        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
9728    }
9729
9730    /**
9731     * Sets the bottom position of this view relative to its parent. This method is meant to be
9732     * called by the layout system and should not generally be called otherwise, because the
9733     * property may be changed at any time by the layout.
9734     *
9735     * @param bottom The bottom of this view, in pixels.
9736     */
9737    public final void setBottom(int bottom) {
9738        if (bottom != mBottom) {
9739            updateMatrix();
9740            final boolean matrixIsIdentity = mTransformationInfo == null
9741                    || mTransformationInfo.mMatrixIsIdentity;
9742            if (matrixIsIdentity) {
9743                if (mAttachInfo != null) {
9744                    int maxBottom;
9745                    if (bottom < mBottom) {
9746                        maxBottom = mBottom;
9747                    } else {
9748                        maxBottom = bottom;
9749                    }
9750                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
9751                }
9752            } else {
9753                // Double-invalidation is necessary to capture view's old and new areas
9754                invalidate(true);
9755            }
9756
9757            int width = mRight - mLeft;
9758            int oldHeight = mBottom - mTop;
9759
9760            mBottom = bottom;
9761            if (mDisplayList != null) {
9762                mDisplayList.setBottom(mBottom);
9763            }
9764
9765            sizeChange(width, mBottom - mTop, width, oldHeight);
9766
9767            if (!matrixIsIdentity) {
9768                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9769                    // A change in dimension means an auto-centered pivot point changes, too
9770                    mTransformationInfo.mMatrixDirty = true;
9771                }
9772                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
9773                invalidate(true);
9774            }
9775            mBackgroundSizeChanged = true;
9776            invalidateParentIfNeeded();
9777            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9778                // View was rejected last time it was drawn by its parent; this may have changed
9779                invalidateParentIfNeeded();
9780            }
9781        }
9782    }
9783
9784    /**
9785     * Left position of this view relative to its parent.
9786     *
9787     * @return The left edge of this view, in pixels.
9788     */
9789    @ViewDebug.CapturedViewProperty
9790    public final int getLeft() {
9791        return mLeft;
9792    }
9793
9794    /**
9795     * Sets the left position of this view relative to its parent. This method is meant to be called
9796     * by the layout system and should not generally be called otherwise, because the property
9797     * may be changed at any time by the layout.
9798     *
9799     * @param left The bottom of this view, in pixels.
9800     */
9801    public final void setLeft(int left) {
9802        if (left != mLeft) {
9803            updateMatrix();
9804            final boolean matrixIsIdentity = mTransformationInfo == null
9805                    || mTransformationInfo.mMatrixIsIdentity;
9806            if (matrixIsIdentity) {
9807                if (mAttachInfo != null) {
9808                    int minLeft;
9809                    int xLoc;
9810                    if (left < mLeft) {
9811                        minLeft = left;
9812                        xLoc = left - mLeft;
9813                    } else {
9814                        minLeft = mLeft;
9815                        xLoc = 0;
9816                    }
9817                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
9818                }
9819            } else {
9820                // Double-invalidation is necessary to capture view's old and new areas
9821                invalidate(true);
9822            }
9823
9824            int oldWidth = mRight - mLeft;
9825            int height = mBottom - mTop;
9826
9827            mLeft = left;
9828            if (mDisplayList != null) {
9829                mDisplayList.setLeft(left);
9830            }
9831
9832            sizeChange(mRight - mLeft, height, oldWidth, height);
9833
9834            if (!matrixIsIdentity) {
9835                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9836                    // A change in dimension means an auto-centered pivot point changes, too
9837                    mTransformationInfo.mMatrixDirty = true;
9838                }
9839                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
9840                invalidate(true);
9841            }
9842            mBackgroundSizeChanged = true;
9843            invalidateParentIfNeeded();
9844            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9845                // View was rejected last time it was drawn by its parent; this may have changed
9846                invalidateParentIfNeeded();
9847            }
9848        }
9849    }
9850
9851    /**
9852     * Right position of this view relative to its parent.
9853     *
9854     * @return The right edge of this view, in pixels.
9855     */
9856    @ViewDebug.CapturedViewProperty
9857    public final int getRight() {
9858        return mRight;
9859    }
9860
9861    /**
9862     * Sets the right position of this view relative to its parent. This method is meant to be called
9863     * by the layout system and should not generally be called otherwise, because the property
9864     * may be changed at any time by the layout.
9865     *
9866     * @param right The bottom of this view, in pixels.
9867     */
9868    public final void setRight(int right) {
9869        if (right != mRight) {
9870            updateMatrix();
9871            final boolean matrixIsIdentity = mTransformationInfo == null
9872                    || mTransformationInfo.mMatrixIsIdentity;
9873            if (matrixIsIdentity) {
9874                if (mAttachInfo != null) {
9875                    int maxRight;
9876                    if (right < mRight) {
9877                        maxRight = mRight;
9878                    } else {
9879                        maxRight = right;
9880                    }
9881                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
9882                }
9883            } else {
9884                // Double-invalidation is necessary to capture view's old and new areas
9885                invalidate(true);
9886            }
9887
9888            int oldWidth = mRight - mLeft;
9889            int height = mBottom - mTop;
9890
9891            mRight = right;
9892            if (mDisplayList != null) {
9893                mDisplayList.setRight(mRight);
9894            }
9895
9896            sizeChange(mRight - mLeft, height, oldWidth, height);
9897
9898            if (!matrixIsIdentity) {
9899                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9900                    // A change in dimension means an auto-centered pivot point changes, too
9901                    mTransformationInfo.mMatrixDirty = true;
9902                }
9903                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
9904                invalidate(true);
9905            }
9906            mBackgroundSizeChanged = true;
9907            invalidateParentIfNeeded();
9908            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9909                // View was rejected last time it was drawn by its parent; this may have changed
9910                invalidateParentIfNeeded();
9911            }
9912        }
9913    }
9914
9915    /**
9916     * The visual x position of this view, in pixels. This is equivalent to the
9917     * {@link #setTranslationX(float) translationX} property plus the current
9918     * {@link #getLeft() left} property.
9919     *
9920     * @return The visual x position of this view, in pixels.
9921     */
9922    @ViewDebug.ExportedProperty(category = "drawing")
9923    public float getX() {
9924        return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0);
9925    }
9926
9927    /**
9928     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
9929     * {@link #setTranslationX(float) translationX} property to be the difference between
9930     * the x value passed in and the current {@link #getLeft() left} property.
9931     *
9932     * @param x The visual x position of this view, in pixels.
9933     */
9934    public void setX(float x) {
9935        setTranslationX(x - mLeft);
9936    }
9937
9938    /**
9939     * The visual y position of this view, in pixels. This is equivalent to the
9940     * {@link #setTranslationY(float) translationY} property plus the current
9941     * {@link #getTop() top} property.
9942     *
9943     * @return The visual y position of this view, in pixels.
9944     */
9945    @ViewDebug.ExportedProperty(category = "drawing")
9946    public float getY() {
9947        return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0);
9948    }
9949
9950    /**
9951     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
9952     * {@link #setTranslationY(float) translationY} property to be the difference between
9953     * the y value passed in and the current {@link #getTop() top} property.
9954     *
9955     * @param y The visual y position of this view, in pixels.
9956     */
9957    public void setY(float y) {
9958        setTranslationY(y - mTop);
9959    }
9960
9961
9962    /**
9963     * The horizontal location of this view relative to its {@link #getLeft() left} position.
9964     * This position is post-layout, in addition to wherever the object's
9965     * layout placed it.
9966     *
9967     * @return The horizontal position of this view relative to its left position, in pixels.
9968     */
9969    @ViewDebug.ExportedProperty(category = "drawing")
9970    public float getTranslationX() {
9971        return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0;
9972    }
9973
9974    /**
9975     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
9976     * This effectively positions the object post-layout, in addition to wherever the object's
9977     * layout placed it.
9978     *
9979     * @param translationX The horizontal position of this view relative to its left position,
9980     * in pixels.
9981     *
9982     * @attr ref android.R.styleable#View_translationX
9983     */
9984    public void setTranslationX(float translationX) {
9985        ensureTransformationInfo();
9986        final TransformationInfo info = mTransformationInfo;
9987        if (info.mTranslationX != translationX) {
9988            // Double-invalidation is necessary to capture view's old and new areas
9989            invalidateViewProperty(true, false);
9990            info.mTranslationX = translationX;
9991            info.mMatrixDirty = true;
9992            invalidateViewProperty(false, true);
9993            if (mDisplayList != null) {
9994                mDisplayList.setTranslationX(translationX);
9995            }
9996            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9997                // View was rejected last time it was drawn by its parent; this may have changed
9998                invalidateParentIfNeeded();
9999            }
10000        }
10001    }
10002
10003    /**
10004     * The horizontal location of this view relative to its {@link #getTop() top} position.
10005     * This position is post-layout, in addition to wherever the object's
10006     * layout placed it.
10007     *
10008     * @return The vertical position of this view relative to its top position,
10009     * in pixels.
10010     */
10011    @ViewDebug.ExportedProperty(category = "drawing")
10012    public float getTranslationY() {
10013        return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0;
10014    }
10015
10016    /**
10017     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
10018     * This effectively positions the object post-layout, in addition to wherever the object's
10019     * layout placed it.
10020     *
10021     * @param translationY The vertical position of this view relative to its top position,
10022     * in pixels.
10023     *
10024     * @attr ref android.R.styleable#View_translationY
10025     */
10026    public void setTranslationY(float translationY) {
10027        ensureTransformationInfo();
10028        final TransformationInfo info = mTransformationInfo;
10029        if (info.mTranslationY != translationY) {
10030            invalidateViewProperty(true, false);
10031            info.mTranslationY = translationY;
10032            info.mMatrixDirty = true;
10033            invalidateViewProperty(false, true);
10034            if (mDisplayList != null) {
10035                mDisplayList.setTranslationY(translationY);
10036            }
10037            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10038                // View was rejected last time it was drawn by its parent; this may have changed
10039                invalidateParentIfNeeded();
10040            }
10041        }
10042    }
10043
10044    /**
10045     * Hit rectangle in parent's coordinates
10046     *
10047     * @param outRect The hit rectangle of the view.
10048     */
10049    public void getHitRect(Rect outRect) {
10050        updateMatrix();
10051        final TransformationInfo info = mTransformationInfo;
10052        if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) {
10053            outRect.set(mLeft, mTop, mRight, mBottom);
10054        } else {
10055            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
10056            tmpRect.set(0, 0, getWidth(), getHeight());
10057            info.mMatrix.mapRect(tmpRect);
10058            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
10059                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
10060        }
10061    }
10062
10063    /**
10064     * Determines whether the given point, in local coordinates is inside the view.
10065     */
10066    /*package*/ final boolean pointInView(float localX, float localY) {
10067        return localX >= 0 && localX < (mRight - mLeft)
10068                && localY >= 0 && localY < (mBottom - mTop);
10069    }
10070
10071    /**
10072     * Utility method to determine whether the given point, in local coordinates,
10073     * is inside the view, where the area of the view is expanded by the slop factor.
10074     * This method is called while processing touch-move events to determine if the event
10075     * is still within the view.
10076     *
10077     * @hide
10078     */
10079    public boolean pointInView(float localX, float localY, float slop) {
10080        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
10081                localY < ((mBottom - mTop) + slop);
10082    }
10083
10084    /**
10085     * When a view has focus and the user navigates away from it, the next view is searched for
10086     * starting from the rectangle filled in by this method.
10087     *
10088     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
10089     * of the view.  However, if your view maintains some idea of internal selection,
10090     * such as a cursor, or a selected row or column, you should override this method and
10091     * fill in a more specific rectangle.
10092     *
10093     * @param r The rectangle to fill in, in this view's coordinates.
10094     */
10095    public void getFocusedRect(Rect r) {
10096        getDrawingRect(r);
10097    }
10098
10099    /**
10100     * If some part of this view is not clipped by any of its parents, then
10101     * return that area in r in global (root) coordinates. To convert r to local
10102     * coordinates (without taking possible View rotations into account), offset
10103     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
10104     * If the view is completely clipped or translated out, return false.
10105     *
10106     * @param r If true is returned, r holds the global coordinates of the
10107     *        visible portion of this view.
10108     * @param globalOffset If true is returned, globalOffset holds the dx,dy
10109     *        between this view and its root. globalOffet may be null.
10110     * @return true if r is non-empty (i.e. part of the view is visible at the
10111     *         root level.
10112     */
10113    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
10114        int width = mRight - mLeft;
10115        int height = mBottom - mTop;
10116        if (width > 0 && height > 0) {
10117            r.set(0, 0, width, height);
10118            if (globalOffset != null) {
10119                globalOffset.set(-mScrollX, -mScrollY);
10120            }
10121            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
10122        }
10123        return false;
10124    }
10125
10126    public final boolean getGlobalVisibleRect(Rect r) {
10127        return getGlobalVisibleRect(r, null);
10128    }
10129
10130    public final boolean getLocalVisibleRect(Rect r) {
10131        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
10132        if (getGlobalVisibleRect(r, offset)) {
10133            r.offset(-offset.x, -offset.y); // make r local
10134            return true;
10135        }
10136        return false;
10137    }
10138
10139    /**
10140     * Offset this view's vertical location by the specified number of pixels.
10141     *
10142     * @param offset the number of pixels to offset the view by
10143     */
10144    public void offsetTopAndBottom(int offset) {
10145        if (offset != 0) {
10146            updateMatrix();
10147            final boolean matrixIsIdentity = mTransformationInfo == null
10148                    || mTransformationInfo.mMatrixIsIdentity;
10149            if (matrixIsIdentity) {
10150                if (mDisplayList != null) {
10151                    invalidateViewProperty(false, false);
10152                } else {
10153                    final ViewParent p = mParent;
10154                    if (p != null && mAttachInfo != null) {
10155                        final Rect r = mAttachInfo.mTmpInvalRect;
10156                        int minTop;
10157                        int maxBottom;
10158                        int yLoc;
10159                        if (offset < 0) {
10160                            minTop = mTop + offset;
10161                            maxBottom = mBottom;
10162                            yLoc = offset;
10163                        } else {
10164                            minTop = mTop;
10165                            maxBottom = mBottom + offset;
10166                            yLoc = 0;
10167                        }
10168                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
10169                        p.invalidateChild(this, r);
10170                    }
10171                }
10172            } else {
10173                invalidateViewProperty(false, false);
10174            }
10175
10176            mTop += offset;
10177            mBottom += offset;
10178            if (mDisplayList != null) {
10179                mDisplayList.offsetTopAndBottom(offset);
10180                invalidateViewProperty(false, false);
10181            } else {
10182                if (!matrixIsIdentity) {
10183                    invalidateViewProperty(false, true);
10184                }
10185                invalidateParentIfNeeded();
10186            }
10187        }
10188    }
10189
10190    /**
10191     * Offset this view's horizontal location by the specified amount of pixels.
10192     *
10193     * @param offset the number of pixels to offset the view by
10194     */
10195    public void offsetLeftAndRight(int offset) {
10196        if (offset != 0) {
10197            updateMatrix();
10198            final boolean matrixIsIdentity = mTransformationInfo == null
10199                    || mTransformationInfo.mMatrixIsIdentity;
10200            if (matrixIsIdentity) {
10201                if (mDisplayList != null) {
10202                    invalidateViewProperty(false, false);
10203                } else {
10204                    final ViewParent p = mParent;
10205                    if (p != null && mAttachInfo != null) {
10206                        final Rect r = mAttachInfo.mTmpInvalRect;
10207                        int minLeft;
10208                        int maxRight;
10209                        if (offset < 0) {
10210                            minLeft = mLeft + offset;
10211                            maxRight = mRight;
10212                        } else {
10213                            minLeft = mLeft;
10214                            maxRight = mRight + offset;
10215                        }
10216                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
10217                        p.invalidateChild(this, r);
10218                    }
10219                }
10220            } else {
10221                invalidateViewProperty(false, false);
10222            }
10223
10224            mLeft += offset;
10225            mRight += offset;
10226            if (mDisplayList != null) {
10227                mDisplayList.offsetLeftAndRight(offset);
10228                invalidateViewProperty(false, false);
10229            } else {
10230                if (!matrixIsIdentity) {
10231                    invalidateViewProperty(false, true);
10232                }
10233                invalidateParentIfNeeded();
10234            }
10235        }
10236    }
10237
10238    /**
10239     * Get the LayoutParams associated with this view. All views should have
10240     * layout parameters. These supply parameters to the <i>parent</i> of this
10241     * view specifying how it should be arranged. There are many subclasses of
10242     * ViewGroup.LayoutParams, and these correspond to the different subclasses
10243     * of ViewGroup that are responsible for arranging their children.
10244     *
10245     * This method may return null if this View is not attached to a parent
10246     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
10247     * was not invoked successfully. When a View is attached to a parent
10248     * ViewGroup, this method must not return null.
10249     *
10250     * @return The LayoutParams associated with this view, or null if no
10251     *         parameters have been set yet
10252     */
10253    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
10254    public ViewGroup.LayoutParams getLayoutParams() {
10255        return mLayoutParams;
10256    }
10257
10258    /**
10259     * Set the layout parameters associated with this view. These supply
10260     * parameters to the <i>parent</i> of this view specifying how it should be
10261     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
10262     * correspond to the different subclasses of ViewGroup that are responsible
10263     * for arranging their children.
10264     *
10265     * @param params The layout parameters for this view, cannot be null
10266     */
10267    public void setLayoutParams(ViewGroup.LayoutParams params) {
10268        if (params == null) {
10269            throw new NullPointerException("Layout parameters cannot be null");
10270        }
10271        mLayoutParams = params;
10272        resolveLayoutParams();
10273        if (mParent instanceof ViewGroup) {
10274            ((ViewGroup) mParent).onSetLayoutParams(this, params);
10275        }
10276        requestLayout();
10277    }
10278
10279    /**
10280     * Resolve the layout parameters depending on the resolved layout direction
10281     *
10282     * @hide
10283     */
10284    public void resolveLayoutParams() {
10285        if (mLayoutParams != null) {
10286            mLayoutParams.resolveLayoutDirection(getLayoutDirection());
10287        }
10288    }
10289
10290    /**
10291     * Set the scrolled position of your view. This will cause a call to
10292     * {@link #onScrollChanged(int, int, int, int)} and the view will be
10293     * invalidated.
10294     * @param x the x position to scroll to
10295     * @param y the y position to scroll to
10296     */
10297    public void scrollTo(int x, int y) {
10298        if (mScrollX != x || mScrollY != y) {
10299            int oldX = mScrollX;
10300            int oldY = mScrollY;
10301            mScrollX = x;
10302            mScrollY = y;
10303            invalidateParentCaches();
10304            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
10305            if (!awakenScrollBars()) {
10306                postInvalidateOnAnimation();
10307            }
10308        }
10309    }
10310
10311    /**
10312     * Move the scrolled position of your view. This will cause a call to
10313     * {@link #onScrollChanged(int, int, int, int)} and the view will be
10314     * invalidated.
10315     * @param x the amount of pixels to scroll by horizontally
10316     * @param y the amount of pixels to scroll by vertically
10317     */
10318    public void scrollBy(int x, int y) {
10319        scrollTo(mScrollX + x, mScrollY + y);
10320    }
10321
10322    /**
10323     * <p>Trigger the scrollbars to draw. When invoked this method starts an
10324     * animation to fade the scrollbars out after a default delay. If a subclass
10325     * provides animated scrolling, the start delay should equal the duration
10326     * of the scrolling animation.</p>
10327     *
10328     * <p>The animation starts only if at least one of the scrollbars is
10329     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
10330     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
10331     * this method returns true, and false otherwise. If the animation is
10332     * started, this method calls {@link #invalidate()}; in that case the
10333     * caller should not call {@link #invalidate()}.</p>
10334     *
10335     * <p>This method should be invoked every time a subclass directly updates
10336     * the scroll parameters.</p>
10337     *
10338     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
10339     * and {@link #scrollTo(int, int)}.</p>
10340     *
10341     * @return true if the animation is played, false otherwise
10342     *
10343     * @see #awakenScrollBars(int)
10344     * @see #scrollBy(int, int)
10345     * @see #scrollTo(int, int)
10346     * @see #isHorizontalScrollBarEnabled()
10347     * @see #isVerticalScrollBarEnabled()
10348     * @see #setHorizontalScrollBarEnabled(boolean)
10349     * @see #setVerticalScrollBarEnabled(boolean)
10350     */
10351    protected boolean awakenScrollBars() {
10352        return mScrollCache != null &&
10353                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
10354    }
10355
10356    /**
10357     * Trigger the scrollbars to draw.
10358     * This method differs from awakenScrollBars() only in its default duration.
10359     * initialAwakenScrollBars() will show the scroll bars for longer than
10360     * usual to give the user more of a chance to notice them.
10361     *
10362     * @return true if the animation is played, false otherwise.
10363     */
10364    private boolean initialAwakenScrollBars() {
10365        return mScrollCache != null &&
10366                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
10367    }
10368
10369    /**
10370     * <p>
10371     * Trigger the scrollbars to draw. When invoked this method starts an
10372     * animation to fade the scrollbars out after a fixed delay. If a subclass
10373     * provides animated scrolling, the start delay should equal the duration of
10374     * the scrolling animation.
10375     * </p>
10376     *
10377     * <p>
10378     * The animation starts only if at least one of the scrollbars is enabled,
10379     * as specified by {@link #isHorizontalScrollBarEnabled()} and
10380     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
10381     * this method returns true, and false otherwise. If the animation is
10382     * started, this method calls {@link #invalidate()}; in that case the caller
10383     * should not call {@link #invalidate()}.
10384     * </p>
10385     *
10386     * <p>
10387     * This method should be invoked everytime a subclass directly updates the
10388     * scroll parameters.
10389     * </p>
10390     *
10391     * @param startDelay the delay, in milliseconds, after which the animation
10392     *        should start; when the delay is 0, the animation starts
10393     *        immediately
10394     * @return true if the animation is played, false otherwise
10395     *
10396     * @see #scrollBy(int, int)
10397     * @see #scrollTo(int, int)
10398     * @see #isHorizontalScrollBarEnabled()
10399     * @see #isVerticalScrollBarEnabled()
10400     * @see #setHorizontalScrollBarEnabled(boolean)
10401     * @see #setVerticalScrollBarEnabled(boolean)
10402     */
10403    protected boolean awakenScrollBars(int startDelay) {
10404        return awakenScrollBars(startDelay, true);
10405    }
10406
10407    /**
10408     * <p>
10409     * Trigger the scrollbars to draw. When invoked this method starts an
10410     * animation to fade the scrollbars out after a fixed delay. If a subclass
10411     * provides animated scrolling, the start delay should equal the duration of
10412     * the scrolling animation.
10413     * </p>
10414     *
10415     * <p>
10416     * The animation starts only if at least one of the scrollbars is enabled,
10417     * as specified by {@link #isHorizontalScrollBarEnabled()} and
10418     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
10419     * this method returns true, and false otherwise. If the animation is
10420     * started, this method calls {@link #invalidate()} if the invalidate parameter
10421     * is set to true; in that case the caller
10422     * should not call {@link #invalidate()}.
10423     * </p>
10424     *
10425     * <p>
10426     * This method should be invoked everytime a subclass directly updates the
10427     * scroll parameters.
10428     * </p>
10429     *
10430     * @param startDelay the delay, in milliseconds, after which the animation
10431     *        should start; when the delay is 0, the animation starts
10432     *        immediately
10433     *
10434     * @param invalidate Wheter this method should call invalidate
10435     *
10436     * @return true if the animation is played, false otherwise
10437     *
10438     * @see #scrollBy(int, int)
10439     * @see #scrollTo(int, int)
10440     * @see #isHorizontalScrollBarEnabled()
10441     * @see #isVerticalScrollBarEnabled()
10442     * @see #setHorizontalScrollBarEnabled(boolean)
10443     * @see #setVerticalScrollBarEnabled(boolean)
10444     */
10445    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
10446        final ScrollabilityCache scrollCache = mScrollCache;
10447
10448        if (scrollCache == null || !scrollCache.fadeScrollBars) {
10449            return false;
10450        }
10451
10452        if (scrollCache.scrollBar == null) {
10453            scrollCache.scrollBar = new ScrollBarDrawable();
10454        }
10455
10456        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
10457
10458            if (invalidate) {
10459                // Invalidate to show the scrollbars
10460                postInvalidateOnAnimation();
10461            }
10462
10463            if (scrollCache.state == ScrollabilityCache.OFF) {
10464                // FIXME: this is copied from WindowManagerService.
10465                // We should get this value from the system when it
10466                // is possible to do so.
10467                final int KEY_REPEAT_FIRST_DELAY = 750;
10468                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
10469            }
10470
10471            // Tell mScrollCache when we should start fading. This may
10472            // extend the fade start time if one was already scheduled
10473            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
10474            scrollCache.fadeStartTime = fadeStartTime;
10475            scrollCache.state = ScrollabilityCache.ON;
10476
10477            // Schedule our fader to run, unscheduling any old ones first
10478            if (mAttachInfo != null) {
10479                mAttachInfo.mHandler.removeCallbacks(scrollCache);
10480                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
10481            }
10482
10483            return true;
10484        }
10485
10486        return false;
10487    }
10488
10489    /**
10490     * Do not invalidate views which are not visible and which are not running an animation. They
10491     * will not get drawn and they should not set dirty flags as if they will be drawn
10492     */
10493    private boolean skipInvalidate() {
10494        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
10495                (!(mParent instanceof ViewGroup) ||
10496                        !((ViewGroup) mParent).isViewTransitioning(this));
10497    }
10498    /**
10499     * Mark the area defined by dirty as needing to be drawn. If the view is
10500     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point
10501     * in the future. This must be called from a UI thread. To call from a non-UI
10502     * thread, call {@link #postInvalidate()}.
10503     *
10504     * WARNING: This method is destructive to dirty.
10505     * @param dirty the rectangle representing the bounds of the dirty region
10506     */
10507    public void invalidate(Rect dirty) {
10508        if (skipInvalidate()) {
10509            return;
10510        }
10511        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) ||
10512                (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID ||
10513                (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED) {
10514            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10515            mPrivateFlags |= PFLAG_INVALIDATED;
10516            mPrivateFlags |= PFLAG_DIRTY;
10517            final ViewParent p = mParent;
10518            final AttachInfo ai = mAttachInfo;
10519            //noinspection PointlessBooleanExpression,ConstantConditions
10520            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10521                if (p != null && ai != null && ai.mHardwareAccelerated) {
10522                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10523                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10524                    p.invalidateChild(this, null);
10525                    return;
10526                }
10527            }
10528            if (p != null && ai != null) {
10529                final int scrollX = mScrollX;
10530                final int scrollY = mScrollY;
10531                final Rect r = ai.mTmpInvalRect;
10532                r.set(dirty.left - scrollX, dirty.top - scrollY,
10533                        dirty.right - scrollX, dirty.bottom - scrollY);
10534                mParent.invalidateChild(this, r);
10535            }
10536        }
10537    }
10538
10539    /**
10540     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn.
10541     * The coordinates of the dirty rect are relative to the view.
10542     * If the view is visible, {@link #onDraw(android.graphics.Canvas)}
10543     * will be called at some point in the future. This must be called from
10544     * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
10545     * @param l the left position of the dirty region
10546     * @param t the top position of the dirty region
10547     * @param r the right position of the dirty region
10548     * @param b the bottom position of the dirty region
10549     */
10550    public void invalidate(int l, int t, int r, int b) {
10551        if (skipInvalidate()) {
10552            return;
10553        }
10554        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) ||
10555                (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID ||
10556                (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED) {
10557            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10558            mPrivateFlags |= PFLAG_INVALIDATED;
10559            mPrivateFlags |= PFLAG_DIRTY;
10560            final ViewParent p = mParent;
10561            final AttachInfo ai = mAttachInfo;
10562            //noinspection PointlessBooleanExpression,ConstantConditions
10563            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10564                if (p != null && ai != null && ai.mHardwareAccelerated) {
10565                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10566                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10567                    p.invalidateChild(this, null);
10568                    return;
10569                }
10570            }
10571            if (p != null && ai != null && l < r && t < b) {
10572                final int scrollX = mScrollX;
10573                final int scrollY = mScrollY;
10574                final Rect tmpr = ai.mTmpInvalRect;
10575                tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
10576                p.invalidateChild(this, tmpr);
10577            }
10578        }
10579    }
10580
10581    /**
10582     * Invalidate the whole view. If the view is visible,
10583     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
10584     * the future. This must be called from a UI thread. To call from a non-UI thread,
10585     * call {@link #postInvalidate()}.
10586     */
10587    public void invalidate() {
10588        invalidate(true);
10589    }
10590
10591    /**
10592     * This is where the invalidate() work actually happens. A full invalidate()
10593     * causes the drawing cache to be invalidated, but this function can be called with
10594     * invalidateCache set to false to skip that invalidation step for cases that do not
10595     * need it (for example, a component that remains at the same dimensions with the same
10596     * content).
10597     *
10598     * @param invalidateCache Whether the drawing cache for this view should be invalidated as
10599     * well. This is usually true for a full invalidate, but may be set to false if the
10600     * View's contents or dimensions have not changed.
10601     */
10602    void invalidate(boolean invalidateCache) {
10603        if (skipInvalidate()) {
10604            return;
10605        }
10606        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) ||
10607                (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) ||
10608                (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED || isOpaque() != mLastIsOpaque) {
10609            mLastIsOpaque = isOpaque();
10610            mPrivateFlags &= ~PFLAG_DRAWN;
10611            mPrivateFlags |= PFLAG_DIRTY;
10612            if (invalidateCache) {
10613                mPrivateFlags |= PFLAG_INVALIDATED;
10614                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10615            }
10616            final AttachInfo ai = mAttachInfo;
10617            final ViewParent p = mParent;
10618            //noinspection PointlessBooleanExpression,ConstantConditions
10619            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10620                if (p != null && ai != null && ai.mHardwareAccelerated) {
10621                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10622                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10623                    p.invalidateChild(this, null);
10624                    return;
10625                }
10626            }
10627
10628            if (p != null && ai != null) {
10629                final Rect r = ai.mTmpInvalRect;
10630                r.set(0, 0, mRight - mLeft, mBottom - mTop);
10631                // Don't call invalidate -- we don't want to internally scroll
10632                // our own bounds
10633                p.invalidateChild(this, r);
10634            }
10635        }
10636    }
10637
10638    /**
10639     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
10640     * set any flags or handle all of the cases handled by the default invalidation methods.
10641     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
10642     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
10643     * walk up the hierarchy, transforming the dirty rect as necessary.
10644     *
10645     * The method also handles normal invalidation logic if display list properties are not
10646     * being used in this view. The invalidateParent and forceRedraw flags are used by that
10647     * backup approach, to handle these cases used in the various property-setting methods.
10648     *
10649     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
10650     * are not being used in this view
10651     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
10652     * list properties are not being used in this view
10653     */
10654    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
10655        if (mDisplayList == null || (mPrivateFlags & PFLAG_DRAW_ANIMATION) == PFLAG_DRAW_ANIMATION) {
10656            if (invalidateParent) {
10657                invalidateParentCaches();
10658            }
10659            if (forceRedraw) {
10660                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10661            }
10662            invalidate(false);
10663        } else {
10664            final AttachInfo ai = mAttachInfo;
10665            final ViewParent p = mParent;
10666            if (p != null && ai != null) {
10667                final Rect r = ai.mTmpInvalRect;
10668                r.set(0, 0, mRight - mLeft, mBottom - mTop);
10669                if (mParent instanceof ViewGroup) {
10670                    ((ViewGroup) mParent).invalidateChildFast(this, r);
10671                } else {
10672                    mParent.invalidateChild(this, r);
10673                }
10674            }
10675        }
10676    }
10677
10678    /**
10679     * Utility method to transform a given Rect by the current matrix of this view.
10680     */
10681    void transformRect(final Rect rect) {
10682        if (!getMatrix().isIdentity()) {
10683            RectF boundingRect = mAttachInfo.mTmpTransformRect;
10684            boundingRect.set(rect);
10685            getMatrix().mapRect(boundingRect);
10686            rect.set((int) Math.floor(boundingRect.left),
10687                    (int) Math.floor(boundingRect.top),
10688                    (int) Math.ceil(boundingRect.right),
10689                    (int) Math.ceil(boundingRect.bottom));
10690        }
10691    }
10692
10693    /**
10694     * Used to indicate that the parent of this view should clear its caches. This functionality
10695     * is used to force the parent to rebuild its display list (when hardware-accelerated),
10696     * which is necessary when various parent-managed properties of the view change, such as
10697     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
10698     * clears the parent caches and does not causes an invalidate event.
10699     *
10700     * @hide
10701     */
10702    protected void invalidateParentCaches() {
10703        if (mParent instanceof View) {
10704            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
10705        }
10706    }
10707
10708    /**
10709     * Used to indicate that the parent of this view should be invalidated. This functionality
10710     * is used to force the parent to rebuild its display list (when hardware-accelerated),
10711     * which is necessary when various parent-managed properties of the view change, such as
10712     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
10713     * an invalidation event to the parent.
10714     *
10715     * @hide
10716     */
10717    protected void invalidateParentIfNeeded() {
10718        if (isHardwareAccelerated() && mParent instanceof View) {
10719            ((View) mParent).invalidate(true);
10720        }
10721    }
10722
10723    /**
10724     * Indicates whether this View is opaque. An opaque View guarantees that it will
10725     * draw all the pixels overlapping its bounds using a fully opaque color.
10726     *
10727     * Subclasses of View should override this method whenever possible to indicate
10728     * whether an instance is opaque. Opaque Views are treated in a special way by
10729     * the View hierarchy, possibly allowing it to perform optimizations during
10730     * invalidate/draw passes.
10731     *
10732     * @return True if this View is guaranteed to be fully opaque, false otherwise.
10733     */
10734    @ViewDebug.ExportedProperty(category = "drawing")
10735    public boolean isOpaque() {
10736        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
10737                ((mTransformationInfo != null ? mTransformationInfo.mAlpha : 1.0f) >= 1.0f);
10738    }
10739
10740    /**
10741     * @hide
10742     */
10743    protected void computeOpaqueFlags() {
10744        // Opaque if:
10745        //   - Has a background
10746        //   - Background is opaque
10747        //   - Doesn't have scrollbars or scrollbars overlay
10748
10749        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
10750            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
10751        } else {
10752            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
10753        }
10754
10755        final int flags = mViewFlags;
10756        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
10757                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY ||
10758                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) {
10759            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
10760        } else {
10761            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
10762        }
10763    }
10764
10765    /**
10766     * @hide
10767     */
10768    protected boolean hasOpaqueScrollbars() {
10769        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
10770    }
10771
10772    /**
10773     * @return A handler associated with the thread running the View. This
10774     * handler can be used to pump events in the UI events queue.
10775     */
10776    public Handler getHandler() {
10777        final AttachInfo attachInfo = mAttachInfo;
10778        if (attachInfo != null) {
10779            return attachInfo.mHandler;
10780        }
10781        return null;
10782    }
10783
10784    /**
10785     * Gets the view root associated with the View.
10786     * @return The view root, or null if none.
10787     * @hide
10788     */
10789    public ViewRootImpl getViewRootImpl() {
10790        if (mAttachInfo != null) {
10791            return mAttachInfo.mViewRootImpl;
10792        }
10793        return null;
10794    }
10795
10796    /**
10797     * <p>Causes the Runnable to be added to the message queue.
10798     * The runnable will be run on the user interface thread.</p>
10799     *
10800     * @param action The Runnable that will be executed.
10801     *
10802     * @return Returns true if the Runnable was successfully placed in to the
10803     *         message queue.  Returns false on failure, usually because the
10804     *         looper processing the message queue is exiting.
10805     *
10806     * @see #postDelayed
10807     * @see #removeCallbacks
10808     */
10809    public boolean post(Runnable action) {
10810        final AttachInfo attachInfo = mAttachInfo;
10811        if (attachInfo != null) {
10812            return attachInfo.mHandler.post(action);
10813        }
10814        // Assume that post will succeed later
10815        ViewRootImpl.getRunQueue().post(action);
10816        return true;
10817    }
10818
10819    /**
10820     * <p>Causes the Runnable to be added to the message queue, to be run
10821     * after the specified amount of time elapses.
10822     * The runnable will be run on the user interface thread.</p>
10823     *
10824     * @param action The Runnable that will be executed.
10825     * @param delayMillis The delay (in milliseconds) until the Runnable
10826     *        will be executed.
10827     *
10828     * @return true if the Runnable was successfully placed in to the
10829     *         message queue.  Returns false on failure, usually because the
10830     *         looper processing the message queue is exiting.  Note that a
10831     *         result of true does not mean the Runnable will be processed --
10832     *         if the looper is quit before the delivery time of the message
10833     *         occurs then the message will be dropped.
10834     *
10835     * @see #post
10836     * @see #removeCallbacks
10837     */
10838    public boolean postDelayed(Runnable action, long delayMillis) {
10839        final AttachInfo attachInfo = mAttachInfo;
10840        if (attachInfo != null) {
10841            return attachInfo.mHandler.postDelayed(action, delayMillis);
10842        }
10843        // Assume that post will succeed later
10844        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
10845        return true;
10846    }
10847
10848    /**
10849     * <p>Causes the Runnable to execute on the next animation time step.
10850     * The runnable will be run on the user interface thread.</p>
10851     *
10852     * @param action The Runnable that will be executed.
10853     *
10854     * @see #postOnAnimationDelayed
10855     * @see #removeCallbacks
10856     */
10857    public void postOnAnimation(Runnable action) {
10858        final AttachInfo attachInfo = mAttachInfo;
10859        if (attachInfo != null) {
10860            attachInfo.mViewRootImpl.mChoreographer.postCallback(
10861                    Choreographer.CALLBACK_ANIMATION, action, null);
10862        } else {
10863            // Assume that post will succeed later
10864            ViewRootImpl.getRunQueue().post(action);
10865        }
10866    }
10867
10868    /**
10869     * <p>Causes the Runnable to execute on the next animation time step,
10870     * after the specified amount of time elapses.
10871     * The runnable will be run on the user interface thread.</p>
10872     *
10873     * @param action The Runnable that will be executed.
10874     * @param delayMillis The delay (in milliseconds) until the Runnable
10875     *        will be executed.
10876     *
10877     * @see #postOnAnimation
10878     * @see #removeCallbacks
10879     */
10880    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
10881        final AttachInfo attachInfo = mAttachInfo;
10882        if (attachInfo != null) {
10883            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
10884                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
10885        } else {
10886            // Assume that post will succeed later
10887            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
10888        }
10889    }
10890
10891    /**
10892     * <p>Removes the specified Runnable from the message queue.</p>
10893     *
10894     * @param action The Runnable to remove from the message handling queue
10895     *
10896     * @return true if this view could ask the Handler to remove the Runnable,
10897     *         false otherwise. When the returned value is true, the Runnable
10898     *         may or may not have been actually removed from the message queue
10899     *         (for instance, if the Runnable was not in the queue already.)
10900     *
10901     * @see #post
10902     * @see #postDelayed
10903     * @see #postOnAnimation
10904     * @see #postOnAnimationDelayed
10905     */
10906    public boolean removeCallbacks(Runnable action) {
10907        if (action != null) {
10908            final AttachInfo attachInfo = mAttachInfo;
10909            if (attachInfo != null) {
10910                attachInfo.mHandler.removeCallbacks(action);
10911                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
10912                        Choreographer.CALLBACK_ANIMATION, action, null);
10913            } else {
10914                // Assume that post will succeed later
10915                ViewRootImpl.getRunQueue().removeCallbacks(action);
10916            }
10917        }
10918        return true;
10919    }
10920
10921    /**
10922     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
10923     * Use this to invalidate the View from a non-UI thread.</p>
10924     *
10925     * <p>This method can be invoked from outside of the UI thread
10926     * only when this View is attached to a window.</p>
10927     *
10928     * @see #invalidate()
10929     * @see #postInvalidateDelayed(long)
10930     */
10931    public void postInvalidate() {
10932        postInvalidateDelayed(0);
10933    }
10934
10935    /**
10936     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
10937     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
10938     *
10939     * <p>This method can be invoked from outside of the UI thread
10940     * only when this View is attached to a window.</p>
10941     *
10942     * @param left The left coordinate of the rectangle to invalidate.
10943     * @param top The top coordinate of the rectangle to invalidate.
10944     * @param right The right coordinate of the rectangle to invalidate.
10945     * @param bottom The bottom coordinate of the rectangle to invalidate.
10946     *
10947     * @see #invalidate(int, int, int, int)
10948     * @see #invalidate(Rect)
10949     * @see #postInvalidateDelayed(long, int, int, int, int)
10950     */
10951    public void postInvalidate(int left, int top, int right, int bottom) {
10952        postInvalidateDelayed(0, left, top, right, bottom);
10953    }
10954
10955    /**
10956     * <p>Cause an invalidate to happen on a subsequent cycle through the event
10957     * loop. Waits for the specified amount of time.</p>
10958     *
10959     * <p>This method can be invoked from outside of the UI thread
10960     * only when this View is attached to a window.</p>
10961     *
10962     * @param delayMilliseconds the duration in milliseconds to delay the
10963     *         invalidation by
10964     *
10965     * @see #invalidate()
10966     * @see #postInvalidate()
10967     */
10968    public void postInvalidateDelayed(long delayMilliseconds) {
10969        // We try only with the AttachInfo because there's no point in invalidating
10970        // if we are not attached to our window
10971        final AttachInfo attachInfo = mAttachInfo;
10972        if (attachInfo != null) {
10973            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
10974        }
10975    }
10976
10977    /**
10978     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
10979     * through the event loop. Waits for the specified amount of time.</p>
10980     *
10981     * <p>This method can be invoked from outside of the UI thread
10982     * only when this View is attached to a window.</p>
10983     *
10984     * @param delayMilliseconds the duration in milliseconds to delay the
10985     *         invalidation by
10986     * @param left The left coordinate of the rectangle to invalidate.
10987     * @param top The top coordinate of the rectangle to invalidate.
10988     * @param right The right coordinate of the rectangle to invalidate.
10989     * @param bottom The bottom coordinate of the rectangle to invalidate.
10990     *
10991     * @see #invalidate(int, int, int, int)
10992     * @see #invalidate(Rect)
10993     * @see #postInvalidate(int, int, int, int)
10994     */
10995    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
10996            int right, int bottom) {
10997
10998        // We try only with the AttachInfo because there's no point in invalidating
10999        // if we are not attached to our window
11000        final AttachInfo attachInfo = mAttachInfo;
11001        if (attachInfo != null) {
11002            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
11003            info.target = this;
11004            info.left = left;
11005            info.top = top;
11006            info.right = right;
11007            info.bottom = bottom;
11008
11009            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
11010        }
11011    }
11012
11013    /**
11014     * <p>Cause an invalidate to happen on the next animation time step, typically the
11015     * next display frame.</p>
11016     *
11017     * <p>This method can be invoked from outside of the UI thread
11018     * only when this View is attached to a window.</p>
11019     *
11020     * @see #invalidate()
11021     */
11022    public void postInvalidateOnAnimation() {
11023        // We try only with the AttachInfo because there's no point in invalidating
11024        // if we are not attached to our window
11025        final AttachInfo attachInfo = mAttachInfo;
11026        if (attachInfo != null) {
11027            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
11028        }
11029    }
11030
11031    /**
11032     * <p>Cause an invalidate of the specified area to happen on the next animation
11033     * time step, typically the next display frame.</p>
11034     *
11035     * <p>This method can be invoked from outside of the UI thread
11036     * only when this View is attached to a window.</p>
11037     *
11038     * @param left The left coordinate of the rectangle to invalidate.
11039     * @param top The top coordinate of the rectangle to invalidate.
11040     * @param right The right coordinate of the rectangle to invalidate.
11041     * @param bottom The bottom coordinate of the rectangle to invalidate.
11042     *
11043     * @see #invalidate(int, int, int, int)
11044     * @see #invalidate(Rect)
11045     */
11046    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
11047        // We try only with the AttachInfo because there's no point in invalidating
11048        // if we are not attached to our window
11049        final AttachInfo attachInfo = mAttachInfo;
11050        if (attachInfo != null) {
11051            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
11052            info.target = this;
11053            info.left = left;
11054            info.top = top;
11055            info.right = right;
11056            info.bottom = bottom;
11057
11058            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
11059        }
11060    }
11061
11062    /**
11063     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
11064     * This event is sent at most once every
11065     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
11066     */
11067    private void postSendViewScrolledAccessibilityEventCallback() {
11068        if (mSendViewScrolledAccessibilityEvent == null) {
11069            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
11070        }
11071        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
11072            mSendViewScrolledAccessibilityEvent.mIsPending = true;
11073            postDelayed(mSendViewScrolledAccessibilityEvent,
11074                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
11075        }
11076    }
11077
11078    /**
11079     * Called by a parent to request that a child update its values for mScrollX
11080     * and mScrollY if necessary. This will typically be done if the child is
11081     * animating a scroll using a {@link android.widget.Scroller Scroller}
11082     * object.
11083     */
11084    public void computeScroll() {
11085    }
11086
11087    /**
11088     * <p>Indicate whether the horizontal edges are faded when the view is
11089     * scrolled horizontally.</p>
11090     *
11091     * @return true if the horizontal edges should are faded on scroll, false
11092     *         otherwise
11093     *
11094     * @see #setHorizontalFadingEdgeEnabled(boolean)
11095     *
11096     * @attr ref android.R.styleable#View_requiresFadingEdge
11097     */
11098    public boolean isHorizontalFadingEdgeEnabled() {
11099        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
11100    }
11101
11102    /**
11103     * <p>Define whether the horizontal edges should be faded when this view
11104     * is scrolled horizontally.</p>
11105     *
11106     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
11107     *                                    be faded when the view is scrolled
11108     *                                    horizontally
11109     *
11110     * @see #isHorizontalFadingEdgeEnabled()
11111     *
11112     * @attr ref android.R.styleable#View_requiresFadingEdge
11113     */
11114    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
11115        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
11116            if (horizontalFadingEdgeEnabled) {
11117                initScrollCache();
11118            }
11119
11120            mViewFlags ^= FADING_EDGE_HORIZONTAL;
11121        }
11122    }
11123
11124    /**
11125     * <p>Indicate whether the vertical edges are faded when the view is
11126     * scrolled horizontally.</p>
11127     *
11128     * @return true if the vertical edges should are faded on scroll, false
11129     *         otherwise
11130     *
11131     * @see #setVerticalFadingEdgeEnabled(boolean)
11132     *
11133     * @attr ref android.R.styleable#View_requiresFadingEdge
11134     */
11135    public boolean isVerticalFadingEdgeEnabled() {
11136        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
11137    }
11138
11139    /**
11140     * <p>Define whether the vertical edges should be faded when this view
11141     * is scrolled vertically.</p>
11142     *
11143     * @param verticalFadingEdgeEnabled true if the vertical edges should
11144     *                                  be faded when the view is scrolled
11145     *                                  vertically
11146     *
11147     * @see #isVerticalFadingEdgeEnabled()
11148     *
11149     * @attr ref android.R.styleable#View_requiresFadingEdge
11150     */
11151    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
11152        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
11153            if (verticalFadingEdgeEnabled) {
11154                initScrollCache();
11155            }
11156
11157            mViewFlags ^= FADING_EDGE_VERTICAL;
11158        }
11159    }
11160
11161    /**
11162     * Returns the strength, or intensity, of the top faded edge. The strength is
11163     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11164     * returns 0.0 or 1.0 but no value in between.
11165     *
11166     * Subclasses should override this method to provide a smoother fade transition
11167     * when scrolling occurs.
11168     *
11169     * @return the intensity of the top fade as a float between 0.0f and 1.0f
11170     */
11171    protected float getTopFadingEdgeStrength() {
11172        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
11173    }
11174
11175    /**
11176     * Returns the strength, or intensity, of the bottom faded edge. The strength is
11177     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11178     * returns 0.0 or 1.0 but no value in between.
11179     *
11180     * Subclasses should override this method to provide a smoother fade transition
11181     * when scrolling occurs.
11182     *
11183     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
11184     */
11185    protected float getBottomFadingEdgeStrength() {
11186        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
11187                computeVerticalScrollRange() ? 1.0f : 0.0f;
11188    }
11189
11190    /**
11191     * Returns the strength, or intensity, of the left faded edge. The strength is
11192     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11193     * returns 0.0 or 1.0 but no value in between.
11194     *
11195     * Subclasses should override this method to provide a smoother fade transition
11196     * when scrolling occurs.
11197     *
11198     * @return the intensity of the left fade as a float between 0.0f and 1.0f
11199     */
11200    protected float getLeftFadingEdgeStrength() {
11201        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
11202    }
11203
11204    /**
11205     * Returns the strength, or intensity, of the right faded edge. The strength is
11206     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11207     * returns 0.0 or 1.0 but no value in between.
11208     *
11209     * Subclasses should override this method to provide a smoother fade transition
11210     * when scrolling occurs.
11211     *
11212     * @return the intensity of the right fade as a float between 0.0f and 1.0f
11213     */
11214    protected float getRightFadingEdgeStrength() {
11215        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
11216                computeHorizontalScrollRange() ? 1.0f : 0.0f;
11217    }
11218
11219    /**
11220     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
11221     * scrollbar is not drawn by default.</p>
11222     *
11223     * @return true if the horizontal scrollbar should be painted, false
11224     *         otherwise
11225     *
11226     * @see #setHorizontalScrollBarEnabled(boolean)
11227     */
11228    public boolean isHorizontalScrollBarEnabled() {
11229        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
11230    }
11231
11232    /**
11233     * <p>Define whether the horizontal scrollbar should be drawn or not. The
11234     * scrollbar is not drawn by default.</p>
11235     *
11236     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
11237     *                                   be painted
11238     *
11239     * @see #isHorizontalScrollBarEnabled()
11240     */
11241    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
11242        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
11243            mViewFlags ^= SCROLLBARS_HORIZONTAL;
11244            computeOpaqueFlags();
11245            resolvePadding();
11246        }
11247    }
11248
11249    /**
11250     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
11251     * scrollbar is not drawn by default.</p>
11252     *
11253     * @return true if the vertical scrollbar should be painted, false
11254     *         otherwise
11255     *
11256     * @see #setVerticalScrollBarEnabled(boolean)
11257     */
11258    public boolean isVerticalScrollBarEnabled() {
11259        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
11260    }
11261
11262    /**
11263     * <p>Define whether the vertical scrollbar should be drawn or not. The
11264     * scrollbar is not drawn by default.</p>
11265     *
11266     * @param verticalScrollBarEnabled true if the vertical scrollbar should
11267     *                                 be painted
11268     *
11269     * @see #isVerticalScrollBarEnabled()
11270     */
11271    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
11272        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
11273            mViewFlags ^= SCROLLBARS_VERTICAL;
11274            computeOpaqueFlags();
11275            resolvePadding();
11276        }
11277    }
11278
11279    /**
11280     * @hide
11281     */
11282    protected void recomputePadding() {
11283        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
11284    }
11285
11286    /**
11287     * Define whether scrollbars will fade when the view is not scrolling.
11288     *
11289     * @param fadeScrollbars wheter to enable fading
11290     *
11291     * @attr ref android.R.styleable#View_fadeScrollbars
11292     */
11293    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
11294        initScrollCache();
11295        final ScrollabilityCache scrollabilityCache = mScrollCache;
11296        scrollabilityCache.fadeScrollBars = fadeScrollbars;
11297        if (fadeScrollbars) {
11298            scrollabilityCache.state = ScrollabilityCache.OFF;
11299        } else {
11300            scrollabilityCache.state = ScrollabilityCache.ON;
11301        }
11302    }
11303
11304    /**
11305     *
11306     * Returns true if scrollbars will fade when this view is not scrolling
11307     *
11308     * @return true if scrollbar fading is enabled
11309     *
11310     * @attr ref android.R.styleable#View_fadeScrollbars
11311     */
11312    public boolean isScrollbarFadingEnabled() {
11313        return mScrollCache != null && mScrollCache.fadeScrollBars;
11314    }
11315
11316    /**
11317     *
11318     * Returns the delay before scrollbars fade.
11319     *
11320     * @return the delay before scrollbars fade
11321     *
11322     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
11323     */
11324    public int getScrollBarDefaultDelayBeforeFade() {
11325        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
11326                mScrollCache.scrollBarDefaultDelayBeforeFade;
11327    }
11328
11329    /**
11330     * Define the delay before scrollbars fade.
11331     *
11332     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
11333     *
11334     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
11335     */
11336    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
11337        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
11338    }
11339
11340    /**
11341     *
11342     * Returns the scrollbar fade duration.
11343     *
11344     * @return the scrollbar fade duration
11345     *
11346     * @attr ref android.R.styleable#View_scrollbarFadeDuration
11347     */
11348    public int getScrollBarFadeDuration() {
11349        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
11350                mScrollCache.scrollBarFadeDuration;
11351    }
11352
11353    /**
11354     * Define the scrollbar fade duration.
11355     *
11356     * @param scrollBarFadeDuration - the scrollbar fade duration
11357     *
11358     * @attr ref android.R.styleable#View_scrollbarFadeDuration
11359     */
11360    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
11361        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
11362    }
11363
11364    /**
11365     *
11366     * Returns the scrollbar size.
11367     *
11368     * @return the scrollbar size
11369     *
11370     * @attr ref android.R.styleable#View_scrollbarSize
11371     */
11372    public int getScrollBarSize() {
11373        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
11374                mScrollCache.scrollBarSize;
11375    }
11376
11377    /**
11378     * Define the scrollbar size.
11379     *
11380     * @param scrollBarSize - the scrollbar size
11381     *
11382     * @attr ref android.R.styleable#View_scrollbarSize
11383     */
11384    public void setScrollBarSize(int scrollBarSize) {
11385        getScrollCache().scrollBarSize = scrollBarSize;
11386    }
11387
11388    /**
11389     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
11390     * inset. When inset, they add to the padding of the view. And the scrollbars
11391     * can be drawn inside the padding area or on the edge of the view. For example,
11392     * if a view has a background drawable and you want to draw the scrollbars
11393     * inside the padding specified by the drawable, you can use
11394     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
11395     * appear at the edge of the view, ignoring the padding, then you can use
11396     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
11397     * @param style the style of the scrollbars. Should be one of
11398     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
11399     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
11400     * @see #SCROLLBARS_INSIDE_OVERLAY
11401     * @see #SCROLLBARS_INSIDE_INSET
11402     * @see #SCROLLBARS_OUTSIDE_OVERLAY
11403     * @see #SCROLLBARS_OUTSIDE_INSET
11404     *
11405     * @attr ref android.R.styleable#View_scrollbarStyle
11406     */
11407    public void setScrollBarStyle(int style) {
11408        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
11409            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
11410            computeOpaqueFlags();
11411            resolvePadding();
11412        }
11413    }
11414
11415    /**
11416     * <p>Returns the current scrollbar style.</p>
11417     * @return the current scrollbar style
11418     * @see #SCROLLBARS_INSIDE_OVERLAY
11419     * @see #SCROLLBARS_INSIDE_INSET
11420     * @see #SCROLLBARS_OUTSIDE_OVERLAY
11421     * @see #SCROLLBARS_OUTSIDE_INSET
11422     *
11423     * @attr ref android.R.styleable#View_scrollbarStyle
11424     */
11425    @ViewDebug.ExportedProperty(mapping = {
11426            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
11427            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
11428            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
11429            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
11430    })
11431    public int getScrollBarStyle() {
11432        return mViewFlags & SCROLLBARS_STYLE_MASK;
11433    }
11434
11435    /**
11436     * <p>Compute the horizontal range that the horizontal scrollbar
11437     * represents.</p>
11438     *
11439     * <p>The range is expressed in arbitrary units that must be the same as the
11440     * units used by {@link #computeHorizontalScrollExtent()} and
11441     * {@link #computeHorizontalScrollOffset()}.</p>
11442     *
11443     * <p>The default range is the drawing width of this view.</p>
11444     *
11445     * @return the total horizontal range represented by the horizontal
11446     *         scrollbar
11447     *
11448     * @see #computeHorizontalScrollExtent()
11449     * @see #computeHorizontalScrollOffset()
11450     * @see android.widget.ScrollBarDrawable
11451     */
11452    protected int computeHorizontalScrollRange() {
11453        return getWidth();
11454    }
11455
11456    /**
11457     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
11458     * within the horizontal range. This value is used to compute the position
11459     * of the thumb within the scrollbar's track.</p>
11460     *
11461     * <p>The range is expressed in arbitrary units that must be the same as the
11462     * units used by {@link #computeHorizontalScrollRange()} and
11463     * {@link #computeHorizontalScrollExtent()}.</p>
11464     *
11465     * <p>The default offset is the scroll offset of this view.</p>
11466     *
11467     * @return the horizontal offset of the scrollbar's thumb
11468     *
11469     * @see #computeHorizontalScrollRange()
11470     * @see #computeHorizontalScrollExtent()
11471     * @see android.widget.ScrollBarDrawable
11472     */
11473    protected int computeHorizontalScrollOffset() {
11474        return mScrollX;
11475    }
11476
11477    /**
11478     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
11479     * within the horizontal range. This value is used to compute the length
11480     * of the thumb within the scrollbar's track.</p>
11481     *
11482     * <p>The range is expressed in arbitrary units that must be the same as the
11483     * units used by {@link #computeHorizontalScrollRange()} and
11484     * {@link #computeHorizontalScrollOffset()}.</p>
11485     *
11486     * <p>The default extent is the drawing width of this view.</p>
11487     *
11488     * @return the horizontal extent of the scrollbar's thumb
11489     *
11490     * @see #computeHorizontalScrollRange()
11491     * @see #computeHorizontalScrollOffset()
11492     * @see android.widget.ScrollBarDrawable
11493     */
11494    protected int computeHorizontalScrollExtent() {
11495        return getWidth();
11496    }
11497
11498    /**
11499     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
11500     *
11501     * <p>The range is expressed in arbitrary units that must be the same as the
11502     * units used by {@link #computeVerticalScrollExtent()} and
11503     * {@link #computeVerticalScrollOffset()}.</p>
11504     *
11505     * @return the total vertical range represented by the vertical scrollbar
11506     *
11507     * <p>The default range is the drawing height of this view.</p>
11508     *
11509     * @see #computeVerticalScrollExtent()
11510     * @see #computeVerticalScrollOffset()
11511     * @see android.widget.ScrollBarDrawable
11512     */
11513    protected int computeVerticalScrollRange() {
11514        return getHeight();
11515    }
11516
11517    /**
11518     * <p>Compute the vertical offset of the vertical scrollbar's thumb
11519     * within the horizontal range. This value is used to compute the position
11520     * of the thumb within the scrollbar's track.</p>
11521     *
11522     * <p>The range is expressed in arbitrary units that must be the same as the
11523     * units used by {@link #computeVerticalScrollRange()} and
11524     * {@link #computeVerticalScrollExtent()}.</p>
11525     *
11526     * <p>The default offset is the scroll offset of this view.</p>
11527     *
11528     * @return the vertical offset of the scrollbar's thumb
11529     *
11530     * @see #computeVerticalScrollRange()
11531     * @see #computeVerticalScrollExtent()
11532     * @see android.widget.ScrollBarDrawable
11533     */
11534    protected int computeVerticalScrollOffset() {
11535        return mScrollY;
11536    }
11537
11538    /**
11539     * <p>Compute the vertical extent of the horizontal scrollbar's thumb
11540     * within the vertical range. This value is used to compute the length
11541     * of the thumb within the scrollbar's track.</p>
11542     *
11543     * <p>The range is expressed in arbitrary units that must be the same as the
11544     * units used by {@link #computeVerticalScrollRange()} and
11545     * {@link #computeVerticalScrollOffset()}.</p>
11546     *
11547     * <p>The default extent is the drawing height of this view.</p>
11548     *
11549     * @return the vertical extent of the scrollbar's thumb
11550     *
11551     * @see #computeVerticalScrollRange()
11552     * @see #computeVerticalScrollOffset()
11553     * @see android.widget.ScrollBarDrawable
11554     */
11555    protected int computeVerticalScrollExtent() {
11556        return getHeight();
11557    }
11558
11559    /**
11560     * Check if this view can be scrolled horizontally in a certain direction.
11561     *
11562     * @param direction Negative to check scrolling left, positive to check scrolling right.
11563     * @return true if this view can be scrolled in the specified direction, false otherwise.
11564     */
11565    public boolean canScrollHorizontally(int direction) {
11566        final int offset = computeHorizontalScrollOffset();
11567        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
11568        if (range == 0) return false;
11569        if (direction < 0) {
11570            return offset > 0;
11571        } else {
11572            return offset < range - 1;
11573        }
11574    }
11575
11576    /**
11577     * Check if this view can be scrolled vertically in a certain direction.
11578     *
11579     * @param direction Negative to check scrolling up, positive to check scrolling down.
11580     * @return true if this view can be scrolled in the specified direction, false otherwise.
11581     */
11582    public boolean canScrollVertically(int direction) {
11583        final int offset = computeVerticalScrollOffset();
11584        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
11585        if (range == 0) return false;
11586        if (direction < 0) {
11587            return offset > 0;
11588        } else {
11589            return offset < range - 1;
11590        }
11591    }
11592
11593    /**
11594     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
11595     * scrollbars are painted only if they have been awakened first.</p>
11596     *
11597     * @param canvas the canvas on which to draw the scrollbars
11598     *
11599     * @see #awakenScrollBars(int)
11600     */
11601    protected final void onDrawScrollBars(Canvas canvas) {
11602        // scrollbars are drawn only when the animation is running
11603        final ScrollabilityCache cache = mScrollCache;
11604        if (cache != null) {
11605
11606            int state = cache.state;
11607
11608            if (state == ScrollabilityCache.OFF) {
11609                return;
11610            }
11611
11612            boolean invalidate = false;
11613
11614            if (state == ScrollabilityCache.FADING) {
11615                // We're fading -- get our fade interpolation
11616                if (cache.interpolatorValues == null) {
11617                    cache.interpolatorValues = new float[1];
11618                }
11619
11620                float[] values = cache.interpolatorValues;
11621
11622                // Stops the animation if we're done
11623                if (cache.scrollBarInterpolator.timeToValues(values) ==
11624                        Interpolator.Result.FREEZE_END) {
11625                    cache.state = ScrollabilityCache.OFF;
11626                } else {
11627                    cache.scrollBar.setAlpha(Math.round(values[0]));
11628                }
11629
11630                // This will make the scroll bars inval themselves after
11631                // drawing. We only want this when we're fading so that
11632                // we prevent excessive redraws
11633                invalidate = true;
11634            } else {
11635                // We're just on -- but we may have been fading before so
11636                // reset alpha
11637                cache.scrollBar.setAlpha(255);
11638            }
11639
11640
11641            final int viewFlags = mViewFlags;
11642
11643            final boolean drawHorizontalScrollBar =
11644                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
11645            final boolean drawVerticalScrollBar =
11646                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
11647                && !isVerticalScrollBarHidden();
11648
11649            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
11650                final int width = mRight - mLeft;
11651                final int height = mBottom - mTop;
11652
11653                final ScrollBarDrawable scrollBar = cache.scrollBar;
11654
11655                final int scrollX = mScrollX;
11656                final int scrollY = mScrollY;
11657                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
11658
11659                int left;
11660                int top;
11661                int right;
11662                int bottom;
11663
11664                if (drawHorizontalScrollBar) {
11665                    int size = scrollBar.getSize(false);
11666                    if (size <= 0) {
11667                        size = cache.scrollBarSize;
11668                    }
11669
11670                    scrollBar.setParameters(computeHorizontalScrollRange(),
11671                                            computeHorizontalScrollOffset(),
11672                                            computeHorizontalScrollExtent(), false);
11673                    final int verticalScrollBarGap = drawVerticalScrollBar ?
11674                            getVerticalScrollbarWidth() : 0;
11675                    top = scrollY + height - size - (mUserPaddingBottom & inside);
11676                    left = scrollX + (mPaddingLeft & inside);
11677                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
11678                    bottom = top + size;
11679                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
11680                    if (invalidate) {
11681                        invalidate(left, top, right, bottom);
11682                    }
11683                }
11684
11685                if (drawVerticalScrollBar) {
11686                    int size = scrollBar.getSize(true);
11687                    if (size <= 0) {
11688                        size = cache.scrollBarSize;
11689                    }
11690
11691                    scrollBar.setParameters(computeVerticalScrollRange(),
11692                                            computeVerticalScrollOffset(),
11693                                            computeVerticalScrollExtent(), true);
11694                    int verticalScrollbarPosition = mVerticalScrollbarPosition;
11695                    if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
11696                        verticalScrollbarPosition = isLayoutRtl() ?
11697                                SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
11698                    }
11699                    switch (verticalScrollbarPosition) {
11700                        default:
11701                        case SCROLLBAR_POSITION_RIGHT:
11702                            left = scrollX + width - size - (mUserPaddingRight & inside);
11703                            break;
11704                        case SCROLLBAR_POSITION_LEFT:
11705                            left = scrollX + (mUserPaddingLeft & inside);
11706                            break;
11707                    }
11708                    top = scrollY + (mPaddingTop & inside);
11709                    right = left + size;
11710                    bottom = scrollY + height - (mUserPaddingBottom & inside);
11711                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
11712                    if (invalidate) {
11713                        invalidate(left, top, right, bottom);
11714                    }
11715                }
11716            }
11717        }
11718    }
11719
11720    /**
11721     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
11722     * FastScroller is visible.
11723     * @return whether to temporarily hide the vertical scrollbar
11724     * @hide
11725     */
11726    protected boolean isVerticalScrollBarHidden() {
11727        return false;
11728    }
11729
11730    /**
11731     * <p>Draw the horizontal scrollbar if
11732     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
11733     *
11734     * @param canvas the canvas on which to draw the scrollbar
11735     * @param scrollBar the scrollbar's drawable
11736     *
11737     * @see #isHorizontalScrollBarEnabled()
11738     * @see #computeHorizontalScrollRange()
11739     * @see #computeHorizontalScrollExtent()
11740     * @see #computeHorizontalScrollOffset()
11741     * @see android.widget.ScrollBarDrawable
11742     * @hide
11743     */
11744    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
11745            int l, int t, int r, int b) {
11746        scrollBar.setBounds(l, t, r, b);
11747        scrollBar.draw(canvas);
11748    }
11749
11750    /**
11751     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
11752     * returns true.</p>
11753     *
11754     * @param canvas the canvas on which to draw the scrollbar
11755     * @param scrollBar the scrollbar's drawable
11756     *
11757     * @see #isVerticalScrollBarEnabled()
11758     * @see #computeVerticalScrollRange()
11759     * @see #computeVerticalScrollExtent()
11760     * @see #computeVerticalScrollOffset()
11761     * @see android.widget.ScrollBarDrawable
11762     * @hide
11763     */
11764    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
11765            int l, int t, int r, int b) {
11766        scrollBar.setBounds(l, t, r, b);
11767        scrollBar.draw(canvas);
11768    }
11769
11770    /**
11771     * Implement this to do your drawing.
11772     *
11773     * @param canvas the canvas on which the background will be drawn
11774     */
11775    protected void onDraw(Canvas canvas) {
11776    }
11777
11778    /*
11779     * Caller is responsible for calling requestLayout if necessary.
11780     * (This allows addViewInLayout to not request a new layout.)
11781     */
11782    void assignParent(ViewParent parent) {
11783        if (mParent == null) {
11784            mParent = parent;
11785        } else if (parent == null) {
11786            mParent = null;
11787        } else {
11788            throw new RuntimeException("view " + this + " being added, but"
11789                    + " it already has a parent");
11790        }
11791    }
11792
11793    /**
11794     * This is called when the view is attached to a window.  At this point it
11795     * has a Surface and will start drawing.  Note that this function is
11796     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
11797     * however it may be called any time before the first onDraw -- including
11798     * before or after {@link #onMeasure(int, int)}.
11799     *
11800     * @see #onDetachedFromWindow()
11801     */
11802    protected void onAttachedToWindow() {
11803        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
11804            mParent.requestTransparentRegion(this);
11805        }
11806
11807        if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
11808            initialAwakenScrollBars();
11809            mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
11810        }
11811
11812        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
11813
11814        jumpDrawablesToCurrentState();
11815
11816        clearAccessibilityFocus();
11817        resetSubtreeAccessibilityStateChanged();
11818
11819        if (isFocused()) {
11820            InputMethodManager imm = InputMethodManager.peekInstance();
11821            imm.focusIn(this);
11822        }
11823
11824        if (mDisplayList != null) {
11825            mDisplayList.clearDirty();
11826        }
11827    }
11828
11829    /**
11830     * Resolve all RTL related properties.
11831     *
11832     * @return true if resolution of RTL properties has been done
11833     *
11834     * @hide
11835     */
11836    public boolean resolveRtlPropertiesIfNeeded() {
11837        if (!needRtlPropertiesResolution()) return false;
11838
11839        // Order is important here: LayoutDirection MUST be resolved first
11840        if (!isLayoutDirectionResolved()) {
11841            resolveLayoutDirection();
11842            resolveLayoutParams();
11843        }
11844        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
11845        if (!isTextDirectionResolved()) {
11846            resolveTextDirection();
11847        }
11848        if (!isTextAlignmentResolved()) {
11849            resolveTextAlignment();
11850        }
11851        if (!isPaddingResolved()) {
11852            resolvePadding();
11853        }
11854        if (!isDrawablesResolved()) {
11855            resolveDrawables();
11856        }
11857        onRtlPropertiesChanged(getLayoutDirection());
11858        return true;
11859    }
11860
11861    /**
11862     * Reset resolution of all RTL related properties.
11863     *
11864     * @hide
11865     */
11866    public void resetRtlProperties() {
11867        resetResolvedLayoutDirection();
11868        resetResolvedTextDirection();
11869        resetResolvedTextAlignment();
11870        resetResolvedPadding();
11871        resetResolvedDrawables();
11872    }
11873
11874    /**
11875     * @see #onScreenStateChanged(int)
11876     */
11877    void dispatchScreenStateChanged(int screenState) {
11878        onScreenStateChanged(screenState);
11879    }
11880
11881    /**
11882     * This method is called whenever the state of the screen this view is
11883     * attached to changes. A state change will usually occurs when the screen
11884     * turns on or off (whether it happens automatically or the user does it
11885     * manually.)
11886     *
11887     * @param screenState The new state of the screen. Can be either
11888     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
11889     */
11890    public void onScreenStateChanged(int screenState) {
11891    }
11892
11893    /**
11894     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
11895     */
11896    private boolean hasRtlSupport() {
11897        return mContext.getApplicationInfo().hasRtlSupport();
11898    }
11899
11900    /**
11901     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
11902     * RTL not supported)
11903     */
11904    private boolean isRtlCompatibilityMode() {
11905        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
11906        return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport();
11907    }
11908
11909    /**
11910     * @return true if RTL properties need resolution.
11911     *
11912     */
11913    private boolean needRtlPropertiesResolution() {
11914        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
11915    }
11916
11917    /**
11918     * Called when any RTL property (layout direction or text direction or text alignment) has
11919     * been changed.
11920     *
11921     * Subclasses need to override this method to take care of cached information that depends on the
11922     * resolved layout direction, or to inform child views that inherit their layout direction.
11923     *
11924     * The default implementation does nothing.
11925     *
11926     * @param layoutDirection the direction of the layout
11927     *
11928     * @see #LAYOUT_DIRECTION_LTR
11929     * @see #LAYOUT_DIRECTION_RTL
11930     */
11931    public void onRtlPropertiesChanged(int layoutDirection) {
11932    }
11933
11934    /**
11935     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
11936     * that the parent directionality can and will be resolved before its children.
11937     *
11938     * @return true if resolution has been done, false otherwise.
11939     *
11940     * @hide
11941     */
11942    public boolean resolveLayoutDirection() {
11943        // Clear any previous layout direction resolution
11944        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
11945
11946        if (hasRtlSupport()) {
11947            // Set resolved depending on layout direction
11948            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
11949                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
11950                case LAYOUT_DIRECTION_INHERIT:
11951                    // We cannot resolve yet. LTR is by default and let the resolution happen again
11952                    // later to get the correct resolved value
11953                    if (!canResolveLayoutDirection()) return false;
11954
11955                    // Parent has not yet resolved, LTR is still the default
11956                    try {
11957                        if (!mParent.isLayoutDirectionResolved()) return false;
11958
11959                        if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
11960                            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
11961                        }
11962                    } catch (AbstractMethodError e) {
11963                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
11964                                " does not fully implement ViewParent", e);
11965                    }
11966                    break;
11967                case LAYOUT_DIRECTION_RTL:
11968                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
11969                    break;
11970                case LAYOUT_DIRECTION_LOCALE:
11971                    if((LAYOUT_DIRECTION_RTL ==
11972                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
11973                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
11974                    }
11975                    break;
11976                default:
11977                    // Nothing to do, LTR by default
11978            }
11979        }
11980
11981        // Set to resolved
11982        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
11983        return true;
11984    }
11985
11986    /**
11987     * Check if layout direction resolution can be done.
11988     *
11989     * @return true if layout direction resolution can be done otherwise return false.
11990     */
11991    public boolean canResolveLayoutDirection() {
11992        switch (getRawLayoutDirection()) {
11993            case LAYOUT_DIRECTION_INHERIT:
11994                if (mParent != null) {
11995                    try {
11996                        return mParent.canResolveLayoutDirection();
11997                    } catch (AbstractMethodError e) {
11998                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
11999                                " does not fully implement ViewParent", e);
12000                    }
12001                }
12002                return false;
12003
12004            default:
12005                return true;
12006        }
12007    }
12008
12009    /**
12010     * Reset the resolved layout direction. Layout direction will be resolved during a call to
12011     * {@link #onMeasure(int, int)}.
12012     *
12013     * @hide
12014     */
12015    public void resetResolvedLayoutDirection() {
12016        // Reset the current resolved bits
12017        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
12018    }
12019
12020    /**
12021     * @return true if the layout direction is inherited.
12022     *
12023     * @hide
12024     */
12025    public boolean isLayoutDirectionInherited() {
12026        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
12027    }
12028
12029    /**
12030     * @return true if layout direction has been resolved.
12031     */
12032    public boolean isLayoutDirectionResolved() {
12033        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
12034    }
12035
12036    /**
12037     * Return if padding has been resolved
12038     *
12039     * @hide
12040     */
12041    boolean isPaddingResolved() {
12042        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
12043    }
12044
12045    /**
12046     * Resolve padding depending on layout direction.
12047     *
12048     * @hide
12049     */
12050    public void resolvePadding() {
12051        if (!isRtlCompatibilityMode()) {
12052            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
12053            // If start / end padding are defined, they will be resolved (hence overriding) to
12054            // left / right or right / left depending on the resolved layout direction.
12055            // If start / end padding are not defined, use the left / right ones.
12056            int resolvedLayoutDirection = getLayoutDirection();
12057            switch (resolvedLayoutDirection) {
12058                case LAYOUT_DIRECTION_RTL:
12059                    if (mUserPaddingStart != UNDEFINED_PADDING) {
12060                        mUserPaddingRight = mUserPaddingStart;
12061                    } else {
12062                        mUserPaddingRight = mUserPaddingRightInitial;
12063                    }
12064                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
12065                        mUserPaddingLeft = mUserPaddingEnd;
12066                    } else {
12067                        mUserPaddingLeft = mUserPaddingLeftInitial;
12068                    }
12069                    break;
12070                case LAYOUT_DIRECTION_LTR:
12071                default:
12072                    if (mUserPaddingStart != UNDEFINED_PADDING) {
12073                        mUserPaddingLeft = mUserPaddingStart;
12074                    } else {
12075                        mUserPaddingLeft = mUserPaddingLeftInitial;
12076                    }
12077                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
12078                        mUserPaddingRight = mUserPaddingEnd;
12079                    } else {
12080                        mUserPaddingRight = mUserPaddingRightInitial;
12081                    }
12082            }
12083
12084            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
12085
12086            internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight,
12087                    mUserPaddingBottom);
12088            onRtlPropertiesChanged(resolvedLayoutDirection);
12089        }
12090
12091        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
12092    }
12093
12094    /**
12095     * Reset the resolved layout direction.
12096     *
12097     * @hide
12098     */
12099    public void resetResolvedPadding() {
12100        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
12101    }
12102
12103    /**
12104     * This is called when the view is detached from a window.  At this point it
12105     * no longer has a surface for drawing.
12106     *
12107     * @see #onAttachedToWindow()
12108     */
12109    protected void onDetachedFromWindow() {
12110        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
12111        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
12112
12113        removeUnsetPressCallback();
12114        removeLongPressCallback();
12115        removePerformClickCallback();
12116        removeSendViewScrolledAccessibilityEventCallback();
12117
12118        destroyDrawingCache();
12119
12120        destroyLayer(false);
12121
12122        cleanupDraw();
12123
12124        mCurrentAnimation = null;
12125        mCurrentScene = null;
12126    }
12127
12128    private void cleanupDraw() {
12129        if (mAttachInfo != null) {
12130            if (mDisplayList != null) {
12131                mDisplayList.markDirty();
12132                mAttachInfo.mViewRootImpl.enqueueDisplayList(mDisplayList);
12133            }
12134            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
12135        } else {
12136            // Should never happen
12137            clearDisplayList();
12138        }
12139    }
12140
12141    void invalidateInheritedLayoutMode(int layoutModeOfRoot) {
12142    }
12143
12144    /**
12145     * @return The number of times this view has been attached to a window
12146     */
12147    protected int getWindowAttachCount() {
12148        return mWindowAttachCount;
12149    }
12150
12151    /**
12152     * Retrieve a unique token identifying the window this view is attached to.
12153     * @return Return the window's token for use in
12154     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
12155     */
12156    public IBinder getWindowToken() {
12157        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
12158    }
12159
12160    /**
12161     * Retrieve the {@link WindowId} for the window this view is
12162     * currently attached to.
12163     */
12164    public WindowId getWindowId() {
12165        if (mAttachInfo == null) {
12166            return null;
12167        }
12168        if (mAttachInfo.mWindowId == null) {
12169            try {
12170                mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId(
12171                        mAttachInfo.mWindowToken);
12172                mAttachInfo.mWindowId = new WindowId(
12173                        mAttachInfo.mIWindowId);
12174            } catch (RemoteException e) {
12175            }
12176        }
12177        return mAttachInfo.mWindowId;
12178    }
12179
12180    /**
12181     * Retrieve a unique token identifying the top-level "real" window of
12182     * the window that this view is attached to.  That is, this is like
12183     * {@link #getWindowToken}, except if the window this view in is a panel
12184     * window (attached to another containing window), then the token of
12185     * the containing window is returned instead.
12186     *
12187     * @return Returns the associated window token, either
12188     * {@link #getWindowToken()} or the containing window's token.
12189     */
12190    public IBinder getApplicationWindowToken() {
12191        AttachInfo ai = mAttachInfo;
12192        if (ai != null) {
12193            IBinder appWindowToken = ai.mPanelParentWindowToken;
12194            if (appWindowToken == null) {
12195                appWindowToken = ai.mWindowToken;
12196            }
12197            return appWindowToken;
12198        }
12199        return null;
12200    }
12201
12202    /**
12203     * Gets the logical display to which the view's window has been attached.
12204     *
12205     * @return The logical display, or null if the view is not currently attached to a window.
12206     */
12207    public Display getDisplay() {
12208        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
12209    }
12210
12211    /**
12212     * Retrieve private session object this view hierarchy is using to
12213     * communicate with the window manager.
12214     * @return the session object to communicate with the window manager
12215     */
12216    /*package*/ IWindowSession getWindowSession() {
12217        return mAttachInfo != null ? mAttachInfo.mSession : null;
12218    }
12219
12220    /**
12221     * @param info the {@link android.view.View.AttachInfo} to associated with
12222     *        this view
12223     */
12224    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
12225        //System.out.println("Attached! " + this);
12226        mAttachInfo = info;
12227        if (mOverlay != null) {
12228            mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
12229        }
12230        mWindowAttachCount++;
12231        // We will need to evaluate the drawable state at least once.
12232        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
12233        if (mFloatingTreeObserver != null) {
12234            info.mTreeObserver.merge(mFloatingTreeObserver);
12235            mFloatingTreeObserver = null;
12236        }
12237        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
12238            mAttachInfo.mScrollContainers.add(this);
12239            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
12240        }
12241        performCollectViewAttributes(mAttachInfo, visibility);
12242        onAttachedToWindow();
12243
12244        ListenerInfo li = mListenerInfo;
12245        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
12246                li != null ? li.mOnAttachStateChangeListeners : null;
12247        if (listeners != null && listeners.size() > 0) {
12248            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
12249            // perform the dispatching. The iterator is a safe guard against listeners that
12250            // could mutate the list by calling the various add/remove methods. This prevents
12251            // the array from being modified while we iterate it.
12252            for (OnAttachStateChangeListener listener : listeners) {
12253                listener.onViewAttachedToWindow(this);
12254            }
12255        }
12256
12257        int vis = info.mWindowVisibility;
12258        if (vis != GONE) {
12259            onWindowVisibilityChanged(vis);
12260        }
12261        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
12262            // If nobody has evaluated the drawable state yet, then do it now.
12263            refreshDrawableState();
12264        }
12265        needGlobalAttributesUpdate(false);
12266    }
12267
12268    void dispatchDetachedFromWindow() {
12269        AttachInfo info = mAttachInfo;
12270        if (info != null) {
12271            int vis = info.mWindowVisibility;
12272            if (vis != GONE) {
12273                onWindowVisibilityChanged(GONE);
12274            }
12275        }
12276
12277        onDetachedFromWindow();
12278
12279        ListenerInfo li = mListenerInfo;
12280        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
12281                li != null ? li.mOnAttachStateChangeListeners : null;
12282        if (listeners != null && listeners.size() > 0) {
12283            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
12284            // perform the dispatching. The iterator is a safe guard against listeners that
12285            // could mutate the list by calling the various add/remove methods. This prevents
12286            // the array from being modified while we iterate it.
12287            for (OnAttachStateChangeListener listener : listeners) {
12288                listener.onViewDetachedFromWindow(this);
12289            }
12290        }
12291
12292        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
12293            mAttachInfo.mScrollContainers.remove(this);
12294            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
12295        }
12296
12297        mAttachInfo = null;
12298        if (mOverlay != null) {
12299            mOverlay.getOverlayView().dispatchDetachedFromWindow();
12300        }
12301    }
12302
12303    /**
12304     * Store this view hierarchy's frozen state into the given container.
12305     *
12306     * @param container The SparseArray in which to save the view's state.
12307     *
12308     * @see #restoreHierarchyState(android.util.SparseArray)
12309     * @see #dispatchSaveInstanceState(android.util.SparseArray)
12310     * @see #onSaveInstanceState()
12311     */
12312    public void saveHierarchyState(SparseArray<Parcelable> container) {
12313        dispatchSaveInstanceState(container);
12314    }
12315
12316    /**
12317     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
12318     * this view and its children. May be overridden to modify how freezing happens to a
12319     * view's children; for example, some views may want to not store state for their children.
12320     *
12321     * @param container The SparseArray in which to save the view's state.
12322     *
12323     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
12324     * @see #saveHierarchyState(android.util.SparseArray)
12325     * @see #onSaveInstanceState()
12326     */
12327    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
12328        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
12329            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
12330            Parcelable state = onSaveInstanceState();
12331            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
12332                throw new IllegalStateException(
12333                        "Derived class did not call super.onSaveInstanceState()");
12334            }
12335            if (state != null) {
12336                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
12337                // + ": " + state);
12338                container.put(mID, state);
12339            }
12340        }
12341    }
12342
12343    /**
12344     * Hook allowing a view to generate a representation of its internal state
12345     * that can later be used to create a new instance with that same state.
12346     * This state should only contain information that is not persistent or can
12347     * not be reconstructed later. For example, you will never store your
12348     * current position on screen because that will be computed again when a
12349     * new instance of the view is placed in its view hierarchy.
12350     * <p>
12351     * Some examples of things you may store here: the current cursor position
12352     * in a text view (but usually not the text itself since that is stored in a
12353     * content provider or other persistent storage), the currently selected
12354     * item in a list view.
12355     *
12356     * @return Returns a Parcelable object containing the view's current dynamic
12357     *         state, or null if there is nothing interesting to save. The
12358     *         default implementation returns null.
12359     * @see #onRestoreInstanceState(android.os.Parcelable)
12360     * @see #saveHierarchyState(android.util.SparseArray)
12361     * @see #dispatchSaveInstanceState(android.util.SparseArray)
12362     * @see #setSaveEnabled(boolean)
12363     */
12364    protected Parcelable onSaveInstanceState() {
12365        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
12366        return BaseSavedState.EMPTY_STATE;
12367    }
12368
12369    /**
12370     * Restore this view hierarchy's frozen state from the given container.
12371     *
12372     * @param container The SparseArray which holds previously frozen states.
12373     *
12374     * @see #saveHierarchyState(android.util.SparseArray)
12375     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
12376     * @see #onRestoreInstanceState(android.os.Parcelable)
12377     */
12378    public void restoreHierarchyState(SparseArray<Parcelable> container) {
12379        dispatchRestoreInstanceState(container);
12380    }
12381
12382    /**
12383     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
12384     * state for this view and its children. May be overridden to modify how restoring
12385     * happens to a view's children; for example, some views may want to not store state
12386     * for their children.
12387     *
12388     * @param container The SparseArray which holds previously saved state.
12389     *
12390     * @see #dispatchSaveInstanceState(android.util.SparseArray)
12391     * @see #restoreHierarchyState(android.util.SparseArray)
12392     * @see #onRestoreInstanceState(android.os.Parcelable)
12393     */
12394    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
12395        if (mID != NO_ID) {
12396            Parcelable state = container.get(mID);
12397            if (state != null) {
12398                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
12399                // + ": " + state);
12400                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
12401                onRestoreInstanceState(state);
12402                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
12403                    throw new IllegalStateException(
12404                            "Derived class did not call super.onRestoreInstanceState()");
12405                }
12406            }
12407        }
12408    }
12409
12410    /**
12411     * Hook allowing a view to re-apply a representation of its internal state that had previously
12412     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
12413     * null state.
12414     *
12415     * @param state The frozen state that had previously been returned by
12416     *        {@link #onSaveInstanceState}.
12417     *
12418     * @see #onSaveInstanceState()
12419     * @see #restoreHierarchyState(android.util.SparseArray)
12420     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
12421     */
12422    protected void onRestoreInstanceState(Parcelable state) {
12423        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
12424        if (state != BaseSavedState.EMPTY_STATE && state != null) {
12425            throw new IllegalArgumentException("Wrong state class, expecting View State but "
12426                    + "received " + state.getClass().toString() + " instead. This usually happens "
12427                    + "when two views of different type have the same id in the same hierarchy. "
12428                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
12429                    + "other views do not use the same id.");
12430        }
12431    }
12432
12433    /**
12434     * <p>Return the time at which the drawing of the view hierarchy started.</p>
12435     *
12436     * @return the drawing start time in milliseconds
12437     */
12438    public long getDrawingTime() {
12439        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
12440    }
12441
12442    /**
12443     * <p>Enables or disables the duplication of the parent's state into this view. When
12444     * duplication is enabled, this view gets its drawable state from its parent rather
12445     * than from its own internal properties.</p>
12446     *
12447     * <p>Note: in the current implementation, setting this property to true after the
12448     * view was added to a ViewGroup might have no effect at all. This property should
12449     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
12450     *
12451     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
12452     * property is enabled, an exception will be thrown.</p>
12453     *
12454     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
12455     * parent, these states should not be affected by this method.</p>
12456     *
12457     * @param enabled True to enable duplication of the parent's drawable state, false
12458     *                to disable it.
12459     *
12460     * @see #getDrawableState()
12461     * @see #isDuplicateParentStateEnabled()
12462     */
12463    public void setDuplicateParentStateEnabled(boolean enabled) {
12464        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
12465    }
12466
12467    /**
12468     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
12469     *
12470     * @return True if this view's drawable state is duplicated from the parent,
12471     *         false otherwise
12472     *
12473     * @see #getDrawableState()
12474     * @see #setDuplicateParentStateEnabled(boolean)
12475     */
12476    public boolean isDuplicateParentStateEnabled() {
12477        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
12478    }
12479
12480    /**
12481     * <p>Specifies the type of layer backing this view. The layer can be
12482     * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
12483     * {@link #LAYER_TYPE_HARDWARE}.</p>
12484     *
12485     * <p>A layer is associated with an optional {@link android.graphics.Paint}
12486     * instance that controls how the layer is composed on screen. The following
12487     * properties of the paint are taken into account when composing the layer:</p>
12488     * <ul>
12489     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
12490     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
12491     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
12492     * </ul>
12493     *
12494     * <p>If this view has an alpha value set to < 1.0 by calling
12495     * {@link #setAlpha(float)}, the alpha value of the layer's paint is superceded
12496     * by this view's alpha value.</p>
12497     *
12498     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE},
12499     * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE}
12500     * for more information on when and how to use layers.</p>
12501     *
12502     * @param layerType The type of layer to use with this view, must be one of
12503     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
12504     *        {@link #LAYER_TYPE_HARDWARE}
12505     * @param paint The paint used to compose the layer. This argument is optional
12506     *        and can be null. It is ignored when the layer type is
12507     *        {@link #LAYER_TYPE_NONE}
12508     *
12509     * @see #getLayerType()
12510     * @see #LAYER_TYPE_NONE
12511     * @see #LAYER_TYPE_SOFTWARE
12512     * @see #LAYER_TYPE_HARDWARE
12513     * @see #setAlpha(float)
12514     *
12515     * @attr ref android.R.styleable#View_layerType
12516     */
12517    public void setLayerType(int layerType, Paint paint) {
12518        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
12519            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
12520                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
12521        }
12522
12523        if (layerType == mLayerType) {
12524            if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) {
12525                mLayerPaint = paint == null ? new Paint() : paint;
12526                invalidateParentCaches();
12527                invalidate(true);
12528            }
12529            return;
12530        }
12531
12532        // Destroy any previous software drawing cache if needed
12533        switch (mLayerType) {
12534            case LAYER_TYPE_HARDWARE:
12535                destroyLayer(false);
12536                // fall through - non-accelerated views may use software layer mechanism instead
12537            case LAYER_TYPE_SOFTWARE:
12538                destroyDrawingCache();
12539                break;
12540            default:
12541                break;
12542        }
12543
12544        mLayerType = layerType;
12545        final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE;
12546        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
12547        mLocalDirtyRect = layerDisabled ? null : new Rect();
12548
12549        invalidateParentCaches();
12550        invalidate(true);
12551    }
12552
12553    /**
12554     * Updates the {@link Paint} object used with the current layer (used only if the current
12555     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
12556     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
12557     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
12558     * ensure that the view gets redrawn immediately.
12559     *
12560     * <p>A layer is associated with an optional {@link android.graphics.Paint}
12561     * instance that controls how the layer is composed on screen. The following
12562     * properties of the paint are taken into account when composing the layer:</p>
12563     * <ul>
12564     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
12565     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
12566     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
12567     * </ul>
12568     *
12569     * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the
12570     * alpha value of the layer's paint is superceded by this view's alpha value.</p>
12571     *
12572     * @param paint The paint used to compose the layer. This argument is optional
12573     *        and can be null. It is ignored when the layer type is
12574     *        {@link #LAYER_TYPE_NONE}
12575     *
12576     * @see #setLayerType(int, android.graphics.Paint)
12577     */
12578    public void setLayerPaint(Paint paint) {
12579        int layerType = getLayerType();
12580        if (layerType != LAYER_TYPE_NONE) {
12581            mLayerPaint = paint == null ? new Paint() : paint;
12582            if (layerType == LAYER_TYPE_HARDWARE) {
12583                HardwareLayer layer = getHardwareLayer();
12584                if (layer != null) {
12585                    layer.setLayerPaint(paint);
12586                }
12587                invalidateViewProperty(false, false);
12588            } else {
12589                invalidate();
12590            }
12591        }
12592    }
12593
12594    /**
12595     * Indicates whether this view has a static layer. A view with layer type
12596     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
12597     * dynamic.
12598     */
12599    boolean hasStaticLayer() {
12600        return true;
12601    }
12602
12603    /**
12604     * Indicates what type of layer is currently associated with this view. By default
12605     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
12606     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
12607     * for more information on the different types of layers.
12608     *
12609     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
12610     *         {@link #LAYER_TYPE_HARDWARE}
12611     *
12612     * @see #setLayerType(int, android.graphics.Paint)
12613     * @see #buildLayer()
12614     * @see #LAYER_TYPE_NONE
12615     * @see #LAYER_TYPE_SOFTWARE
12616     * @see #LAYER_TYPE_HARDWARE
12617     */
12618    public int getLayerType() {
12619        return mLayerType;
12620    }
12621
12622    /**
12623     * Forces this view's layer to be created and this view to be rendered
12624     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
12625     * invoking this method will have no effect.
12626     *
12627     * This method can for instance be used to render a view into its layer before
12628     * starting an animation. If this view is complex, rendering into the layer
12629     * before starting the animation will avoid skipping frames.
12630     *
12631     * @throws IllegalStateException If this view is not attached to a window
12632     *
12633     * @see #setLayerType(int, android.graphics.Paint)
12634     */
12635    public void buildLayer() {
12636        if (mLayerType == LAYER_TYPE_NONE) return;
12637
12638        final AttachInfo attachInfo = mAttachInfo;
12639        if (attachInfo == null) {
12640            throw new IllegalStateException("This view must be attached to a window first");
12641        }
12642
12643        switch (mLayerType) {
12644            case LAYER_TYPE_HARDWARE:
12645                if (attachInfo.mHardwareRenderer != null &&
12646                        attachInfo.mHardwareRenderer.isEnabled() &&
12647                        attachInfo.mHardwareRenderer.validate()) {
12648                    getHardwareLayer();
12649                    // TODO: We need a better way to handle this case
12650                    // If views have registered pre-draw listeners they need
12651                    // to be notified before we build the layer. Those listeners
12652                    // may however rely on other events to happen first so we
12653                    // cannot just invoke them here until they don't cancel the
12654                    // current frame
12655                    if (!attachInfo.mTreeObserver.hasOnPreDrawListeners()) {
12656                        attachInfo.mViewRootImpl.dispatchFlushHardwareLayerUpdates();
12657                    }
12658                }
12659                break;
12660            case LAYER_TYPE_SOFTWARE:
12661                buildDrawingCache(true);
12662                break;
12663        }
12664    }
12665
12666    /**
12667     * <p>Returns a hardware layer that can be used to draw this view again
12668     * without executing its draw method.</p>
12669     *
12670     * @return A HardwareLayer ready to render, or null if an error occurred.
12671     */
12672    HardwareLayer getHardwareLayer() {
12673        if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null ||
12674                !mAttachInfo.mHardwareRenderer.isEnabled()) {
12675            return null;
12676        }
12677
12678        if (!mAttachInfo.mHardwareRenderer.validate()) return null;
12679
12680        final int width = mRight - mLeft;
12681        final int height = mBottom - mTop;
12682
12683        if (width == 0 || height == 0) {
12684            return null;
12685        }
12686
12687        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
12688            if (mHardwareLayer == null) {
12689                mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
12690                        width, height, isOpaque());
12691                mLocalDirtyRect.set(0, 0, width, height);
12692            } else {
12693                if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) {
12694                    if (mHardwareLayer.resize(width, height)) {
12695                        mLocalDirtyRect.set(0, 0, width, height);
12696                    }
12697                }
12698
12699                // This should not be necessary but applications that change
12700                // the parameters of their background drawable without calling
12701                // this.setBackground(Drawable) can leave the view in a bad state
12702                // (for instance isOpaque() returns true, but the background is
12703                // not opaque.)
12704                computeOpaqueFlags();
12705
12706                final boolean opaque = isOpaque();
12707                if (mHardwareLayer.isValid() && mHardwareLayer.isOpaque() != opaque) {
12708                    mHardwareLayer.setOpaque(opaque);
12709                    mLocalDirtyRect.set(0, 0, width, height);
12710                }
12711            }
12712
12713            // The layer is not valid if the underlying GPU resources cannot be allocated
12714            if (!mHardwareLayer.isValid()) {
12715                return null;
12716            }
12717
12718            mHardwareLayer.setLayerPaint(mLayerPaint);
12719            mHardwareLayer.redrawLater(getHardwareLayerDisplayList(mHardwareLayer), mLocalDirtyRect);
12720            ViewRootImpl viewRoot = getViewRootImpl();
12721            if (viewRoot != null) viewRoot.pushHardwareLayerUpdate(mHardwareLayer);
12722
12723            mLocalDirtyRect.setEmpty();
12724        }
12725
12726        return mHardwareLayer;
12727    }
12728
12729    /**
12730     * Destroys this View's hardware layer if possible.
12731     *
12732     * @return True if the layer was destroyed, false otherwise.
12733     *
12734     * @see #setLayerType(int, android.graphics.Paint)
12735     * @see #LAYER_TYPE_HARDWARE
12736     */
12737    boolean destroyLayer(boolean valid) {
12738        if (mHardwareLayer != null) {
12739            AttachInfo info = mAttachInfo;
12740            if (info != null && info.mHardwareRenderer != null &&
12741                    info.mHardwareRenderer.isEnabled() &&
12742                    (valid || info.mHardwareRenderer.validate())) {
12743
12744                info.mHardwareRenderer.cancelLayerUpdate(mHardwareLayer);
12745                mHardwareLayer.destroy();
12746                mHardwareLayer = null;
12747
12748                if (mDisplayList != null) {
12749                    mDisplayList.reset();
12750                }
12751                invalidate(true);
12752                invalidateParentCaches();
12753            }
12754            return true;
12755        }
12756        return false;
12757    }
12758
12759    /**
12760     * Destroys all hardware rendering resources. This method is invoked
12761     * when the system needs to reclaim resources. Upon execution of this
12762     * method, you should free any OpenGL resources created by the view.
12763     *
12764     * Note: you <strong>must</strong> call
12765     * <code>super.destroyHardwareResources()</code> when overriding
12766     * this method.
12767     *
12768     * @hide
12769     */
12770    protected void destroyHardwareResources() {
12771        clearDisplayList();
12772        destroyLayer(true);
12773    }
12774
12775    /**
12776     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
12777     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
12778     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
12779     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
12780     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
12781     * null.</p>
12782     *
12783     * <p>Enabling the drawing cache is similar to
12784     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
12785     * acceleration is turned off. When hardware acceleration is turned on, enabling the
12786     * drawing cache has no effect on rendering because the system uses a different mechanism
12787     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
12788     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
12789     * for information on how to enable software and hardware layers.</p>
12790     *
12791     * <p>This API can be used to manually generate
12792     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
12793     * {@link #getDrawingCache()}.</p>
12794     *
12795     * @param enabled true to enable the drawing cache, false otherwise
12796     *
12797     * @see #isDrawingCacheEnabled()
12798     * @see #getDrawingCache()
12799     * @see #buildDrawingCache()
12800     * @see #setLayerType(int, android.graphics.Paint)
12801     */
12802    public void setDrawingCacheEnabled(boolean enabled) {
12803        mCachingFailed = false;
12804        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
12805    }
12806
12807    /**
12808     * <p>Indicates whether the drawing cache is enabled for this view.</p>
12809     *
12810     * @return true if the drawing cache is enabled
12811     *
12812     * @see #setDrawingCacheEnabled(boolean)
12813     * @see #getDrawingCache()
12814     */
12815    @ViewDebug.ExportedProperty(category = "drawing")
12816    public boolean isDrawingCacheEnabled() {
12817        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
12818    }
12819
12820    /**
12821     * Debugging utility which recursively outputs the dirty state of a view and its
12822     * descendants.
12823     *
12824     * @hide
12825     */
12826    @SuppressWarnings({"UnusedDeclaration"})
12827    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
12828        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
12829                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
12830                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
12831                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
12832        if (clear) {
12833            mPrivateFlags &= clearMask;
12834        }
12835        if (this instanceof ViewGroup) {
12836            ViewGroup parent = (ViewGroup) this;
12837            final int count = parent.getChildCount();
12838            for (int i = 0; i < count; i++) {
12839                final View child = parent.getChildAt(i);
12840                child.outputDirtyFlags(indent + "  ", clear, clearMask);
12841            }
12842        }
12843    }
12844
12845    /**
12846     * This method is used by ViewGroup to cause its children to restore or recreate their
12847     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
12848     * to recreate its own display list, which would happen if it went through the normal
12849     * draw/dispatchDraw mechanisms.
12850     *
12851     * @hide
12852     */
12853    protected void dispatchGetDisplayList() {}
12854
12855    /**
12856     * A view that is not attached or hardware accelerated cannot create a display list.
12857     * This method checks these conditions and returns the appropriate result.
12858     *
12859     * @return true if view has the ability to create a display list, false otherwise.
12860     *
12861     * @hide
12862     */
12863    public boolean canHaveDisplayList() {
12864        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
12865    }
12866
12867    /**
12868     * @return The {@link HardwareRenderer} associated with that view or null if
12869     *         hardware rendering is not supported or this view is not attached
12870     *         to a window.
12871     *
12872     * @hide
12873     */
12874    public HardwareRenderer getHardwareRenderer() {
12875        if (mAttachInfo != null) {
12876            return mAttachInfo.mHardwareRenderer;
12877        }
12878        return null;
12879    }
12880
12881    /**
12882     * Returns a DisplayList. If the incoming displayList is null, one will be created.
12883     * Otherwise, the same display list will be returned (after having been rendered into
12884     * along the way, depending on the invalidation state of the view).
12885     *
12886     * @param displayList The previous version of this displayList, could be null.
12887     * @param isLayer Whether the requester of the display list is a layer. If so,
12888     * the view will avoid creating a layer inside the resulting display list.
12889     * @return A new or reused DisplayList object.
12890     */
12891    private DisplayList getDisplayList(DisplayList displayList, boolean isLayer) {
12892        if (!canHaveDisplayList()) {
12893            return null;
12894        }
12895
12896        if (((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 ||
12897                displayList == null || !displayList.isValid() ||
12898                (!isLayer && mRecreateDisplayList))) {
12899            // Don't need to recreate the display list, just need to tell our
12900            // children to restore/recreate theirs
12901            if (displayList != null && displayList.isValid() &&
12902                    !isLayer && !mRecreateDisplayList) {
12903                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
12904                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
12905                dispatchGetDisplayList();
12906
12907                return displayList;
12908            }
12909
12910            if (!isLayer) {
12911                // If we got here, we're recreating it. Mark it as such to ensure that
12912                // we copy in child display lists into ours in drawChild()
12913                mRecreateDisplayList = true;
12914            }
12915            if (displayList == null) {
12916                displayList = mAttachInfo.mHardwareRenderer.createDisplayList(getClass().getName());
12917                // If we're creating a new display list, make sure our parent gets invalidated
12918                // since they will need to recreate their display list to account for this
12919                // new child display list.
12920                invalidateParentCaches();
12921            }
12922
12923            boolean caching = false;
12924            int width = mRight - mLeft;
12925            int height = mBottom - mTop;
12926            int layerType = getLayerType();
12927
12928            final HardwareCanvas canvas = displayList.start(width, height);
12929
12930            try {
12931                if (!isLayer && layerType != LAYER_TYPE_NONE) {
12932                    if (layerType == LAYER_TYPE_HARDWARE) {
12933                        final HardwareLayer layer = getHardwareLayer();
12934                        if (layer != null && layer.isValid()) {
12935                            canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
12936                        } else {
12937                            canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint,
12938                                    Canvas.HAS_ALPHA_LAYER_SAVE_FLAG |
12939                                            Canvas.CLIP_TO_LAYER_SAVE_FLAG);
12940                        }
12941                        caching = true;
12942                    } else {
12943                        buildDrawingCache(true);
12944                        Bitmap cache = getDrawingCache(true);
12945                        if (cache != null) {
12946                            canvas.drawBitmap(cache, 0, 0, mLayerPaint);
12947                            caching = true;
12948                        }
12949                    }
12950                } else {
12951
12952                    computeScroll();
12953
12954                    canvas.translate(-mScrollX, -mScrollY);
12955                    if (!isLayer) {
12956                        mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
12957                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
12958                    }
12959
12960                    // Fast path for layouts with no backgrounds
12961                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
12962                        dispatchDraw(canvas);
12963                        if (mOverlay != null && !mOverlay.isEmpty()) {
12964                            mOverlay.getOverlayView().draw(canvas);
12965                        }
12966                    } else {
12967                        draw(canvas);
12968                    }
12969                }
12970            } finally {
12971                displayList.end();
12972                displayList.setCaching(caching);
12973                if (isLayer) {
12974                    displayList.setLeftTopRightBottom(0, 0, width, height);
12975                } else {
12976                    setDisplayListProperties(displayList);
12977                }
12978            }
12979        } else if (!isLayer) {
12980            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
12981            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
12982        }
12983
12984        return displayList;
12985    }
12986
12987    /**
12988     * Get the DisplayList for the HardwareLayer
12989     *
12990     * @param layer The HardwareLayer whose DisplayList we want
12991     * @return A DisplayList fopr the specified HardwareLayer
12992     */
12993    private DisplayList getHardwareLayerDisplayList(HardwareLayer layer) {
12994        DisplayList displayList = getDisplayList(layer.getDisplayList(), true);
12995        layer.setDisplayList(displayList);
12996        return displayList;
12997    }
12998
12999
13000    /**
13001     * <p>Returns a display list that can be used to draw this view again
13002     * without executing its draw method.</p>
13003     *
13004     * @return A DisplayList ready to replay, or null if caching is not enabled.
13005     *
13006     * @hide
13007     */
13008    public DisplayList getDisplayList() {
13009        mDisplayList = getDisplayList(mDisplayList, false);
13010        return mDisplayList;
13011    }
13012
13013    private void clearDisplayList() {
13014        if (mDisplayList != null) {
13015            mDisplayList.clear();
13016        }
13017    }
13018
13019    /**
13020     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
13021     *
13022     * @return A non-scaled bitmap representing this view or null if cache is disabled.
13023     *
13024     * @see #getDrawingCache(boolean)
13025     */
13026    public Bitmap getDrawingCache() {
13027        return getDrawingCache(false);
13028    }
13029
13030    /**
13031     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
13032     * is null when caching is disabled. If caching is enabled and the cache is not ready,
13033     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
13034     * draw from the cache when the cache is enabled. To benefit from the cache, you must
13035     * request the drawing cache by calling this method and draw it on screen if the
13036     * returned bitmap is not null.</p>
13037     *
13038     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
13039     * this method will create a bitmap of the same size as this view. Because this bitmap
13040     * will be drawn scaled by the parent ViewGroup, the result on screen might show
13041     * scaling artifacts. To avoid such artifacts, you should call this method by setting
13042     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
13043     * size than the view. This implies that your application must be able to handle this
13044     * size.</p>
13045     *
13046     * @param autoScale Indicates whether the generated bitmap should be scaled based on
13047     *        the current density of the screen when the application is in compatibility
13048     *        mode.
13049     *
13050     * @return A bitmap representing this view or null if cache is disabled.
13051     *
13052     * @see #setDrawingCacheEnabled(boolean)
13053     * @see #isDrawingCacheEnabled()
13054     * @see #buildDrawingCache(boolean)
13055     * @see #destroyDrawingCache()
13056     */
13057    public Bitmap getDrawingCache(boolean autoScale) {
13058        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
13059            return null;
13060        }
13061        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
13062            buildDrawingCache(autoScale);
13063        }
13064        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
13065    }
13066
13067    /**
13068     * <p>Frees the resources used by the drawing cache. If you call
13069     * {@link #buildDrawingCache()} manually without calling
13070     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
13071     * should cleanup the cache with this method afterwards.</p>
13072     *
13073     * @see #setDrawingCacheEnabled(boolean)
13074     * @see #buildDrawingCache()
13075     * @see #getDrawingCache()
13076     */
13077    public void destroyDrawingCache() {
13078        if (mDrawingCache != null) {
13079            mDrawingCache.recycle();
13080            mDrawingCache = null;
13081        }
13082        if (mUnscaledDrawingCache != null) {
13083            mUnscaledDrawingCache.recycle();
13084            mUnscaledDrawingCache = null;
13085        }
13086    }
13087
13088    /**
13089     * Setting a solid background color for the drawing cache's bitmaps will improve
13090     * performance and memory usage. Note, though that this should only be used if this
13091     * view will always be drawn on top of a solid color.
13092     *
13093     * @param color The background color to use for the drawing cache's bitmap
13094     *
13095     * @see #setDrawingCacheEnabled(boolean)
13096     * @see #buildDrawingCache()
13097     * @see #getDrawingCache()
13098     */
13099    public void setDrawingCacheBackgroundColor(int color) {
13100        if (color != mDrawingCacheBackgroundColor) {
13101            mDrawingCacheBackgroundColor = color;
13102            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
13103        }
13104    }
13105
13106    /**
13107     * @see #setDrawingCacheBackgroundColor(int)
13108     *
13109     * @return The background color to used for the drawing cache's bitmap
13110     */
13111    public int getDrawingCacheBackgroundColor() {
13112        return mDrawingCacheBackgroundColor;
13113    }
13114
13115    /**
13116     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
13117     *
13118     * @see #buildDrawingCache(boolean)
13119     */
13120    public void buildDrawingCache() {
13121        buildDrawingCache(false);
13122    }
13123
13124    /**
13125     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
13126     *
13127     * <p>If you call {@link #buildDrawingCache()} manually without calling
13128     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
13129     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
13130     *
13131     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
13132     * this method will create a bitmap of the same size as this view. Because this bitmap
13133     * will be drawn scaled by the parent ViewGroup, the result on screen might show
13134     * scaling artifacts. To avoid such artifacts, you should call this method by setting
13135     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
13136     * size than the view. This implies that your application must be able to handle this
13137     * size.</p>
13138     *
13139     * <p>You should avoid calling this method when hardware acceleration is enabled. If
13140     * you do not need the drawing cache bitmap, calling this method will increase memory
13141     * usage and cause the view to be rendered in software once, thus negatively impacting
13142     * performance.</p>
13143     *
13144     * @see #getDrawingCache()
13145     * @see #destroyDrawingCache()
13146     */
13147    public void buildDrawingCache(boolean autoScale) {
13148        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
13149                mDrawingCache == null : mUnscaledDrawingCache == null)) {
13150            mCachingFailed = false;
13151
13152            int width = mRight - mLeft;
13153            int height = mBottom - mTop;
13154
13155            final AttachInfo attachInfo = mAttachInfo;
13156            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
13157
13158            if (autoScale && scalingRequired) {
13159                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
13160                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
13161            }
13162
13163            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
13164            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
13165            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
13166
13167            final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
13168            final long drawingCacheSize =
13169                    ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
13170            if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
13171                if (width > 0 && height > 0) {
13172                    Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs "
13173                            + projectedBitmapSize + " bytes, only "
13174                            + drawingCacheSize + " available");
13175                }
13176                destroyDrawingCache();
13177                mCachingFailed = true;
13178                return;
13179            }
13180
13181            boolean clear = true;
13182            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
13183
13184            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
13185                Bitmap.Config quality;
13186                if (!opaque) {
13187                    // Never pick ARGB_4444 because it looks awful
13188                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
13189                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
13190                        case DRAWING_CACHE_QUALITY_AUTO:
13191                            quality = Bitmap.Config.ARGB_8888;
13192                            break;
13193                        case DRAWING_CACHE_QUALITY_LOW:
13194                            quality = Bitmap.Config.ARGB_8888;
13195                            break;
13196                        case DRAWING_CACHE_QUALITY_HIGH:
13197                            quality = Bitmap.Config.ARGB_8888;
13198                            break;
13199                        default:
13200                            quality = Bitmap.Config.ARGB_8888;
13201                            break;
13202                    }
13203                } else {
13204                    // Optimization for translucent windows
13205                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
13206                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
13207                }
13208
13209                // Try to cleanup memory
13210                if (bitmap != null) bitmap.recycle();
13211
13212                try {
13213                    bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
13214                            width, height, quality);
13215                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
13216                    if (autoScale) {
13217                        mDrawingCache = bitmap;
13218                    } else {
13219                        mUnscaledDrawingCache = bitmap;
13220                    }
13221                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
13222                } catch (OutOfMemoryError e) {
13223                    // If there is not enough memory to create the bitmap cache, just
13224                    // ignore the issue as bitmap caches are not required to draw the
13225                    // view hierarchy
13226                    if (autoScale) {
13227                        mDrawingCache = null;
13228                    } else {
13229                        mUnscaledDrawingCache = null;
13230                    }
13231                    mCachingFailed = true;
13232                    return;
13233                }
13234
13235                clear = drawingCacheBackgroundColor != 0;
13236            }
13237
13238            Canvas canvas;
13239            if (attachInfo != null) {
13240                canvas = attachInfo.mCanvas;
13241                if (canvas == null) {
13242                    canvas = new Canvas();
13243                }
13244                canvas.setBitmap(bitmap);
13245                // Temporarily clobber the cached Canvas in case one of our children
13246                // is also using a drawing cache. Without this, the children would
13247                // steal the canvas by attaching their own bitmap to it and bad, bad
13248                // thing would happen (invisible views, corrupted drawings, etc.)
13249                attachInfo.mCanvas = null;
13250            } else {
13251                // This case should hopefully never or seldom happen
13252                canvas = new Canvas(bitmap);
13253            }
13254
13255            if (clear) {
13256                bitmap.eraseColor(drawingCacheBackgroundColor);
13257            }
13258
13259            computeScroll();
13260            final int restoreCount = canvas.save();
13261
13262            if (autoScale && scalingRequired) {
13263                final float scale = attachInfo.mApplicationScale;
13264                canvas.scale(scale, scale);
13265            }
13266
13267            canvas.translate(-mScrollX, -mScrollY);
13268
13269            mPrivateFlags |= PFLAG_DRAWN;
13270            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
13271                    mLayerType != LAYER_TYPE_NONE) {
13272                mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
13273            }
13274
13275            // Fast path for layouts with no backgrounds
13276            if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13277                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13278                dispatchDraw(canvas);
13279                if (mOverlay != null && !mOverlay.isEmpty()) {
13280                    mOverlay.getOverlayView().draw(canvas);
13281                }
13282            } else {
13283                draw(canvas);
13284            }
13285
13286            canvas.restoreToCount(restoreCount);
13287            canvas.setBitmap(null);
13288
13289            if (attachInfo != null) {
13290                // Restore the cached Canvas for our siblings
13291                attachInfo.mCanvas = canvas;
13292            }
13293        }
13294    }
13295
13296    /**
13297     * Create a snapshot of the view into a bitmap.  We should probably make
13298     * some form of this public, but should think about the API.
13299     */
13300    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
13301        int width = mRight - mLeft;
13302        int height = mBottom - mTop;
13303
13304        final AttachInfo attachInfo = mAttachInfo;
13305        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
13306        width = (int) ((width * scale) + 0.5f);
13307        height = (int) ((height * scale) + 0.5f);
13308
13309        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
13310                width > 0 ? width : 1, height > 0 ? height : 1, quality);
13311        if (bitmap == null) {
13312            throw new OutOfMemoryError();
13313        }
13314
13315        Resources resources = getResources();
13316        if (resources != null) {
13317            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
13318        }
13319
13320        Canvas canvas;
13321        if (attachInfo != null) {
13322            canvas = attachInfo.mCanvas;
13323            if (canvas == null) {
13324                canvas = new Canvas();
13325            }
13326            canvas.setBitmap(bitmap);
13327            // Temporarily clobber the cached Canvas in case one of our children
13328            // is also using a drawing cache. Without this, the children would
13329            // steal the canvas by attaching their own bitmap to it and bad, bad
13330            // things would happen (invisible views, corrupted drawings, etc.)
13331            attachInfo.mCanvas = null;
13332        } else {
13333            // This case should hopefully never or seldom happen
13334            canvas = new Canvas(bitmap);
13335        }
13336
13337        if ((backgroundColor & 0xff000000) != 0) {
13338            bitmap.eraseColor(backgroundColor);
13339        }
13340
13341        computeScroll();
13342        final int restoreCount = canvas.save();
13343        canvas.scale(scale, scale);
13344        canvas.translate(-mScrollX, -mScrollY);
13345
13346        // Temporarily remove the dirty mask
13347        int flags = mPrivateFlags;
13348        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13349
13350        // Fast path for layouts with no backgrounds
13351        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13352            dispatchDraw(canvas);
13353        } else {
13354            draw(canvas);
13355        }
13356
13357        mPrivateFlags = flags;
13358
13359        canvas.restoreToCount(restoreCount);
13360        canvas.setBitmap(null);
13361
13362        if (attachInfo != null) {
13363            // Restore the cached Canvas for our siblings
13364            attachInfo.mCanvas = canvas;
13365        }
13366
13367        return bitmap;
13368    }
13369
13370    /**
13371     * Indicates whether this View is currently in edit mode. A View is usually
13372     * in edit mode when displayed within a developer tool. For instance, if
13373     * this View is being drawn by a visual user interface builder, this method
13374     * should return true.
13375     *
13376     * Subclasses should check the return value of this method to provide
13377     * different behaviors if their normal behavior might interfere with the
13378     * host environment. For instance: the class spawns a thread in its
13379     * constructor, the drawing code relies on device-specific features, etc.
13380     *
13381     * This method is usually checked in the drawing code of custom widgets.
13382     *
13383     * @return True if this View is in edit mode, false otherwise.
13384     */
13385    public boolean isInEditMode() {
13386        return false;
13387    }
13388
13389    /**
13390     * If the View draws content inside its padding and enables fading edges,
13391     * it needs to support padding offsets. Padding offsets are added to the
13392     * fading edges to extend the length of the fade so that it covers pixels
13393     * drawn inside the padding.
13394     *
13395     * Subclasses of this class should override this method if they need
13396     * to draw content inside the padding.
13397     *
13398     * @return True if padding offset must be applied, false otherwise.
13399     *
13400     * @see #getLeftPaddingOffset()
13401     * @see #getRightPaddingOffset()
13402     * @see #getTopPaddingOffset()
13403     * @see #getBottomPaddingOffset()
13404     *
13405     * @since CURRENT
13406     */
13407    protected boolean isPaddingOffsetRequired() {
13408        return false;
13409    }
13410
13411    /**
13412     * Amount by which to extend the left fading region. Called only when
13413     * {@link #isPaddingOffsetRequired()} returns true.
13414     *
13415     * @return The left padding offset in pixels.
13416     *
13417     * @see #isPaddingOffsetRequired()
13418     *
13419     * @since CURRENT
13420     */
13421    protected int getLeftPaddingOffset() {
13422        return 0;
13423    }
13424
13425    /**
13426     * Amount by which to extend the right fading region. Called only when
13427     * {@link #isPaddingOffsetRequired()} returns true.
13428     *
13429     * @return The right padding offset in pixels.
13430     *
13431     * @see #isPaddingOffsetRequired()
13432     *
13433     * @since CURRENT
13434     */
13435    protected int getRightPaddingOffset() {
13436        return 0;
13437    }
13438
13439    /**
13440     * Amount by which to extend the top fading region. Called only when
13441     * {@link #isPaddingOffsetRequired()} returns true.
13442     *
13443     * @return The top padding offset in pixels.
13444     *
13445     * @see #isPaddingOffsetRequired()
13446     *
13447     * @since CURRENT
13448     */
13449    protected int getTopPaddingOffset() {
13450        return 0;
13451    }
13452
13453    /**
13454     * Amount by which to extend the bottom fading region. Called only when
13455     * {@link #isPaddingOffsetRequired()} returns true.
13456     *
13457     * @return The bottom padding offset in pixels.
13458     *
13459     * @see #isPaddingOffsetRequired()
13460     *
13461     * @since CURRENT
13462     */
13463    protected int getBottomPaddingOffset() {
13464        return 0;
13465    }
13466
13467    /**
13468     * @hide
13469     * @param offsetRequired
13470     */
13471    protected int getFadeTop(boolean offsetRequired) {
13472        int top = mPaddingTop;
13473        if (offsetRequired) top += getTopPaddingOffset();
13474        return top;
13475    }
13476
13477    /**
13478     * @hide
13479     * @param offsetRequired
13480     */
13481    protected int getFadeHeight(boolean offsetRequired) {
13482        int padding = mPaddingTop;
13483        if (offsetRequired) padding += getTopPaddingOffset();
13484        return mBottom - mTop - mPaddingBottom - padding;
13485    }
13486
13487    /**
13488     * <p>Indicates whether this view is attached to a hardware accelerated
13489     * window or not.</p>
13490     *
13491     * <p>Even if this method returns true, it does not mean that every call
13492     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
13493     * accelerated {@link android.graphics.Canvas}. For instance, if this view
13494     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
13495     * window is hardware accelerated,
13496     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
13497     * return false, and this method will return true.</p>
13498     *
13499     * @return True if the view is attached to a window and the window is
13500     *         hardware accelerated; false in any other case.
13501     */
13502    public boolean isHardwareAccelerated() {
13503        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
13504    }
13505
13506    /**
13507     * Sets a rectangular area on this view to which the view will be clipped
13508     * when it is drawn. Setting the value to null will remove the clip bounds
13509     * and the view will draw normally, using its full bounds.
13510     *
13511     * @param clipBounds The rectangular area, in the local coordinates of
13512     * this view, to which future drawing operations will be clipped.
13513     */
13514    public void setClipBounds(Rect clipBounds) {
13515        if (clipBounds != null) {
13516            if (clipBounds.equals(mClipBounds)) {
13517                return;
13518            }
13519            if (mClipBounds == null) {
13520                invalidate();
13521                mClipBounds = new Rect(clipBounds);
13522            } else {
13523                invalidate(Math.min(mClipBounds.left, clipBounds.left),
13524                        Math.min(mClipBounds.top, clipBounds.top),
13525                        Math.max(mClipBounds.right, clipBounds.right),
13526                        Math.max(mClipBounds.bottom, clipBounds.bottom));
13527                mClipBounds.set(clipBounds);
13528            }
13529        } else {
13530            if (mClipBounds != null) {
13531                invalidate();
13532                mClipBounds = null;
13533            }
13534        }
13535    }
13536
13537    /**
13538     * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}.
13539     *
13540     * @return A copy of the current clip bounds if clip bounds are set,
13541     * otherwise null.
13542     */
13543    public Rect getClipBounds() {
13544        return (mClipBounds != null) ? new Rect(mClipBounds) : null;
13545    }
13546
13547    /**
13548     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
13549     * case of an active Animation being run on the view.
13550     */
13551    private boolean drawAnimation(ViewGroup parent, long drawingTime,
13552            Animation a, boolean scalingRequired) {
13553        Transformation invalidationTransform;
13554        final int flags = parent.mGroupFlags;
13555        final boolean initialized = a.isInitialized();
13556        if (!initialized) {
13557            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
13558            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
13559            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
13560            onAnimationStart();
13561        }
13562
13563        final Transformation t = parent.getChildTransformation();
13564        boolean more = a.getTransformation(drawingTime, t, 1f);
13565        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
13566            if (parent.mInvalidationTransformation == null) {
13567                parent.mInvalidationTransformation = new Transformation();
13568            }
13569            invalidationTransform = parent.mInvalidationTransformation;
13570            a.getTransformation(drawingTime, invalidationTransform, 1f);
13571        } else {
13572            invalidationTransform = t;
13573        }
13574
13575        if (more) {
13576            if (!a.willChangeBounds()) {
13577                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
13578                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
13579                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
13580                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
13581                    // The child need to draw an animation, potentially offscreen, so
13582                    // make sure we do not cancel invalidate requests
13583                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
13584                    parent.invalidate(mLeft, mTop, mRight, mBottom);
13585                }
13586            } else {
13587                if (parent.mInvalidateRegion == null) {
13588                    parent.mInvalidateRegion = new RectF();
13589                }
13590                final RectF region = parent.mInvalidateRegion;
13591                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
13592                        invalidationTransform);
13593
13594                // The child need to draw an animation, potentially offscreen, so
13595                // make sure we do not cancel invalidate requests
13596                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
13597
13598                final int left = mLeft + (int) region.left;
13599                final int top = mTop + (int) region.top;
13600                parent.invalidate(left, top, left + (int) (region.width() + .5f),
13601                        top + (int) (region.height() + .5f));
13602            }
13603        }
13604        return more;
13605    }
13606
13607    /**
13608     * This method is called by getDisplayList() when a display list is created or re-rendered.
13609     * It sets or resets the current value of all properties on that display list (resetting is
13610     * necessary when a display list is being re-created, because we need to make sure that
13611     * previously-set transform values
13612     */
13613    void setDisplayListProperties(DisplayList displayList) {
13614        if (displayList != null) {
13615            displayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
13616            displayList.setHasOverlappingRendering(hasOverlappingRendering());
13617            if (mParent instanceof ViewGroup) {
13618                displayList.setClipToBounds(
13619                        (((ViewGroup) mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0);
13620            }
13621            float alpha = 1;
13622            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
13623                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
13624                ViewGroup parentVG = (ViewGroup) mParent;
13625                final Transformation t = parentVG.getChildTransformation();
13626                if (parentVG.getChildStaticTransformation(this, t)) {
13627                    final int transformType = t.getTransformationType();
13628                    if (transformType != Transformation.TYPE_IDENTITY) {
13629                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
13630                            alpha = t.getAlpha();
13631                        }
13632                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
13633                            displayList.setMatrix(t.getMatrix());
13634                        }
13635                    }
13636                }
13637            }
13638            if (mTransformationInfo != null) {
13639                alpha *= mTransformationInfo.mAlpha;
13640                if (alpha < 1) {
13641                    final int multipliedAlpha = (int) (255 * alpha);
13642                    if (onSetAlpha(multipliedAlpha)) {
13643                        alpha = 1;
13644                    }
13645                }
13646                displayList.setTransformationInfo(alpha,
13647                        mTransformationInfo.mTranslationX, mTransformationInfo.mTranslationY,
13648                        mTransformationInfo.mRotation, mTransformationInfo.mRotationX,
13649                        mTransformationInfo.mRotationY, mTransformationInfo.mScaleX,
13650                        mTransformationInfo.mScaleY);
13651                if (mTransformationInfo.mCamera == null) {
13652                    mTransformationInfo.mCamera = new Camera();
13653                    mTransformationInfo.matrix3D = new Matrix();
13654                }
13655                displayList.setCameraDistance(mTransformationInfo.mCamera.getLocationZ());
13656                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == PFLAG_PIVOT_EXPLICITLY_SET) {
13657                    displayList.setPivotX(getPivotX());
13658                    displayList.setPivotY(getPivotY());
13659                }
13660            } else if (alpha < 1) {
13661                displayList.setAlpha(alpha);
13662            }
13663        }
13664    }
13665
13666    /**
13667     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
13668     * This draw() method is an implementation detail and is not intended to be overridden or
13669     * to be called from anywhere else other than ViewGroup.drawChild().
13670     */
13671    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
13672        boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
13673        boolean more = false;
13674        final boolean childHasIdentityMatrix = hasIdentityMatrix();
13675        final int flags = parent.mGroupFlags;
13676
13677        if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) {
13678            parent.getChildTransformation().clear();
13679            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13680        }
13681
13682        Transformation transformToApply = null;
13683        boolean concatMatrix = false;
13684
13685        boolean scalingRequired = false;
13686        boolean caching;
13687        int layerType = getLayerType();
13688
13689        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
13690        if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 ||
13691                (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) {
13692            caching = true;
13693            // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList
13694            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
13695        } else {
13696            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
13697        }
13698
13699        final Animation a = getAnimation();
13700        if (a != null) {
13701            more = drawAnimation(parent, drawingTime, a, scalingRequired);
13702            concatMatrix = a.willChangeTransformationMatrix();
13703            if (concatMatrix) {
13704                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
13705            }
13706            transformToApply = parent.getChildTransformation();
13707        } else {
13708            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) ==
13709                    PFLAG3_VIEW_IS_ANIMATING_TRANSFORM && mDisplayList != null) {
13710                // No longer animating: clear out old animation matrix
13711                mDisplayList.setAnimationMatrix(null);
13712                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
13713            }
13714            if (!useDisplayListProperties &&
13715                    (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
13716                final Transformation t = parent.getChildTransformation();
13717                final boolean hasTransform = parent.getChildStaticTransformation(this, t);
13718                if (hasTransform) {
13719                    final int transformType = t.getTransformationType();
13720                    transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null;
13721                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
13722                }
13723            }
13724        }
13725
13726        concatMatrix |= !childHasIdentityMatrix;
13727
13728        // Sets the flag as early as possible to allow draw() implementations
13729        // to call invalidate() successfully when doing animations
13730        mPrivateFlags |= PFLAG_DRAWN;
13731
13732        if (!concatMatrix &&
13733                (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
13734                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
13735                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
13736                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
13737            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
13738            return more;
13739        }
13740        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
13741
13742        if (hardwareAccelerated) {
13743            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
13744            // retain the flag's value temporarily in the mRecreateDisplayList flag
13745            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED;
13746            mPrivateFlags &= ~PFLAG_INVALIDATED;
13747        }
13748
13749        DisplayList displayList = null;
13750        Bitmap cache = null;
13751        boolean hasDisplayList = false;
13752        if (caching) {
13753            if (!hardwareAccelerated) {
13754                if (layerType != LAYER_TYPE_NONE) {
13755                    layerType = LAYER_TYPE_SOFTWARE;
13756                    buildDrawingCache(true);
13757                }
13758                cache = getDrawingCache(true);
13759            } else {
13760                switch (layerType) {
13761                    case LAYER_TYPE_SOFTWARE:
13762                        if (useDisplayListProperties) {
13763                            hasDisplayList = canHaveDisplayList();
13764                        } else {
13765                            buildDrawingCache(true);
13766                            cache = getDrawingCache(true);
13767                        }
13768                        break;
13769                    case LAYER_TYPE_HARDWARE:
13770                        if (useDisplayListProperties) {
13771                            hasDisplayList = canHaveDisplayList();
13772                        }
13773                        break;
13774                    case LAYER_TYPE_NONE:
13775                        // Delay getting the display list until animation-driven alpha values are
13776                        // set up and possibly passed on to the view
13777                        hasDisplayList = canHaveDisplayList();
13778                        break;
13779                }
13780            }
13781        }
13782        useDisplayListProperties &= hasDisplayList;
13783        if (useDisplayListProperties) {
13784            displayList = getDisplayList();
13785            if (!displayList.isValid()) {
13786                // Uncommon, but possible. If a view is removed from the hierarchy during the call
13787                // to getDisplayList(), the display list will be marked invalid and we should not
13788                // try to use it again.
13789                displayList = null;
13790                hasDisplayList = false;
13791                useDisplayListProperties = false;
13792            }
13793        }
13794
13795        int sx = 0;
13796        int sy = 0;
13797        if (!hasDisplayList) {
13798            computeScroll();
13799            sx = mScrollX;
13800            sy = mScrollY;
13801        }
13802
13803        final boolean hasNoCache = cache == null || hasDisplayList;
13804        final boolean offsetForScroll = cache == null && !hasDisplayList &&
13805                layerType != LAYER_TYPE_HARDWARE;
13806
13807        int restoreTo = -1;
13808        if (!useDisplayListProperties || transformToApply != null) {
13809            restoreTo = canvas.save();
13810        }
13811        if (offsetForScroll) {
13812            canvas.translate(mLeft - sx, mTop - sy);
13813        } else {
13814            if (!useDisplayListProperties) {
13815                canvas.translate(mLeft, mTop);
13816            }
13817            if (scalingRequired) {
13818                if (useDisplayListProperties) {
13819                    // TODO: Might not need this if we put everything inside the DL
13820                    restoreTo = canvas.save();
13821                }
13822                // mAttachInfo cannot be null, otherwise scalingRequired == false
13823                final float scale = 1.0f / mAttachInfo.mApplicationScale;
13824                canvas.scale(scale, scale);
13825            }
13826        }
13827
13828        float alpha = useDisplayListProperties ? 1 : getAlpha();
13829        if (transformToApply != null || alpha < 1 || !hasIdentityMatrix() ||
13830                (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
13831            if (transformToApply != null || !childHasIdentityMatrix) {
13832                int transX = 0;
13833                int transY = 0;
13834
13835                if (offsetForScroll) {
13836                    transX = -sx;
13837                    transY = -sy;
13838                }
13839
13840                if (transformToApply != null) {
13841                    if (concatMatrix) {
13842                        if (useDisplayListProperties) {
13843                            displayList.setAnimationMatrix(transformToApply.getMatrix());
13844                        } else {
13845                            // Undo the scroll translation, apply the transformation matrix,
13846                            // then redo the scroll translate to get the correct result.
13847                            canvas.translate(-transX, -transY);
13848                            canvas.concat(transformToApply.getMatrix());
13849                            canvas.translate(transX, transY);
13850                        }
13851                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13852                    }
13853
13854                    float transformAlpha = transformToApply.getAlpha();
13855                    if (transformAlpha < 1) {
13856                        alpha *= transformAlpha;
13857                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13858                    }
13859                }
13860
13861                if (!childHasIdentityMatrix && !useDisplayListProperties) {
13862                    canvas.translate(-transX, -transY);
13863                    canvas.concat(getMatrix());
13864                    canvas.translate(transX, transY);
13865                }
13866            }
13867
13868            // Deal with alpha if it is or used to be <1
13869            if (alpha < 1 ||
13870                    (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
13871                if (alpha < 1) {
13872                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
13873                } else {
13874                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
13875                }
13876                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13877                if (hasNoCache) {
13878                    final int multipliedAlpha = (int) (255 * alpha);
13879                    if (!onSetAlpha(multipliedAlpha)) {
13880                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
13881                        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 ||
13882                                layerType != LAYER_TYPE_NONE) {
13883                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
13884                        }
13885                        if (useDisplayListProperties) {
13886                            displayList.setAlpha(alpha * getAlpha());
13887                        } else  if (layerType == LAYER_TYPE_NONE) {
13888                            final int scrollX = hasDisplayList ? 0 : sx;
13889                            final int scrollY = hasDisplayList ? 0 : sy;
13890                            canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft,
13891                                    scrollY + mBottom - mTop, multipliedAlpha, layerFlags);
13892                        }
13893                    } else {
13894                        // Alpha is handled by the child directly, clobber the layer's alpha
13895                        mPrivateFlags |= PFLAG_ALPHA_SET;
13896                    }
13897                }
13898            }
13899        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
13900            onSetAlpha(255);
13901            mPrivateFlags &= ~PFLAG_ALPHA_SET;
13902        }
13903
13904        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN &&
13905                !useDisplayListProperties && cache == null) {
13906            if (offsetForScroll) {
13907                canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
13908            } else {
13909                if (!scalingRequired || cache == null) {
13910                    canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
13911                } else {
13912                    canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
13913                }
13914            }
13915        }
13916
13917        if (!useDisplayListProperties && hasDisplayList) {
13918            displayList = getDisplayList();
13919            if (!displayList.isValid()) {
13920                // Uncommon, but possible. If a view is removed from the hierarchy during the call
13921                // to getDisplayList(), the display list will be marked invalid and we should not
13922                // try to use it again.
13923                displayList = null;
13924                hasDisplayList = false;
13925            }
13926        }
13927
13928        if (hasNoCache) {
13929            boolean layerRendered = false;
13930            if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) {
13931                final HardwareLayer layer = getHardwareLayer();
13932                if (layer != null && layer.isValid()) {
13933                    mLayerPaint.setAlpha((int) (alpha * 255));
13934                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
13935                    layerRendered = true;
13936                } else {
13937                    final int scrollX = hasDisplayList ? 0 : sx;
13938                    final int scrollY = hasDisplayList ? 0 : sy;
13939                    canvas.saveLayer(scrollX, scrollY,
13940                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
13941                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
13942                }
13943            }
13944
13945            if (!layerRendered) {
13946                if (!hasDisplayList) {
13947                    // Fast path for layouts with no backgrounds
13948                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13949                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13950                        dispatchDraw(canvas);
13951                    } else {
13952                        draw(canvas);
13953                    }
13954                } else {
13955                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13956                    ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags);
13957                }
13958            }
13959        } else if (cache != null) {
13960            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13961            Paint cachePaint;
13962
13963            if (layerType == LAYER_TYPE_NONE) {
13964                cachePaint = parent.mCachePaint;
13965                if (cachePaint == null) {
13966                    cachePaint = new Paint();
13967                    cachePaint.setDither(false);
13968                    parent.mCachePaint = cachePaint;
13969                }
13970                if (alpha < 1) {
13971                    cachePaint.setAlpha((int) (alpha * 255));
13972                    parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
13973                } else if  ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) {
13974                    cachePaint.setAlpha(255);
13975                    parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
13976                }
13977            } else {
13978                cachePaint = mLayerPaint;
13979                cachePaint.setAlpha((int) (alpha * 255));
13980            }
13981            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
13982        }
13983
13984        if (restoreTo >= 0) {
13985            canvas.restoreToCount(restoreTo);
13986        }
13987
13988        if (a != null && !more) {
13989            if (!hardwareAccelerated && !a.getFillAfter()) {
13990                onSetAlpha(255);
13991            }
13992            parent.finishAnimatingView(this, a);
13993        }
13994
13995        if (more && hardwareAccelerated) {
13996            // invalidation is the trigger to recreate display lists, so if we're using
13997            // display lists to render, force an invalidate to allow the animation to
13998            // continue drawing another frame
13999            parent.invalidate(true);
14000            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
14001                // alpha animations should cause the child to recreate its display list
14002                invalidate(true);
14003            }
14004        }
14005
14006        mRecreateDisplayList = false;
14007
14008        return more;
14009    }
14010
14011    /**
14012     * Manually render this view (and all of its children) to the given Canvas.
14013     * The view must have already done a full layout before this function is
14014     * called.  When implementing a view, implement
14015     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
14016     * If you do need to override this method, call the superclass version.
14017     *
14018     * @param canvas The Canvas to which the View is rendered.
14019     */
14020    public void draw(Canvas canvas) {
14021        if (mClipBounds != null) {
14022            canvas.clipRect(mClipBounds);
14023        }
14024        final int privateFlags = mPrivateFlags;
14025        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
14026                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
14027        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
14028
14029        /*
14030         * Draw traversal performs several drawing steps which must be executed
14031         * in the appropriate order:
14032         *
14033         *      1. Draw the background
14034         *      2. If necessary, save the canvas' layers to prepare for fading
14035         *      3. Draw view's content
14036         *      4. Draw children
14037         *      5. If necessary, draw the fading edges and restore layers
14038         *      6. Draw decorations (scrollbars for instance)
14039         */
14040
14041        // Step 1, draw the background, if needed
14042        int saveCount;
14043
14044        if (!dirtyOpaque) {
14045            final Drawable background = mBackground;
14046            if (background != null) {
14047                final int scrollX = mScrollX;
14048                final int scrollY = mScrollY;
14049
14050                if (mBackgroundSizeChanged) {
14051                    background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
14052                    mBackgroundSizeChanged = false;
14053                }
14054
14055                if ((scrollX | scrollY) == 0) {
14056                    background.draw(canvas);
14057                } else {
14058                    canvas.translate(scrollX, scrollY);
14059                    background.draw(canvas);
14060                    canvas.translate(-scrollX, -scrollY);
14061                }
14062            }
14063        }
14064
14065        // skip step 2 & 5 if possible (common case)
14066        final int viewFlags = mViewFlags;
14067        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
14068        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
14069        if (!verticalEdges && !horizontalEdges) {
14070            // Step 3, draw the content
14071            if (!dirtyOpaque) onDraw(canvas);
14072
14073            // Step 4, draw the children
14074            dispatchDraw(canvas);
14075
14076            // Step 6, draw decorations (scrollbars)
14077            onDrawScrollBars(canvas);
14078
14079            if (mOverlay != null && !mOverlay.isEmpty()) {
14080                mOverlay.getOverlayView().dispatchDraw(canvas);
14081            }
14082
14083            // we're done...
14084            return;
14085        }
14086
14087        /*
14088         * Here we do the full fledged routine...
14089         * (this is an uncommon case where speed matters less,
14090         * this is why we repeat some of the tests that have been
14091         * done above)
14092         */
14093
14094        boolean drawTop = false;
14095        boolean drawBottom = false;
14096        boolean drawLeft = false;
14097        boolean drawRight = false;
14098
14099        float topFadeStrength = 0.0f;
14100        float bottomFadeStrength = 0.0f;
14101        float leftFadeStrength = 0.0f;
14102        float rightFadeStrength = 0.0f;
14103
14104        // Step 2, save the canvas' layers
14105        int paddingLeft = mPaddingLeft;
14106
14107        final boolean offsetRequired = isPaddingOffsetRequired();
14108        if (offsetRequired) {
14109            paddingLeft += getLeftPaddingOffset();
14110        }
14111
14112        int left = mScrollX + paddingLeft;
14113        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
14114        int top = mScrollY + getFadeTop(offsetRequired);
14115        int bottom = top + getFadeHeight(offsetRequired);
14116
14117        if (offsetRequired) {
14118            right += getRightPaddingOffset();
14119            bottom += getBottomPaddingOffset();
14120        }
14121
14122        final ScrollabilityCache scrollabilityCache = mScrollCache;
14123        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
14124        int length = (int) fadeHeight;
14125
14126        // clip the fade length if top and bottom fades overlap
14127        // overlapping fades produce odd-looking artifacts
14128        if (verticalEdges && (top + length > bottom - length)) {
14129            length = (bottom - top) / 2;
14130        }
14131
14132        // also clip horizontal fades if necessary
14133        if (horizontalEdges && (left + length > right - length)) {
14134            length = (right - left) / 2;
14135        }
14136
14137        if (verticalEdges) {
14138            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
14139            drawTop = topFadeStrength * fadeHeight > 1.0f;
14140            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
14141            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
14142        }
14143
14144        if (horizontalEdges) {
14145            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
14146            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
14147            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
14148            drawRight = rightFadeStrength * fadeHeight > 1.0f;
14149        }
14150
14151        saveCount = canvas.getSaveCount();
14152
14153        int solidColor = getSolidColor();
14154        if (solidColor == 0) {
14155            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
14156
14157            if (drawTop) {
14158                canvas.saveLayer(left, top, right, top + length, null, flags);
14159            }
14160
14161            if (drawBottom) {
14162                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
14163            }
14164
14165            if (drawLeft) {
14166                canvas.saveLayer(left, top, left + length, bottom, null, flags);
14167            }
14168
14169            if (drawRight) {
14170                canvas.saveLayer(right - length, top, right, bottom, null, flags);
14171            }
14172        } else {
14173            scrollabilityCache.setFadeColor(solidColor);
14174        }
14175
14176        // Step 3, draw the content
14177        if (!dirtyOpaque) onDraw(canvas);
14178
14179        // Step 4, draw the children
14180        dispatchDraw(canvas);
14181
14182        // Step 5, draw the fade effect and restore layers
14183        final Paint p = scrollabilityCache.paint;
14184        final Matrix matrix = scrollabilityCache.matrix;
14185        final Shader fade = scrollabilityCache.shader;
14186
14187        if (drawTop) {
14188            matrix.setScale(1, fadeHeight * topFadeStrength);
14189            matrix.postTranslate(left, top);
14190            fade.setLocalMatrix(matrix);
14191            canvas.drawRect(left, top, right, top + length, p);
14192        }
14193
14194        if (drawBottom) {
14195            matrix.setScale(1, fadeHeight * bottomFadeStrength);
14196            matrix.postRotate(180);
14197            matrix.postTranslate(left, bottom);
14198            fade.setLocalMatrix(matrix);
14199            canvas.drawRect(left, bottom - length, right, bottom, p);
14200        }
14201
14202        if (drawLeft) {
14203            matrix.setScale(1, fadeHeight * leftFadeStrength);
14204            matrix.postRotate(-90);
14205            matrix.postTranslate(left, top);
14206            fade.setLocalMatrix(matrix);
14207            canvas.drawRect(left, top, left + length, bottom, p);
14208        }
14209
14210        if (drawRight) {
14211            matrix.setScale(1, fadeHeight * rightFadeStrength);
14212            matrix.postRotate(90);
14213            matrix.postTranslate(right, top);
14214            fade.setLocalMatrix(matrix);
14215            canvas.drawRect(right - length, top, right, bottom, p);
14216        }
14217
14218        canvas.restoreToCount(saveCount);
14219
14220        // Step 6, draw decorations (scrollbars)
14221        onDrawScrollBars(canvas);
14222
14223        if (mOverlay != null && !mOverlay.isEmpty()) {
14224            mOverlay.getOverlayView().dispatchDraw(canvas);
14225        }
14226    }
14227
14228    /**
14229     * Returns the overlay for this view, creating it if it does not yet exist.
14230     * Adding drawables to the overlay will cause them to be displayed whenever
14231     * the view itself is redrawn. Objects in the overlay should be actively
14232     * managed: remove them when they should not be displayed anymore. The
14233     * overlay will always have the same size as its host view.
14234     *
14235     * <p>Note: Overlays do not currently work correctly with {@link
14236     * SurfaceView} or {@link TextureView}; contents in overlays for these
14237     * types of views may not display correctly.</p>
14238     *
14239     * @return The ViewOverlay object for this view.
14240     * @see ViewOverlay
14241     */
14242    public ViewOverlay getOverlay() {
14243        if (mOverlay == null) {
14244            mOverlay = new ViewOverlay(mContext, this);
14245        }
14246        return mOverlay;
14247    }
14248
14249    /**
14250     * Override this if your view is known to always be drawn on top of a solid color background,
14251     * and needs to draw fading edges. Returning a non-zero color enables the view system to
14252     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
14253     * should be set to 0xFF.
14254     *
14255     * @see #setVerticalFadingEdgeEnabled(boolean)
14256     * @see #setHorizontalFadingEdgeEnabled(boolean)
14257     *
14258     * @return The known solid color background for this view, or 0 if the color may vary
14259     */
14260    @ViewDebug.ExportedProperty(category = "drawing")
14261    public int getSolidColor() {
14262        return 0;
14263    }
14264
14265    /**
14266     * Build a human readable string representation of the specified view flags.
14267     *
14268     * @param flags the view flags to convert to a string
14269     * @return a String representing the supplied flags
14270     */
14271    private static String printFlags(int flags) {
14272        String output = "";
14273        int numFlags = 0;
14274        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
14275            output += "TAKES_FOCUS";
14276            numFlags++;
14277        }
14278
14279        switch (flags & VISIBILITY_MASK) {
14280        case INVISIBLE:
14281            if (numFlags > 0) {
14282                output += " ";
14283            }
14284            output += "INVISIBLE";
14285            // USELESS HERE numFlags++;
14286            break;
14287        case GONE:
14288            if (numFlags > 0) {
14289                output += " ";
14290            }
14291            output += "GONE";
14292            // USELESS HERE numFlags++;
14293            break;
14294        default:
14295            break;
14296        }
14297        return output;
14298    }
14299
14300    /**
14301     * Build a human readable string representation of the specified private
14302     * view flags.
14303     *
14304     * @param privateFlags the private view flags to convert to a string
14305     * @return a String representing the supplied flags
14306     */
14307    private static String printPrivateFlags(int privateFlags) {
14308        String output = "";
14309        int numFlags = 0;
14310
14311        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
14312            output += "WANTS_FOCUS";
14313            numFlags++;
14314        }
14315
14316        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
14317            if (numFlags > 0) {
14318                output += " ";
14319            }
14320            output += "FOCUSED";
14321            numFlags++;
14322        }
14323
14324        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
14325            if (numFlags > 0) {
14326                output += " ";
14327            }
14328            output += "SELECTED";
14329            numFlags++;
14330        }
14331
14332        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
14333            if (numFlags > 0) {
14334                output += " ";
14335            }
14336            output += "IS_ROOT_NAMESPACE";
14337            numFlags++;
14338        }
14339
14340        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
14341            if (numFlags > 0) {
14342                output += " ";
14343            }
14344            output += "HAS_BOUNDS";
14345            numFlags++;
14346        }
14347
14348        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
14349            if (numFlags > 0) {
14350                output += " ";
14351            }
14352            output += "DRAWN";
14353            // USELESS HERE numFlags++;
14354        }
14355        return output;
14356    }
14357
14358    /**
14359     * <p>Indicates whether or not this view's layout will be requested during
14360     * the next hierarchy layout pass.</p>
14361     *
14362     * @return true if the layout will be forced during next layout pass
14363     */
14364    public boolean isLayoutRequested() {
14365        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
14366    }
14367
14368    /**
14369     * Return true if o is a ViewGroup that is laying out using optical bounds.
14370     * @hide
14371     */
14372    public static boolean isLayoutModeOptical(Object o) {
14373        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
14374    }
14375
14376    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
14377        Insets parentInsets = mParent instanceof View ?
14378                ((View) mParent).getOpticalInsets() : Insets.NONE;
14379        Insets childInsets = getOpticalInsets();
14380        return setFrame(
14381                left   + parentInsets.left - childInsets.left,
14382                top    + parentInsets.top  - childInsets.top,
14383                right  + parentInsets.left + childInsets.right,
14384                bottom + parentInsets.top  + childInsets.bottom);
14385    }
14386
14387    /**
14388     * Assign a size and position to a view and all of its
14389     * descendants
14390     *
14391     * <p>This is the second phase of the layout mechanism.
14392     * (The first is measuring). In this phase, each parent calls
14393     * layout on all of its children to position them.
14394     * This is typically done using the child measurements
14395     * that were stored in the measure pass().</p>
14396     *
14397     * <p>Derived classes should not override this method.
14398     * Derived classes with children should override
14399     * onLayout. In that method, they should
14400     * call layout on each of their children.</p>
14401     *
14402     * @param l Left position, relative to parent
14403     * @param t Top position, relative to parent
14404     * @param r Right position, relative to parent
14405     * @param b Bottom position, relative to parent
14406     */
14407    @SuppressWarnings({"unchecked"})
14408    public void layout(int l, int t, int r, int b) {
14409        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
14410            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
14411            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
14412        }
14413
14414        int oldL = mLeft;
14415        int oldT = mTop;
14416        int oldB = mBottom;
14417        int oldR = mRight;
14418
14419        boolean changed = isLayoutModeOptical(mParent) ?
14420                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
14421
14422        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
14423            onLayout(changed, l, t, r, b);
14424            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
14425
14426            ListenerInfo li = mListenerInfo;
14427            if (li != null && li.mOnLayoutChangeListeners != null) {
14428                ArrayList<OnLayoutChangeListener> listenersCopy =
14429                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
14430                int numListeners = listenersCopy.size();
14431                for (int i = 0; i < numListeners; ++i) {
14432                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
14433                }
14434            }
14435        }
14436
14437        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
14438        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
14439    }
14440
14441    /**
14442     * Called from layout when this view should
14443     * assign a size and position to each of its children.
14444     *
14445     * Derived classes with children should override
14446     * this method and call layout on each of
14447     * their children.
14448     * @param changed This is a new size or position for this view
14449     * @param left Left position, relative to parent
14450     * @param top Top position, relative to parent
14451     * @param right Right position, relative to parent
14452     * @param bottom Bottom position, relative to parent
14453     */
14454    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
14455    }
14456
14457    /**
14458     * Assign a size and position to this view.
14459     *
14460     * This is called from layout.
14461     *
14462     * @param left Left position, relative to parent
14463     * @param top Top position, relative to parent
14464     * @param right Right position, relative to parent
14465     * @param bottom Bottom position, relative to parent
14466     * @return true if the new size and position are different than the
14467     *         previous ones
14468     * {@hide}
14469     */
14470    protected boolean setFrame(int left, int top, int right, int bottom) {
14471        boolean changed = false;
14472
14473        if (DBG) {
14474            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
14475                    + right + "," + bottom + ")");
14476        }
14477
14478        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
14479            changed = true;
14480
14481            // Remember our drawn bit
14482            int drawn = mPrivateFlags & PFLAG_DRAWN;
14483
14484            int oldWidth = mRight - mLeft;
14485            int oldHeight = mBottom - mTop;
14486            int newWidth = right - left;
14487            int newHeight = bottom - top;
14488            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
14489
14490            // Invalidate our old position
14491            invalidate(sizeChanged);
14492
14493            mLeft = left;
14494            mTop = top;
14495            mRight = right;
14496            mBottom = bottom;
14497            if (mDisplayList != null) {
14498                mDisplayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
14499            }
14500
14501            mPrivateFlags |= PFLAG_HAS_BOUNDS;
14502
14503
14504            if (sizeChanged) {
14505                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
14506                    // A change in dimension means an auto-centered pivot point changes, too
14507                    if (mTransformationInfo != null) {
14508                        mTransformationInfo.mMatrixDirty = true;
14509                    }
14510                }
14511                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
14512            }
14513
14514            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
14515                // If we are visible, force the DRAWN bit to on so that
14516                // this invalidate will go through (at least to our parent).
14517                // This is because someone may have invalidated this view
14518                // before this call to setFrame came in, thereby clearing
14519                // the DRAWN bit.
14520                mPrivateFlags |= PFLAG_DRAWN;
14521                invalidate(sizeChanged);
14522                // parent display list may need to be recreated based on a change in the bounds
14523                // of any child
14524                invalidateParentCaches();
14525            }
14526
14527            // Reset drawn bit to original value (invalidate turns it off)
14528            mPrivateFlags |= drawn;
14529
14530            mBackgroundSizeChanged = true;
14531
14532            notifySubtreeAccessibilityStateChangedIfNeeded();
14533        }
14534        return changed;
14535    }
14536
14537    private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
14538        onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
14539        if (mOverlay != null) {
14540            mOverlay.getOverlayView().setRight(newWidth);
14541            mOverlay.getOverlayView().setBottom(newHeight);
14542        }
14543    }
14544
14545    /**
14546     * Finalize inflating a view from XML.  This is called as the last phase
14547     * of inflation, after all child views have been added.
14548     *
14549     * <p>Even if the subclass overrides onFinishInflate, they should always be
14550     * sure to call the super method, so that we get called.
14551     */
14552    protected void onFinishInflate() {
14553    }
14554
14555    /**
14556     * Returns the resources associated with this view.
14557     *
14558     * @return Resources object.
14559     */
14560    public Resources getResources() {
14561        return mResources;
14562    }
14563
14564    /**
14565     * Invalidates the specified Drawable.
14566     *
14567     * @param drawable the drawable to invalidate
14568     */
14569    public void invalidateDrawable(Drawable drawable) {
14570        if (verifyDrawable(drawable)) {
14571            final Rect dirty = drawable.getBounds();
14572            final int scrollX = mScrollX;
14573            final int scrollY = mScrollY;
14574
14575            invalidate(dirty.left + scrollX, dirty.top + scrollY,
14576                    dirty.right + scrollX, dirty.bottom + scrollY);
14577        }
14578    }
14579
14580    /**
14581     * Schedules an action on a drawable to occur at a specified time.
14582     *
14583     * @param who the recipient of the action
14584     * @param what the action to run on the drawable
14585     * @param when the time at which the action must occur. Uses the
14586     *        {@link SystemClock#uptimeMillis} timebase.
14587     */
14588    public void scheduleDrawable(Drawable who, Runnable what, long when) {
14589        if (verifyDrawable(who) && what != null) {
14590            final long delay = when - SystemClock.uptimeMillis();
14591            if (mAttachInfo != null) {
14592                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
14593                        Choreographer.CALLBACK_ANIMATION, what, who,
14594                        Choreographer.subtractFrameDelay(delay));
14595            } else {
14596                ViewRootImpl.getRunQueue().postDelayed(what, delay);
14597            }
14598        }
14599    }
14600
14601    /**
14602     * Cancels a scheduled action on a drawable.
14603     *
14604     * @param who the recipient of the action
14605     * @param what the action to cancel
14606     */
14607    public void unscheduleDrawable(Drawable who, Runnable what) {
14608        if (verifyDrawable(who) && what != null) {
14609            if (mAttachInfo != null) {
14610                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
14611                        Choreographer.CALLBACK_ANIMATION, what, who);
14612            } else {
14613                ViewRootImpl.getRunQueue().removeCallbacks(what);
14614            }
14615        }
14616    }
14617
14618    /**
14619     * Unschedule any events associated with the given Drawable.  This can be
14620     * used when selecting a new Drawable into a view, so that the previous
14621     * one is completely unscheduled.
14622     *
14623     * @param who The Drawable to unschedule.
14624     *
14625     * @see #drawableStateChanged
14626     */
14627    public void unscheduleDrawable(Drawable who) {
14628        if (mAttachInfo != null && who != null) {
14629            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
14630                    Choreographer.CALLBACK_ANIMATION, null, who);
14631        }
14632    }
14633
14634    /**
14635     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
14636     * that the View directionality can and will be resolved before its Drawables.
14637     *
14638     * Will call {@link View#onResolveDrawables} when resolution is done.
14639     *
14640     * @hide
14641     */
14642    protected void resolveDrawables() {
14643        if (canResolveLayoutDirection()) {
14644            if (mBackground != null) {
14645                mBackground.setLayoutDirection(getLayoutDirection());
14646            }
14647            mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
14648            onResolveDrawables(getLayoutDirection());
14649        }
14650    }
14651
14652    /**
14653     * Called when layout direction has been resolved.
14654     *
14655     * The default implementation does nothing.
14656     *
14657     * @param layoutDirection The resolved layout direction.
14658     *
14659     * @see #LAYOUT_DIRECTION_LTR
14660     * @see #LAYOUT_DIRECTION_RTL
14661     *
14662     * @hide
14663     */
14664    public void onResolveDrawables(int layoutDirection) {
14665    }
14666
14667    /**
14668     * @hide
14669     */
14670    protected void resetResolvedDrawables() {
14671        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
14672    }
14673
14674    private boolean isDrawablesResolved() {
14675        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
14676    }
14677
14678    /**
14679     * If your view subclass is displaying its own Drawable objects, it should
14680     * override this function and return true for any Drawable it is
14681     * displaying.  This allows animations for those drawables to be
14682     * scheduled.
14683     *
14684     * <p>Be sure to call through to the super class when overriding this
14685     * function.
14686     *
14687     * @param who The Drawable to verify.  Return true if it is one you are
14688     *            displaying, else return the result of calling through to the
14689     *            super class.
14690     *
14691     * @return boolean If true than the Drawable is being displayed in the
14692     *         view; else false and it is not allowed to animate.
14693     *
14694     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
14695     * @see #drawableStateChanged()
14696     */
14697    protected boolean verifyDrawable(Drawable who) {
14698        return who == mBackground;
14699    }
14700
14701    /**
14702     * This function is called whenever the state of the view changes in such
14703     * a way that it impacts the state of drawables being shown.
14704     *
14705     * <p>Be sure to call through to the superclass when overriding this
14706     * function.
14707     *
14708     * @see Drawable#setState(int[])
14709     */
14710    protected void drawableStateChanged() {
14711        Drawable d = mBackground;
14712        if (d != null && d.isStateful()) {
14713            d.setState(getDrawableState());
14714        }
14715    }
14716
14717    /**
14718     * Call this to force a view to update its drawable state. This will cause
14719     * drawableStateChanged to be called on this view. Views that are interested
14720     * in the new state should call getDrawableState.
14721     *
14722     * @see #drawableStateChanged
14723     * @see #getDrawableState
14724     */
14725    public void refreshDrawableState() {
14726        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
14727        drawableStateChanged();
14728
14729        ViewParent parent = mParent;
14730        if (parent != null) {
14731            parent.childDrawableStateChanged(this);
14732        }
14733    }
14734
14735    /**
14736     * Return an array of resource IDs of the drawable states representing the
14737     * current state of the view.
14738     *
14739     * @return The current drawable state
14740     *
14741     * @see Drawable#setState(int[])
14742     * @see #drawableStateChanged()
14743     * @see #onCreateDrawableState(int)
14744     */
14745    public final int[] getDrawableState() {
14746        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
14747            return mDrawableState;
14748        } else {
14749            mDrawableState = onCreateDrawableState(0);
14750            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
14751            return mDrawableState;
14752        }
14753    }
14754
14755    /**
14756     * Generate the new {@link android.graphics.drawable.Drawable} state for
14757     * this view. This is called by the view
14758     * system when the cached Drawable state is determined to be invalid.  To
14759     * retrieve the current state, you should use {@link #getDrawableState}.
14760     *
14761     * @param extraSpace if non-zero, this is the number of extra entries you
14762     * would like in the returned array in which you can place your own
14763     * states.
14764     *
14765     * @return Returns an array holding the current {@link Drawable} state of
14766     * the view.
14767     *
14768     * @see #mergeDrawableStates(int[], int[])
14769     */
14770    protected int[] onCreateDrawableState(int extraSpace) {
14771        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
14772                mParent instanceof View) {
14773            return ((View) mParent).onCreateDrawableState(extraSpace);
14774        }
14775
14776        int[] drawableState;
14777
14778        int privateFlags = mPrivateFlags;
14779
14780        int viewStateIndex = 0;
14781        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
14782        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
14783        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
14784        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
14785        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
14786        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
14787        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
14788                HardwareRenderer.isAvailable()) {
14789            // This is set if HW acceleration is requested, even if the current
14790            // process doesn't allow it.  This is just to allow app preview
14791            // windows to better match their app.
14792            viewStateIndex |= VIEW_STATE_ACCELERATED;
14793        }
14794        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
14795
14796        final int privateFlags2 = mPrivateFlags2;
14797        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
14798        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
14799
14800        drawableState = VIEW_STATE_SETS[viewStateIndex];
14801
14802        //noinspection ConstantIfStatement
14803        if (false) {
14804            Log.i("View", "drawableStateIndex=" + viewStateIndex);
14805            Log.i("View", toString()
14806                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
14807                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
14808                    + " fo=" + hasFocus()
14809                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
14810                    + " wf=" + hasWindowFocus()
14811                    + ": " + Arrays.toString(drawableState));
14812        }
14813
14814        if (extraSpace == 0) {
14815            return drawableState;
14816        }
14817
14818        final int[] fullState;
14819        if (drawableState != null) {
14820            fullState = new int[drawableState.length + extraSpace];
14821            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
14822        } else {
14823            fullState = new int[extraSpace];
14824        }
14825
14826        return fullState;
14827    }
14828
14829    /**
14830     * Merge your own state values in <var>additionalState</var> into the base
14831     * state values <var>baseState</var> that were returned by
14832     * {@link #onCreateDrawableState(int)}.
14833     *
14834     * @param baseState The base state values returned by
14835     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
14836     * own additional state values.
14837     *
14838     * @param additionalState The additional state values you would like
14839     * added to <var>baseState</var>; this array is not modified.
14840     *
14841     * @return As a convenience, the <var>baseState</var> array you originally
14842     * passed into the function is returned.
14843     *
14844     * @see #onCreateDrawableState(int)
14845     */
14846    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
14847        final int N = baseState.length;
14848        int i = N - 1;
14849        while (i >= 0 && baseState[i] == 0) {
14850            i--;
14851        }
14852        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
14853        return baseState;
14854    }
14855
14856    /**
14857     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
14858     * on all Drawable objects associated with this view.
14859     */
14860    public void jumpDrawablesToCurrentState() {
14861        if (mBackground != null) {
14862            mBackground.jumpToCurrentState();
14863        }
14864    }
14865
14866    /**
14867     * Sets the background color for this view.
14868     * @param color the color of the background
14869     */
14870    @RemotableViewMethod
14871    public void setBackgroundColor(int color) {
14872        if (mBackground instanceof ColorDrawable) {
14873            ((ColorDrawable) mBackground.mutate()).setColor(color);
14874            computeOpaqueFlags();
14875            mBackgroundResource = 0;
14876        } else {
14877            setBackground(new ColorDrawable(color));
14878        }
14879    }
14880
14881    /**
14882     * Set the background to a given resource. The resource should refer to
14883     * a Drawable object or 0 to remove the background.
14884     * @param resid The identifier of the resource.
14885     *
14886     * @attr ref android.R.styleable#View_background
14887     */
14888    @RemotableViewMethod
14889    public void setBackgroundResource(int resid) {
14890        if (resid != 0 && resid == mBackgroundResource) {
14891            return;
14892        }
14893
14894        Drawable d= null;
14895        if (resid != 0) {
14896            d = mResources.getDrawable(resid);
14897        }
14898        setBackground(d);
14899
14900        mBackgroundResource = resid;
14901    }
14902
14903    /**
14904     * Set the background to a given Drawable, or remove the background. If the
14905     * background has padding, this View's padding is set to the background's
14906     * padding. However, when a background is removed, this View's padding isn't
14907     * touched. If setting the padding is desired, please use
14908     * {@link #setPadding(int, int, int, int)}.
14909     *
14910     * @param background The Drawable to use as the background, or null to remove the
14911     *        background
14912     */
14913    public void setBackground(Drawable background) {
14914        //noinspection deprecation
14915        setBackgroundDrawable(background);
14916    }
14917
14918    /**
14919     * @deprecated use {@link #setBackground(Drawable)} instead
14920     */
14921    @Deprecated
14922    public void setBackgroundDrawable(Drawable background) {
14923        computeOpaqueFlags();
14924
14925        if (background == mBackground) {
14926            return;
14927        }
14928
14929        boolean requestLayout = false;
14930
14931        mBackgroundResource = 0;
14932
14933        /*
14934         * Regardless of whether we're setting a new background or not, we want
14935         * to clear the previous drawable.
14936         */
14937        if (mBackground != null) {
14938            mBackground.setCallback(null);
14939            unscheduleDrawable(mBackground);
14940        }
14941
14942        if (background != null) {
14943            Rect padding = sThreadLocal.get();
14944            if (padding == null) {
14945                padding = new Rect();
14946                sThreadLocal.set(padding);
14947            }
14948            resetResolvedDrawables();
14949            background.setLayoutDirection(getLayoutDirection());
14950            if (background.getPadding(padding)) {
14951                resetResolvedPadding();
14952                switch (background.getLayoutDirection()) {
14953                    case LAYOUT_DIRECTION_RTL:
14954                        mUserPaddingLeftInitial = padding.right;
14955                        mUserPaddingRightInitial = padding.left;
14956                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
14957                        break;
14958                    case LAYOUT_DIRECTION_LTR:
14959                    default:
14960                        mUserPaddingLeftInitial = padding.left;
14961                        mUserPaddingRightInitial = padding.right;
14962                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
14963                }
14964            }
14965
14966            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
14967            // if it has a different minimum size, we should layout again
14968            if (mBackground == null || mBackground.getMinimumHeight() != background.getMinimumHeight() ||
14969                    mBackground.getMinimumWidth() != background.getMinimumWidth()) {
14970                requestLayout = true;
14971            }
14972
14973            background.setCallback(this);
14974            if (background.isStateful()) {
14975                background.setState(getDrawableState());
14976            }
14977            background.setVisible(getVisibility() == VISIBLE, false);
14978            mBackground = background;
14979
14980            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
14981                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
14982                mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
14983                requestLayout = true;
14984            }
14985        } else {
14986            /* Remove the background */
14987            mBackground = null;
14988
14989            if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) {
14990                /*
14991                 * This view ONLY drew the background before and we're removing
14992                 * the background, so now it won't draw anything
14993                 * (hence we SKIP_DRAW)
14994                 */
14995                mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND;
14996                mPrivateFlags |= PFLAG_SKIP_DRAW;
14997            }
14998
14999            /*
15000             * When the background is set, we try to apply its padding to this
15001             * View. When the background is removed, we don't touch this View's
15002             * padding. This is noted in the Javadocs. Hence, we don't need to
15003             * requestLayout(), the invalidate() below is sufficient.
15004             */
15005
15006            // The old background's minimum size could have affected this
15007            // View's layout, so let's requestLayout
15008            requestLayout = true;
15009        }
15010
15011        computeOpaqueFlags();
15012
15013        if (requestLayout) {
15014            requestLayout();
15015        }
15016
15017        mBackgroundSizeChanged = true;
15018        invalidate(true);
15019    }
15020
15021    /**
15022     * Gets the background drawable
15023     *
15024     * @return The drawable used as the background for this view, if any.
15025     *
15026     * @see #setBackground(Drawable)
15027     *
15028     * @attr ref android.R.styleable#View_background
15029     */
15030    public Drawable getBackground() {
15031        return mBackground;
15032    }
15033
15034    /**
15035     * Sets the padding. The view may add on the space required to display
15036     * the scrollbars, depending on the style and visibility of the scrollbars.
15037     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
15038     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
15039     * from the values set in this call.
15040     *
15041     * @attr ref android.R.styleable#View_padding
15042     * @attr ref android.R.styleable#View_paddingBottom
15043     * @attr ref android.R.styleable#View_paddingLeft
15044     * @attr ref android.R.styleable#View_paddingRight
15045     * @attr ref android.R.styleable#View_paddingTop
15046     * @param left the left padding in pixels
15047     * @param top the top padding in pixels
15048     * @param right the right padding in pixels
15049     * @param bottom the bottom padding in pixels
15050     */
15051    public void setPadding(int left, int top, int right, int bottom) {
15052        resetResolvedPadding();
15053
15054        mUserPaddingStart = UNDEFINED_PADDING;
15055        mUserPaddingEnd = UNDEFINED_PADDING;
15056
15057        mUserPaddingLeftInitial = left;
15058        mUserPaddingRightInitial = right;
15059
15060        internalSetPadding(left, top, right, bottom);
15061    }
15062
15063    /**
15064     * @hide
15065     */
15066    protected void internalSetPadding(int left, int top, int right, int bottom) {
15067        mUserPaddingLeft = left;
15068        mUserPaddingRight = right;
15069        mUserPaddingBottom = bottom;
15070
15071        final int viewFlags = mViewFlags;
15072        boolean changed = false;
15073
15074        // Common case is there are no scroll bars.
15075        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
15076            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
15077                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
15078                        ? 0 : getVerticalScrollbarWidth();
15079                switch (mVerticalScrollbarPosition) {
15080                    case SCROLLBAR_POSITION_DEFAULT:
15081                        if (isLayoutRtl()) {
15082                            left += offset;
15083                        } else {
15084                            right += offset;
15085                        }
15086                        break;
15087                    case SCROLLBAR_POSITION_RIGHT:
15088                        right += offset;
15089                        break;
15090                    case SCROLLBAR_POSITION_LEFT:
15091                        left += offset;
15092                        break;
15093                }
15094            }
15095            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
15096                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
15097                        ? 0 : getHorizontalScrollbarHeight();
15098            }
15099        }
15100
15101        if (mPaddingLeft != left) {
15102            changed = true;
15103            mPaddingLeft = left;
15104        }
15105        if (mPaddingTop != top) {
15106            changed = true;
15107            mPaddingTop = top;
15108        }
15109        if (mPaddingRight != right) {
15110            changed = true;
15111            mPaddingRight = right;
15112        }
15113        if (mPaddingBottom != bottom) {
15114            changed = true;
15115            mPaddingBottom = bottom;
15116        }
15117
15118        if (changed) {
15119            requestLayout();
15120        }
15121    }
15122
15123    /**
15124     * Sets the relative padding. The view may add on the space required to display
15125     * the scrollbars, depending on the style and visibility of the scrollbars.
15126     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
15127     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
15128     * from the values set in this call.
15129     *
15130     * @attr ref android.R.styleable#View_padding
15131     * @attr ref android.R.styleable#View_paddingBottom
15132     * @attr ref android.R.styleable#View_paddingStart
15133     * @attr ref android.R.styleable#View_paddingEnd
15134     * @attr ref android.R.styleable#View_paddingTop
15135     * @param start the start padding in pixels
15136     * @param top the top padding in pixels
15137     * @param end the end padding in pixels
15138     * @param bottom the bottom padding in pixels
15139     */
15140    public void setPaddingRelative(int start, int top, int end, int bottom) {
15141        resetResolvedPadding();
15142
15143        mUserPaddingStart = start;
15144        mUserPaddingEnd = end;
15145
15146        switch(getLayoutDirection()) {
15147            case LAYOUT_DIRECTION_RTL:
15148                mUserPaddingLeftInitial = end;
15149                mUserPaddingRightInitial = start;
15150                internalSetPadding(end, top, start, bottom);
15151                break;
15152            case LAYOUT_DIRECTION_LTR:
15153            default:
15154                mUserPaddingLeftInitial = start;
15155                mUserPaddingRightInitial = end;
15156                internalSetPadding(start, top, end, bottom);
15157        }
15158    }
15159
15160    /**
15161     * Returns the top padding of this view.
15162     *
15163     * @return the top padding in pixels
15164     */
15165    public int getPaddingTop() {
15166        return mPaddingTop;
15167    }
15168
15169    /**
15170     * Returns the bottom padding of this view. If there are inset and enabled
15171     * scrollbars, this value may include the space required to display the
15172     * scrollbars as well.
15173     *
15174     * @return the bottom padding in pixels
15175     */
15176    public int getPaddingBottom() {
15177        return mPaddingBottom;
15178    }
15179
15180    /**
15181     * Returns the left padding of this view. If there are inset and enabled
15182     * scrollbars, this value may include the space required to display the
15183     * scrollbars as well.
15184     *
15185     * @return the left padding in pixels
15186     */
15187    public int getPaddingLeft() {
15188        if (!isPaddingResolved()) {
15189            resolvePadding();
15190        }
15191        return mPaddingLeft;
15192    }
15193
15194    /**
15195     * Returns the start padding of this view depending on its resolved layout direction.
15196     * If there are inset and enabled scrollbars, this value may include the space
15197     * required to display the scrollbars as well.
15198     *
15199     * @return the start padding in pixels
15200     */
15201    public int getPaddingStart() {
15202        if (!isPaddingResolved()) {
15203            resolvePadding();
15204        }
15205        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
15206                mPaddingRight : mPaddingLeft;
15207    }
15208
15209    /**
15210     * Returns the right padding of this view. If there are inset and enabled
15211     * scrollbars, this value may include the space required to display the
15212     * scrollbars as well.
15213     *
15214     * @return the right padding in pixels
15215     */
15216    public int getPaddingRight() {
15217        if (!isPaddingResolved()) {
15218            resolvePadding();
15219        }
15220        return mPaddingRight;
15221    }
15222
15223    /**
15224     * Returns the end padding of this view depending on its resolved layout direction.
15225     * If there are inset and enabled scrollbars, this value may include the space
15226     * required to display the scrollbars as well.
15227     *
15228     * @return the end padding in pixels
15229     */
15230    public int getPaddingEnd() {
15231        if (!isPaddingResolved()) {
15232            resolvePadding();
15233        }
15234        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
15235                mPaddingLeft : mPaddingRight;
15236    }
15237
15238    /**
15239     * Return if the padding as been set thru relative values
15240     * {@link #setPaddingRelative(int, int, int, int)} or thru
15241     * @attr ref android.R.styleable#View_paddingStart or
15242     * @attr ref android.R.styleable#View_paddingEnd
15243     *
15244     * @return true if the padding is relative or false if it is not.
15245     */
15246    public boolean isPaddingRelative() {
15247        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
15248    }
15249
15250    Insets computeOpticalInsets() {
15251        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
15252    }
15253
15254    /**
15255     * @hide
15256     */
15257    public void resetPaddingToInitialValues() {
15258        if (isRtlCompatibilityMode()) {
15259            mPaddingLeft = mUserPaddingLeftInitial;
15260            mPaddingRight = mUserPaddingRightInitial;
15261            return;
15262        }
15263        if (isLayoutRtl()) {
15264            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
15265            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
15266        } else {
15267            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
15268            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
15269        }
15270    }
15271
15272    /**
15273     * @hide
15274     */
15275    public Insets getOpticalInsets() {
15276        if (mLayoutInsets == null) {
15277            mLayoutInsets = computeOpticalInsets();
15278        }
15279        return mLayoutInsets;
15280    }
15281
15282    /**
15283     * Changes the selection state of this view. A view can be selected or not.
15284     * Note that selection is not the same as focus. Views are typically
15285     * selected in the context of an AdapterView like ListView or GridView;
15286     * the selected view is the view that is highlighted.
15287     *
15288     * @param selected true if the view must be selected, false otherwise
15289     */
15290    public void setSelected(boolean selected) {
15291        //noinspection DoubleNegation
15292        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
15293            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
15294            if (!selected) resetPressedState();
15295            invalidate(true);
15296            refreshDrawableState();
15297            dispatchSetSelected(selected);
15298            notifyViewAccessibilityStateChangedIfNeeded();
15299        }
15300    }
15301
15302    /**
15303     * Dispatch setSelected to all of this View's children.
15304     *
15305     * @see #setSelected(boolean)
15306     *
15307     * @param selected The new selected state
15308     */
15309    protected void dispatchSetSelected(boolean selected) {
15310    }
15311
15312    /**
15313     * Indicates the selection state of this view.
15314     *
15315     * @return true if the view is selected, false otherwise
15316     */
15317    @ViewDebug.ExportedProperty
15318    public boolean isSelected() {
15319        return (mPrivateFlags & PFLAG_SELECTED) != 0;
15320    }
15321
15322    /**
15323     * Changes the activated state of this view. A view can be activated or not.
15324     * Note that activation is not the same as selection.  Selection is
15325     * a transient property, representing the view (hierarchy) the user is
15326     * currently interacting with.  Activation is a longer-term state that the
15327     * user can move views in and out of.  For example, in a list view with
15328     * single or multiple selection enabled, the views in the current selection
15329     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
15330     * here.)  The activated state is propagated down to children of the view it
15331     * is set on.
15332     *
15333     * @param activated true if the view must be activated, false otherwise
15334     */
15335    public void setActivated(boolean activated) {
15336        //noinspection DoubleNegation
15337        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
15338            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
15339            invalidate(true);
15340            refreshDrawableState();
15341            dispatchSetActivated(activated);
15342        }
15343    }
15344
15345    /**
15346     * Dispatch setActivated to all of this View's children.
15347     *
15348     * @see #setActivated(boolean)
15349     *
15350     * @param activated The new activated state
15351     */
15352    protected void dispatchSetActivated(boolean activated) {
15353    }
15354
15355    /**
15356     * Indicates the activation state of this view.
15357     *
15358     * @return true if the view is activated, false otherwise
15359     */
15360    @ViewDebug.ExportedProperty
15361    public boolean isActivated() {
15362        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
15363    }
15364
15365    /**
15366     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
15367     * observer can be used to get notifications when global events, like
15368     * layout, happen.
15369     *
15370     * The returned ViewTreeObserver observer is not guaranteed to remain
15371     * valid for the lifetime of this View. If the caller of this method keeps
15372     * a long-lived reference to ViewTreeObserver, it should always check for
15373     * the return value of {@link ViewTreeObserver#isAlive()}.
15374     *
15375     * @return The ViewTreeObserver for this view's hierarchy.
15376     */
15377    public ViewTreeObserver getViewTreeObserver() {
15378        if (mAttachInfo != null) {
15379            return mAttachInfo.mTreeObserver;
15380        }
15381        if (mFloatingTreeObserver == null) {
15382            mFloatingTreeObserver = new ViewTreeObserver();
15383        }
15384        return mFloatingTreeObserver;
15385    }
15386
15387    /**
15388     * <p>Finds the topmost view in the current view hierarchy.</p>
15389     *
15390     * @return the topmost view containing this view
15391     */
15392    public View getRootView() {
15393        if (mAttachInfo != null) {
15394            final View v = mAttachInfo.mRootView;
15395            if (v != null) {
15396                return v;
15397            }
15398        }
15399
15400        View parent = this;
15401
15402        while (parent.mParent != null && parent.mParent instanceof View) {
15403            parent = (View) parent.mParent;
15404        }
15405
15406        return parent;
15407    }
15408
15409    /**
15410     * <p>Computes the coordinates of this view on the screen. The argument
15411     * must be an array of two integers. After the method returns, the array
15412     * contains the x and y location in that order.</p>
15413     *
15414     * @param location an array of two integers in which to hold the coordinates
15415     */
15416    public void getLocationOnScreen(int[] location) {
15417        getLocationInWindow(location);
15418
15419        final AttachInfo info = mAttachInfo;
15420        if (info != null) {
15421            location[0] += info.mWindowLeft;
15422            location[1] += info.mWindowTop;
15423        }
15424    }
15425
15426    /**
15427     * <p>Computes the coordinates of this view in its window. The argument
15428     * must be an array of two integers. After the method returns, the array
15429     * contains the x and y location in that order.</p>
15430     *
15431     * @param location an array of two integers in which to hold the coordinates
15432     */
15433    public void getLocationInWindow(int[] location) {
15434        if (location == null || location.length < 2) {
15435            throw new IllegalArgumentException("location must be an array of two integers");
15436        }
15437
15438        if (mAttachInfo == null) {
15439            // When the view is not attached to a window, this method does not make sense
15440            location[0] = location[1] = 0;
15441            return;
15442        }
15443
15444        float[] position = mAttachInfo.mTmpTransformLocation;
15445        position[0] = position[1] = 0.0f;
15446
15447        if (!hasIdentityMatrix()) {
15448            getMatrix().mapPoints(position);
15449        }
15450
15451        position[0] += mLeft;
15452        position[1] += mTop;
15453
15454        ViewParent viewParent = mParent;
15455        while (viewParent instanceof View) {
15456            final View view = (View) viewParent;
15457
15458            position[0] -= view.mScrollX;
15459            position[1] -= view.mScrollY;
15460
15461            if (!view.hasIdentityMatrix()) {
15462                view.getMatrix().mapPoints(position);
15463            }
15464
15465            position[0] += view.mLeft;
15466            position[1] += view.mTop;
15467
15468            viewParent = view.mParent;
15469         }
15470
15471        if (viewParent instanceof ViewRootImpl) {
15472            // *cough*
15473            final ViewRootImpl vr = (ViewRootImpl) viewParent;
15474            position[1] -= vr.mCurScrollY;
15475        }
15476
15477        location[0] = (int) (position[0] + 0.5f);
15478        location[1] = (int) (position[1] + 0.5f);
15479    }
15480
15481    /**
15482     * {@hide}
15483     * @param id the id of the view to be found
15484     * @return the view of the specified id, null if cannot be found
15485     */
15486    protected View findViewTraversal(int id) {
15487        if (id == mID) {
15488            return this;
15489        }
15490        return null;
15491    }
15492
15493    /**
15494     * {@hide}
15495     * @param tag the tag of the view to be found
15496     * @return the view of specified tag, null if cannot be found
15497     */
15498    protected View findViewWithTagTraversal(Object tag) {
15499        if (tag != null && tag.equals(mTag)) {
15500            return this;
15501        }
15502        return null;
15503    }
15504
15505    /**
15506     * {@hide}
15507     * @param predicate The predicate to evaluate.
15508     * @param childToSkip If not null, ignores this child during the recursive traversal.
15509     * @return The first view that matches the predicate or null.
15510     */
15511    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
15512        if (predicate.apply(this)) {
15513            return this;
15514        }
15515        return null;
15516    }
15517
15518    /**
15519     * Look for a child view with the given id.  If this view has the given
15520     * id, return this view.
15521     *
15522     * @param id The id to search for.
15523     * @return The view that has the given id in the hierarchy or null
15524     */
15525    public final View findViewById(int id) {
15526        if (id < 0) {
15527            return null;
15528        }
15529        return findViewTraversal(id);
15530    }
15531
15532    /**
15533     * Finds a view by its unuque and stable accessibility id.
15534     *
15535     * @param accessibilityId The searched accessibility id.
15536     * @return The found view.
15537     */
15538    final View findViewByAccessibilityId(int accessibilityId) {
15539        if (accessibilityId < 0) {
15540            return null;
15541        }
15542        return findViewByAccessibilityIdTraversal(accessibilityId);
15543    }
15544
15545    /**
15546     * Performs the traversal to find a view by its unuque and stable accessibility id.
15547     *
15548     * <strong>Note:</strong>This method does not stop at the root namespace
15549     * boundary since the user can touch the screen at an arbitrary location
15550     * potentially crossing the root namespace bounday which will send an
15551     * accessibility event to accessibility services and they should be able
15552     * to obtain the event source. Also accessibility ids are guaranteed to be
15553     * unique in the window.
15554     *
15555     * @param accessibilityId The accessibility id.
15556     * @return The found view.
15557     *
15558     * @hide
15559     */
15560    public View findViewByAccessibilityIdTraversal(int accessibilityId) {
15561        if (getAccessibilityViewId() == accessibilityId) {
15562            return this;
15563        }
15564        return null;
15565    }
15566
15567    /**
15568     * Look for a child view with the given tag.  If this view has the given
15569     * tag, return this view.
15570     *
15571     * @param tag The tag to search for, using "tag.equals(getTag())".
15572     * @return The View that has the given tag in the hierarchy or null
15573     */
15574    public final View findViewWithTag(Object tag) {
15575        if (tag == null) {
15576            return null;
15577        }
15578        return findViewWithTagTraversal(tag);
15579    }
15580
15581    /**
15582     * {@hide}
15583     * Look for a child view that matches the specified predicate.
15584     * If this view matches the predicate, return this view.
15585     *
15586     * @param predicate The predicate to evaluate.
15587     * @return The first view that matches the predicate or null.
15588     */
15589    public final View findViewByPredicate(Predicate<View> predicate) {
15590        return findViewByPredicateTraversal(predicate, null);
15591    }
15592
15593    /**
15594     * {@hide}
15595     * Look for a child view that matches the specified predicate,
15596     * starting with the specified view and its descendents and then
15597     * recusively searching the ancestors and siblings of that view
15598     * until this view is reached.
15599     *
15600     * This method is useful in cases where the predicate does not match
15601     * a single unique view (perhaps multiple views use the same id)
15602     * and we are trying to find the view that is "closest" in scope to the
15603     * starting view.
15604     *
15605     * @param start The view to start from.
15606     * @param predicate The predicate to evaluate.
15607     * @return The first view that matches the predicate or null.
15608     */
15609    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
15610        View childToSkip = null;
15611        for (;;) {
15612            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
15613            if (view != null || start == this) {
15614                return view;
15615            }
15616
15617            ViewParent parent = start.getParent();
15618            if (parent == null || !(parent instanceof View)) {
15619                return null;
15620            }
15621
15622            childToSkip = start;
15623            start = (View) parent;
15624        }
15625    }
15626
15627    /**
15628     * Sets the identifier for this view. The identifier does not have to be
15629     * unique in this view's hierarchy. The identifier should be a positive
15630     * number.
15631     *
15632     * @see #NO_ID
15633     * @see #getId()
15634     * @see #findViewById(int)
15635     *
15636     * @param id a number used to identify the view
15637     *
15638     * @attr ref android.R.styleable#View_id
15639     */
15640    public void setId(int id) {
15641        mID = id;
15642        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
15643            mID = generateViewId();
15644        }
15645    }
15646
15647    /**
15648     * {@hide}
15649     *
15650     * @param isRoot true if the view belongs to the root namespace, false
15651     *        otherwise
15652     */
15653    public void setIsRootNamespace(boolean isRoot) {
15654        if (isRoot) {
15655            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
15656        } else {
15657            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
15658        }
15659    }
15660
15661    /**
15662     * {@hide}
15663     *
15664     * @return true if the view belongs to the root namespace, false otherwise
15665     */
15666    public boolean isRootNamespace() {
15667        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
15668    }
15669
15670    /**
15671     * Returns this view's identifier.
15672     *
15673     * @return a positive integer used to identify the view or {@link #NO_ID}
15674     *         if the view has no ID
15675     *
15676     * @see #setId(int)
15677     * @see #findViewById(int)
15678     * @attr ref android.R.styleable#View_id
15679     */
15680    @ViewDebug.CapturedViewProperty
15681    public int getId() {
15682        return mID;
15683    }
15684
15685    /**
15686     * Returns this view's tag.
15687     *
15688     * @return the Object stored in this view as a tag
15689     *
15690     * @see #setTag(Object)
15691     * @see #getTag(int)
15692     */
15693    @ViewDebug.ExportedProperty
15694    public Object getTag() {
15695        return mTag;
15696    }
15697
15698    /**
15699     * Sets the tag associated with this view. A tag can be used to mark
15700     * a view in its hierarchy and does not have to be unique within the
15701     * hierarchy. Tags can also be used to store data within a view without
15702     * resorting to another data structure.
15703     *
15704     * @param tag an Object to tag the view with
15705     *
15706     * @see #getTag()
15707     * @see #setTag(int, Object)
15708     */
15709    public void setTag(final Object tag) {
15710        mTag = tag;
15711    }
15712
15713    /**
15714     * Returns the tag associated with this view and the specified key.
15715     *
15716     * @param key The key identifying the tag
15717     *
15718     * @return the Object stored in this view as a tag
15719     *
15720     * @see #setTag(int, Object)
15721     * @see #getTag()
15722     */
15723    public Object getTag(int key) {
15724        if (mKeyedTags != null) return mKeyedTags.get(key);
15725        return null;
15726    }
15727
15728    /**
15729     * Sets a tag associated with this view and a key. A tag can be used
15730     * to mark a view in its hierarchy and does not have to be unique within
15731     * the hierarchy. Tags can also be used to store data within a view
15732     * without resorting to another data structure.
15733     *
15734     * The specified key should be an id declared in the resources of the
15735     * application to ensure it is unique (see the <a
15736     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
15737     * Keys identified as belonging to
15738     * the Android framework or not associated with any package will cause
15739     * an {@link IllegalArgumentException} to be thrown.
15740     *
15741     * @param key The key identifying the tag
15742     * @param tag An Object to tag the view with
15743     *
15744     * @throws IllegalArgumentException If they specified key is not valid
15745     *
15746     * @see #setTag(Object)
15747     * @see #getTag(int)
15748     */
15749    public void setTag(int key, final Object tag) {
15750        // If the package id is 0x00 or 0x01, it's either an undefined package
15751        // or a framework id
15752        if ((key >>> 24) < 2) {
15753            throw new IllegalArgumentException("The key must be an application-specific "
15754                    + "resource id.");
15755        }
15756
15757        setKeyedTag(key, tag);
15758    }
15759
15760    /**
15761     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
15762     * framework id.
15763     *
15764     * @hide
15765     */
15766    public void setTagInternal(int key, Object tag) {
15767        if ((key >>> 24) != 0x1) {
15768            throw new IllegalArgumentException("The key must be a framework-specific "
15769                    + "resource id.");
15770        }
15771
15772        setKeyedTag(key, tag);
15773    }
15774
15775    private void setKeyedTag(int key, Object tag) {
15776        if (mKeyedTags == null) {
15777            mKeyedTags = new SparseArray<Object>(2);
15778        }
15779
15780        mKeyedTags.put(key, tag);
15781    }
15782
15783    /**
15784     * Prints information about this view in the log output, with the tag
15785     * {@link #VIEW_LOG_TAG}.
15786     *
15787     * @hide
15788     */
15789    public void debug() {
15790        debug(0);
15791    }
15792
15793    /**
15794     * Prints information about this view in the log output, with the tag
15795     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
15796     * indentation defined by the <code>depth</code>.
15797     *
15798     * @param depth the indentation level
15799     *
15800     * @hide
15801     */
15802    protected void debug(int depth) {
15803        String output = debugIndent(depth - 1);
15804
15805        output += "+ " + this;
15806        int id = getId();
15807        if (id != -1) {
15808            output += " (id=" + id + ")";
15809        }
15810        Object tag = getTag();
15811        if (tag != null) {
15812            output += " (tag=" + tag + ")";
15813        }
15814        Log.d(VIEW_LOG_TAG, output);
15815
15816        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
15817            output = debugIndent(depth) + " FOCUSED";
15818            Log.d(VIEW_LOG_TAG, output);
15819        }
15820
15821        output = debugIndent(depth);
15822        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
15823                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
15824                + "} ";
15825        Log.d(VIEW_LOG_TAG, output);
15826
15827        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
15828                || mPaddingBottom != 0) {
15829            output = debugIndent(depth);
15830            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
15831                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
15832            Log.d(VIEW_LOG_TAG, output);
15833        }
15834
15835        output = debugIndent(depth);
15836        output += "mMeasureWidth=" + mMeasuredWidth +
15837                " mMeasureHeight=" + mMeasuredHeight;
15838        Log.d(VIEW_LOG_TAG, output);
15839
15840        output = debugIndent(depth);
15841        if (mLayoutParams == null) {
15842            output += "BAD! no layout params";
15843        } else {
15844            output = mLayoutParams.debug(output);
15845        }
15846        Log.d(VIEW_LOG_TAG, output);
15847
15848        output = debugIndent(depth);
15849        output += "flags={";
15850        output += View.printFlags(mViewFlags);
15851        output += "}";
15852        Log.d(VIEW_LOG_TAG, output);
15853
15854        output = debugIndent(depth);
15855        output += "privateFlags={";
15856        output += View.printPrivateFlags(mPrivateFlags);
15857        output += "}";
15858        Log.d(VIEW_LOG_TAG, output);
15859    }
15860
15861    /**
15862     * Creates a string of whitespaces used for indentation.
15863     *
15864     * @param depth the indentation level
15865     * @return a String containing (depth * 2 + 3) * 2 white spaces
15866     *
15867     * @hide
15868     */
15869    protected static String debugIndent(int depth) {
15870        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
15871        for (int i = 0; i < (depth * 2) + 3; i++) {
15872            spaces.append(' ').append(' ');
15873        }
15874        return spaces.toString();
15875    }
15876
15877    /**
15878     * <p>Return the offset of the widget's text baseline from the widget's top
15879     * boundary. If this widget does not support baseline alignment, this
15880     * method returns -1. </p>
15881     *
15882     * @return the offset of the baseline within the widget's bounds or -1
15883     *         if baseline alignment is not supported
15884     */
15885    @ViewDebug.ExportedProperty(category = "layout")
15886    public int getBaseline() {
15887        return -1;
15888    }
15889
15890    /**
15891     * Returns whether the view hierarchy is currently undergoing a layout pass. This
15892     * information is useful to avoid situations such as calling {@link #requestLayout()} during
15893     * a layout pass.
15894     *
15895     * @return whether the view hierarchy is currently undergoing a layout pass
15896     */
15897    public boolean isInLayout() {
15898        ViewRootImpl viewRoot = getViewRootImpl();
15899        return (viewRoot != null && viewRoot.isInLayout());
15900    }
15901
15902    /**
15903     * Call this when something has changed which has invalidated the
15904     * layout of this view. This will schedule a layout pass of the view
15905     * tree. This should not be called while the view hierarchy is currently in a layout
15906     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
15907     * end of the current layout pass (and then layout will run again) or after the current
15908     * frame is drawn and the next layout occurs.
15909     *
15910     * <p>Subclasses which override this method should call the superclass method to
15911     * handle possible request-during-layout errors correctly.</p>
15912     */
15913    public void requestLayout() {
15914        if (mMeasureCache != null) mMeasureCache.clear();
15915
15916        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
15917            // Only trigger request-during-layout logic if this is the view requesting it,
15918            // not the views in its parent hierarchy
15919            ViewRootImpl viewRoot = getViewRootImpl();
15920            if (viewRoot != null && viewRoot.isInLayout()) {
15921                if (!viewRoot.requestLayoutDuringLayout(this)) {
15922                    return;
15923                }
15924            }
15925            mAttachInfo.mViewRequestingLayout = this;
15926        }
15927
15928        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
15929        mPrivateFlags |= PFLAG_INVALIDATED;
15930
15931        if (mParent != null && !mParent.isLayoutRequested()) {
15932            mParent.requestLayout();
15933        }
15934        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
15935            mAttachInfo.mViewRequestingLayout = null;
15936        }
15937    }
15938
15939    /**
15940     * Forces this view to be laid out during the next layout pass.
15941     * This method does not call requestLayout() or forceLayout()
15942     * on the parent.
15943     */
15944    public void forceLayout() {
15945        if (mMeasureCache != null) mMeasureCache.clear();
15946
15947        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
15948        mPrivateFlags |= PFLAG_INVALIDATED;
15949    }
15950
15951    /**
15952     * <p>
15953     * This is called to find out how big a view should be. The parent
15954     * supplies constraint information in the width and height parameters.
15955     * </p>
15956     *
15957     * <p>
15958     * The actual measurement work of a view is performed in
15959     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
15960     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
15961     * </p>
15962     *
15963     *
15964     * @param widthMeasureSpec Horizontal space requirements as imposed by the
15965     *        parent
15966     * @param heightMeasureSpec Vertical space requirements as imposed by the
15967     *        parent
15968     *
15969     * @see #onMeasure(int, int)
15970     */
15971    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
15972        boolean optical = isLayoutModeOptical(this);
15973        if (optical != isLayoutModeOptical(mParent)) {
15974            Insets insets = getOpticalInsets();
15975            int oWidth  = insets.left + insets.right;
15976            int oHeight = insets.top  + insets.bottom;
15977            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
15978            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
15979        }
15980
15981        // Suppress sign extension for the low bytes
15982        long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
15983        if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
15984
15985        if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ||
15986                widthMeasureSpec != mOldWidthMeasureSpec ||
15987                heightMeasureSpec != mOldHeightMeasureSpec) {
15988
15989            // first clears the measured dimension flag
15990            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
15991
15992            resolveRtlPropertiesIfNeeded();
15993
15994            int cacheIndex = mMeasureCache.indexOfKey(key);
15995            if (cacheIndex < 0) {
15996                // measure ourselves, this should set the measured dimension flag back
15997                onMeasure(widthMeasureSpec, heightMeasureSpec);
15998                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
15999            } else {
16000                long value = mMeasureCache.valueAt(cacheIndex);
16001                // Casting a long to int drops the high 32 bits, no mask needed
16002                setMeasuredDimension((int) (value >> 32), (int) value);
16003                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
16004            }
16005
16006            // flag not set, setMeasuredDimension() was not invoked, we raise
16007            // an exception to warn the developer
16008            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
16009                throw new IllegalStateException("onMeasure() did not set the"
16010                        + " measured dimension by calling"
16011                        + " setMeasuredDimension()");
16012            }
16013
16014            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
16015        }
16016
16017        mOldWidthMeasureSpec = widthMeasureSpec;
16018        mOldHeightMeasureSpec = heightMeasureSpec;
16019
16020        mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
16021                (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
16022    }
16023
16024    /**
16025     * <p>
16026     * Measure the view and its content to determine the measured width and the
16027     * measured height. This method is invoked by {@link #measure(int, int)} and
16028     * should be overriden by subclasses to provide accurate and efficient
16029     * measurement of their contents.
16030     * </p>
16031     *
16032     * <p>
16033     * <strong>CONTRACT:</strong> When overriding this method, you
16034     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
16035     * measured width and height of this view. Failure to do so will trigger an
16036     * <code>IllegalStateException</code>, thrown by
16037     * {@link #measure(int, int)}. Calling the superclass'
16038     * {@link #onMeasure(int, int)} is a valid use.
16039     * </p>
16040     *
16041     * <p>
16042     * The base class implementation of measure defaults to the background size,
16043     * unless a larger size is allowed by the MeasureSpec. Subclasses should
16044     * override {@link #onMeasure(int, int)} to provide better measurements of
16045     * their content.
16046     * </p>
16047     *
16048     * <p>
16049     * If this method is overridden, it is the subclass's responsibility to make
16050     * sure the measured height and width are at least the view's minimum height
16051     * and width ({@link #getSuggestedMinimumHeight()} and
16052     * {@link #getSuggestedMinimumWidth()}).
16053     * </p>
16054     *
16055     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
16056     *                         The requirements are encoded with
16057     *                         {@link android.view.View.MeasureSpec}.
16058     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
16059     *                         The requirements are encoded with
16060     *                         {@link android.view.View.MeasureSpec}.
16061     *
16062     * @see #getMeasuredWidth()
16063     * @see #getMeasuredHeight()
16064     * @see #setMeasuredDimension(int, int)
16065     * @see #getSuggestedMinimumHeight()
16066     * @see #getSuggestedMinimumWidth()
16067     * @see android.view.View.MeasureSpec#getMode(int)
16068     * @see android.view.View.MeasureSpec#getSize(int)
16069     */
16070    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
16071        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
16072                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
16073    }
16074
16075    /**
16076     * <p>This method must be called by {@link #onMeasure(int, int)} to store the
16077     * measured width and measured height. Failing to do so will trigger an
16078     * exception at measurement time.</p>
16079     *
16080     * @param measuredWidth The measured width of this view.  May be a complex
16081     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
16082     * {@link #MEASURED_STATE_TOO_SMALL}.
16083     * @param measuredHeight The measured height of this view.  May be a complex
16084     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
16085     * {@link #MEASURED_STATE_TOO_SMALL}.
16086     */
16087    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
16088        boolean optical = isLayoutModeOptical(this);
16089        if (optical != isLayoutModeOptical(mParent)) {
16090            Insets insets = getOpticalInsets();
16091            int opticalWidth  = insets.left + insets.right;
16092            int opticalHeight = insets.top  + insets.bottom;
16093
16094            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
16095            measuredHeight += optical ? opticalHeight : -opticalHeight;
16096        }
16097        mMeasuredWidth = measuredWidth;
16098        mMeasuredHeight = measuredHeight;
16099
16100        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
16101    }
16102
16103    /**
16104     * Merge two states as returned by {@link #getMeasuredState()}.
16105     * @param curState The current state as returned from a view or the result
16106     * of combining multiple views.
16107     * @param newState The new view state to combine.
16108     * @return Returns a new integer reflecting the combination of the two
16109     * states.
16110     */
16111    public static int combineMeasuredStates(int curState, int newState) {
16112        return curState | newState;
16113    }
16114
16115    /**
16116     * Version of {@link #resolveSizeAndState(int, int, int)}
16117     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
16118     */
16119    public static int resolveSize(int size, int measureSpec) {
16120        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
16121    }
16122
16123    /**
16124     * Utility to reconcile a desired size and state, with constraints imposed
16125     * by a MeasureSpec.  Will take the desired size, unless a different size
16126     * is imposed by the constraints.  The returned value is a compound integer,
16127     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
16128     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
16129     * size is smaller than the size the view wants to be.
16130     *
16131     * @param size How big the view wants to be
16132     * @param measureSpec Constraints imposed by the parent
16133     * @return Size information bit mask as defined by
16134     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
16135     */
16136    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
16137        int result = size;
16138        int specMode = MeasureSpec.getMode(measureSpec);
16139        int specSize =  MeasureSpec.getSize(measureSpec);
16140        switch (specMode) {
16141        case MeasureSpec.UNSPECIFIED:
16142            result = size;
16143            break;
16144        case MeasureSpec.AT_MOST:
16145            if (specSize < size) {
16146                result = specSize | MEASURED_STATE_TOO_SMALL;
16147            } else {
16148                result = size;
16149            }
16150            break;
16151        case MeasureSpec.EXACTLY:
16152            result = specSize;
16153            break;
16154        }
16155        return result | (childMeasuredState&MEASURED_STATE_MASK);
16156    }
16157
16158    /**
16159     * Utility to return a default size. Uses the supplied size if the
16160     * MeasureSpec imposed no constraints. Will get larger if allowed
16161     * by the MeasureSpec.
16162     *
16163     * @param size Default size for this view
16164     * @param measureSpec Constraints imposed by the parent
16165     * @return The size this view should be.
16166     */
16167    public static int getDefaultSize(int size, int measureSpec) {
16168        int result = size;
16169        int specMode = MeasureSpec.getMode(measureSpec);
16170        int specSize = MeasureSpec.getSize(measureSpec);
16171
16172        switch (specMode) {
16173        case MeasureSpec.UNSPECIFIED:
16174            result = size;
16175            break;
16176        case MeasureSpec.AT_MOST:
16177        case MeasureSpec.EXACTLY:
16178            result = specSize;
16179            break;
16180        }
16181        return result;
16182    }
16183
16184    /**
16185     * Returns the suggested minimum height that the view should use. This
16186     * returns the maximum of the view's minimum height
16187     * and the background's minimum height
16188     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
16189     * <p>
16190     * When being used in {@link #onMeasure(int, int)}, the caller should still
16191     * ensure the returned height is within the requirements of the parent.
16192     *
16193     * @return The suggested minimum height of the view.
16194     */
16195    protected int getSuggestedMinimumHeight() {
16196        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
16197
16198    }
16199
16200    /**
16201     * Returns the suggested minimum width that the view should use. This
16202     * returns the maximum of the view's minimum width)
16203     * and the background's minimum width
16204     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
16205     * <p>
16206     * When being used in {@link #onMeasure(int, int)}, the caller should still
16207     * ensure the returned width is within the requirements of the parent.
16208     *
16209     * @return The suggested minimum width of the view.
16210     */
16211    protected int getSuggestedMinimumWidth() {
16212        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
16213    }
16214
16215    /**
16216     * Returns the minimum height of the view.
16217     *
16218     * @return the minimum height the view will try to be.
16219     *
16220     * @see #setMinimumHeight(int)
16221     *
16222     * @attr ref android.R.styleable#View_minHeight
16223     */
16224    public int getMinimumHeight() {
16225        return mMinHeight;
16226    }
16227
16228    /**
16229     * Sets the minimum height of the view. It is not guaranteed the view will
16230     * be able to achieve this minimum height (for example, if its parent layout
16231     * constrains it with less available height).
16232     *
16233     * @param minHeight The minimum height the view will try to be.
16234     *
16235     * @see #getMinimumHeight()
16236     *
16237     * @attr ref android.R.styleable#View_minHeight
16238     */
16239    public void setMinimumHeight(int minHeight) {
16240        mMinHeight = minHeight;
16241        requestLayout();
16242    }
16243
16244    /**
16245     * Returns the minimum width of the view.
16246     *
16247     * @return the minimum width the view will try to be.
16248     *
16249     * @see #setMinimumWidth(int)
16250     *
16251     * @attr ref android.R.styleable#View_minWidth
16252     */
16253    public int getMinimumWidth() {
16254        return mMinWidth;
16255    }
16256
16257    /**
16258     * Sets the minimum width of the view. It is not guaranteed the view will
16259     * be able to achieve this minimum width (for example, if its parent layout
16260     * constrains it with less available width).
16261     *
16262     * @param minWidth The minimum width the view will try to be.
16263     *
16264     * @see #getMinimumWidth()
16265     *
16266     * @attr ref android.R.styleable#View_minWidth
16267     */
16268    public void setMinimumWidth(int minWidth) {
16269        mMinWidth = minWidth;
16270        requestLayout();
16271
16272    }
16273
16274    /**
16275     * Get the animation currently associated with this view.
16276     *
16277     * @return The animation that is currently playing or
16278     *         scheduled to play for this view.
16279     */
16280    public Animation getAnimation() {
16281        return mCurrentAnimation;
16282    }
16283
16284    /**
16285     * Start the specified animation now.
16286     *
16287     * @param animation the animation to start now
16288     */
16289    public void startAnimation(Animation animation) {
16290        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
16291        setAnimation(animation);
16292        invalidateParentCaches();
16293        invalidate(true);
16294    }
16295
16296    /**
16297     * Cancels any animations for this view.
16298     */
16299    public void clearAnimation() {
16300        if (mCurrentAnimation != null) {
16301            mCurrentAnimation.detach();
16302        }
16303        mCurrentAnimation = null;
16304        invalidateParentIfNeeded();
16305    }
16306
16307    /**
16308     * Sets the next animation to play for this view.
16309     * If you want the animation to play immediately, use
16310     * {@link #startAnimation(android.view.animation.Animation)} instead.
16311     * This method provides allows fine-grained
16312     * control over the start time and invalidation, but you
16313     * must make sure that 1) the animation has a start time set, and
16314     * 2) the view's parent (which controls animations on its children)
16315     * will be invalidated when the animation is supposed to
16316     * start.
16317     *
16318     * @param animation The next animation, or null.
16319     */
16320    public void setAnimation(Animation animation) {
16321        mCurrentAnimation = animation;
16322
16323        if (animation != null) {
16324            // If the screen is off assume the animation start time is now instead of
16325            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
16326            // would cause the animation to start when the screen turns back on
16327            if (mAttachInfo != null && !mAttachInfo.mScreenOn &&
16328                    animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
16329                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
16330            }
16331            animation.reset();
16332        }
16333    }
16334
16335    /**
16336     * Invoked by a parent ViewGroup to notify the start of the animation
16337     * currently associated with this view. If you override this method,
16338     * always call super.onAnimationStart();
16339     *
16340     * @see #setAnimation(android.view.animation.Animation)
16341     * @see #getAnimation()
16342     */
16343    protected void onAnimationStart() {
16344        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
16345    }
16346
16347    /**
16348     * Invoked by a parent ViewGroup to notify the end of the animation
16349     * currently associated with this view. If you override this method,
16350     * always call super.onAnimationEnd();
16351     *
16352     * @see #setAnimation(android.view.animation.Animation)
16353     * @see #getAnimation()
16354     */
16355    protected void onAnimationEnd() {
16356        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
16357    }
16358
16359    /**
16360     * Invoked if there is a Transform that involves alpha. Subclass that can
16361     * draw themselves with the specified alpha should return true, and then
16362     * respect that alpha when their onDraw() is called. If this returns false
16363     * then the view may be redirected to draw into an offscreen buffer to
16364     * fulfill the request, which will look fine, but may be slower than if the
16365     * subclass handles it internally. The default implementation returns false.
16366     *
16367     * @param alpha The alpha (0..255) to apply to the view's drawing
16368     * @return true if the view can draw with the specified alpha.
16369     */
16370    protected boolean onSetAlpha(int alpha) {
16371        return false;
16372    }
16373
16374    /**
16375     * This is used by the RootView to perform an optimization when
16376     * the view hierarchy contains one or several SurfaceView.
16377     * SurfaceView is always considered transparent, but its children are not,
16378     * therefore all View objects remove themselves from the global transparent
16379     * region (passed as a parameter to this function).
16380     *
16381     * @param region The transparent region for this ViewAncestor (window).
16382     *
16383     * @return Returns true if the effective visibility of the view at this
16384     * point is opaque, regardless of the transparent region; returns false
16385     * if it is possible for underlying windows to be seen behind the view.
16386     *
16387     * {@hide}
16388     */
16389    public boolean gatherTransparentRegion(Region region) {
16390        final AttachInfo attachInfo = mAttachInfo;
16391        if (region != null && attachInfo != null) {
16392            final int pflags = mPrivateFlags;
16393            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
16394                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
16395                // remove it from the transparent region.
16396                final int[] location = attachInfo.mTransparentLocation;
16397                getLocationInWindow(location);
16398                region.op(location[0], location[1], location[0] + mRight - mLeft,
16399                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
16400            } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) {
16401                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
16402                // exists, so we remove the background drawable's non-transparent
16403                // parts from this transparent region.
16404                applyDrawableToTransparentRegion(mBackground, region);
16405            }
16406        }
16407        return true;
16408    }
16409
16410    /**
16411     * Play a sound effect for this view.
16412     *
16413     * <p>The framework will play sound effects for some built in actions, such as
16414     * clicking, but you may wish to play these effects in your widget,
16415     * for instance, for internal navigation.
16416     *
16417     * <p>The sound effect will only be played if sound effects are enabled by the user, and
16418     * {@link #isSoundEffectsEnabled()} is true.
16419     *
16420     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
16421     */
16422    public void playSoundEffect(int soundConstant) {
16423        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
16424            return;
16425        }
16426        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
16427    }
16428
16429    /**
16430     * BZZZTT!!1!
16431     *
16432     * <p>Provide haptic feedback to the user for this view.
16433     *
16434     * <p>The framework will provide haptic feedback for some built in actions,
16435     * such as long presses, but you may wish to provide feedback for your
16436     * own widget.
16437     *
16438     * <p>The feedback will only be performed if
16439     * {@link #isHapticFeedbackEnabled()} is true.
16440     *
16441     * @param feedbackConstant One of the constants defined in
16442     * {@link HapticFeedbackConstants}
16443     */
16444    public boolean performHapticFeedback(int feedbackConstant) {
16445        return performHapticFeedback(feedbackConstant, 0);
16446    }
16447
16448    /**
16449     * BZZZTT!!1!
16450     *
16451     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
16452     *
16453     * @param feedbackConstant One of the constants defined in
16454     * {@link HapticFeedbackConstants}
16455     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
16456     */
16457    public boolean performHapticFeedback(int feedbackConstant, int flags) {
16458        if (mAttachInfo == null) {
16459            return false;
16460        }
16461        //noinspection SimplifiableIfStatement
16462        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
16463                && !isHapticFeedbackEnabled()) {
16464            return false;
16465        }
16466        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
16467                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
16468    }
16469
16470    /**
16471     * Request that the visibility of the status bar or other screen/window
16472     * decorations be changed.
16473     *
16474     * <p>This method is used to put the over device UI into temporary modes
16475     * where the user's attention is focused more on the application content,
16476     * by dimming or hiding surrounding system affordances.  This is typically
16477     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
16478     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
16479     * to be placed behind the action bar (and with these flags other system
16480     * affordances) so that smooth transitions between hiding and showing them
16481     * can be done.
16482     *
16483     * <p>Two representative examples of the use of system UI visibility is
16484     * implementing a content browsing application (like a magazine reader)
16485     * and a video playing application.
16486     *
16487     * <p>The first code shows a typical implementation of a View in a content
16488     * browsing application.  In this implementation, the application goes
16489     * into a content-oriented mode by hiding the status bar and action bar,
16490     * and putting the navigation elements into lights out mode.  The user can
16491     * then interact with content while in this mode.  Such an application should
16492     * provide an easy way for the user to toggle out of the mode (such as to
16493     * check information in the status bar or access notifications).  In the
16494     * implementation here, this is done simply by tapping on the content.
16495     *
16496     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
16497     *      content}
16498     *
16499     * <p>This second code sample shows a typical implementation of a View
16500     * in a video playing application.  In this situation, while the video is
16501     * playing the application would like to go into a complete full-screen mode,
16502     * to use as much of the display as possible for the video.  When in this state
16503     * the user can not interact with the application; the system intercepts
16504     * touching on the screen to pop the UI out of full screen mode.  See
16505     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
16506     *
16507     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
16508     *      content}
16509     *
16510     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
16511     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
16512     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
16513     * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}.
16514     */
16515    public void setSystemUiVisibility(int visibility) {
16516        if (visibility != mSystemUiVisibility) {
16517            mSystemUiVisibility = visibility;
16518            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
16519                mParent.recomputeViewAttributes(this);
16520            }
16521        }
16522    }
16523
16524    /**
16525     * Returns the last {@link #setSystemUiVisibility(int) that this view has requested.
16526     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
16527     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
16528     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
16529     * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}.
16530     */
16531    public int getSystemUiVisibility() {
16532        return mSystemUiVisibility;
16533    }
16534
16535    /**
16536     * Returns the current system UI visibility that is currently set for
16537     * the entire window.  This is the combination of the
16538     * {@link #setSystemUiVisibility(int)} values supplied by all of the
16539     * views in the window.
16540     */
16541    public int getWindowSystemUiVisibility() {
16542        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
16543    }
16544
16545    /**
16546     * Override to find out when the window's requested system UI visibility
16547     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
16548     * This is different from the callbacks received through
16549     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
16550     * in that this is only telling you about the local request of the window,
16551     * not the actual values applied by the system.
16552     */
16553    public void onWindowSystemUiVisibilityChanged(int visible) {
16554    }
16555
16556    /**
16557     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
16558     * the view hierarchy.
16559     */
16560    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
16561        onWindowSystemUiVisibilityChanged(visible);
16562    }
16563
16564    /**
16565     * Set a listener to receive callbacks when the visibility of the system bar changes.
16566     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
16567     */
16568    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
16569        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
16570        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
16571            mParent.recomputeViewAttributes(this);
16572        }
16573    }
16574
16575    /**
16576     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
16577     * the view hierarchy.
16578     */
16579    public void dispatchSystemUiVisibilityChanged(int visibility) {
16580        ListenerInfo li = mListenerInfo;
16581        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
16582            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
16583                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
16584        }
16585    }
16586
16587    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
16588        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
16589        if (val != mSystemUiVisibility) {
16590            setSystemUiVisibility(val);
16591            return true;
16592        }
16593        return false;
16594    }
16595
16596    /** @hide */
16597    public void setDisabledSystemUiVisibility(int flags) {
16598        if (mAttachInfo != null) {
16599            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
16600                mAttachInfo.mDisabledSystemUiVisibility = flags;
16601                if (mParent != null) {
16602                    mParent.recomputeViewAttributes(this);
16603                }
16604            }
16605        }
16606    }
16607
16608    /**
16609     * Creates an image that the system displays during the drag and drop
16610     * operation. This is called a &quot;drag shadow&quot;. The default implementation
16611     * for a DragShadowBuilder based on a View returns an image that has exactly the same
16612     * appearance as the given View. The default also positions the center of the drag shadow
16613     * directly under the touch point. If no View is provided (the constructor with no parameters
16614     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
16615     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
16616     * default is an invisible drag shadow.
16617     * <p>
16618     * You are not required to use the View you provide to the constructor as the basis of the
16619     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
16620     * anything you want as the drag shadow.
16621     * </p>
16622     * <p>
16623     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
16624     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
16625     *  size and position of the drag shadow. It uses this data to construct a
16626     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
16627     *  so that your application can draw the shadow image in the Canvas.
16628     * </p>
16629     *
16630     * <div class="special reference">
16631     * <h3>Developer Guides</h3>
16632     * <p>For a guide to implementing drag and drop features, read the
16633     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
16634     * </div>
16635     */
16636    public static class DragShadowBuilder {
16637        private final WeakReference<View> mView;
16638
16639        /**
16640         * Constructs a shadow image builder based on a View. By default, the resulting drag
16641         * shadow will have the same appearance and dimensions as the View, with the touch point
16642         * over the center of the View.
16643         * @param view A View. Any View in scope can be used.
16644         */
16645        public DragShadowBuilder(View view) {
16646            mView = new WeakReference<View>(view);
16647        }
16648
16649        /**
16650         * Construct a shadow builder object with no associated View.  This
16651         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
16652         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
16653         * to supply the drag shadow's dimensions and appearance without
16654         * reference to any View object. If they are not overridden, then the result is an
16655         * invisible drag shadow.
16656         */
16657        public DragShadowBuilder() {
16658            mView = new WeakReference<View>(null);
16659        }
16660
16661        /**
16662         * Returns the View object that had been passed to the
16663         * {@link #View.DragShadowBuilder(View)}
16664         * constructor.  If that View parameter was {@code null} or if the
16665         * {@link #View.DragShadowBuilder()}
16666         * constructor was used to instantiate the builder object, this method will return
16667         * null.
16668         *
16669         * @return The View object associate with this builder object.
16670         */
16671        @SuppressWarnings({"JavadocReference"})
16672        final public View getView() {
16673            return mView.get();
16674        }
16675
16676        /**
16677         * Provides the metrics for the shadow image. These include the dimensions of
16678         * the shadow image, and the point within that shadow that should
16679         * be centered under the touch location while dragging.
16680         * <p>
16681         * The default implementation sets the dimensions of the shadow to be the
16682         * same as the dimensions of the View itself and centers the shadow under
16683         * the touch point.
16684         * </p>
16685         *
16686         * @param shadowSize A {@link android.graphics.Point} containing the width and height
16687         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
16688         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
16689         * image.
16690         *
16691         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
16692         * shadow image that should be underneath the touch point during the drag and drop
16693         * operation. Your application must set {@link android.graphics.Point#x} to the
16694         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
16695         */
16696        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
16697            final View view = mView.get();
16698            if (view != null) {
16699                shadowSize.set(view.getWidth(), view.getHeight());
16700                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
16701            } else {
16702                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
16703            }
16704        }
16705
16706        /**
16707         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
16708         * based on the dimensions it received from the
16709         * {@link #onProvideShadowMetrics(Point, Point)} callback.
16710         *
16711         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
16712         */
16713        public void onDrawShadow(Canvas canvas) {
16714            final View view = mView.get();
16715            if (view != null) {
16716                view.draw(canvas);
16717            } else {
16718                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
16719            }
16720        }
16721    }
16722
16723    /**
16724     * Starts a drag and drop operation. When your application calls this method, it passes a
16725     * {@link android.view.View.DragShadowBuilder} object to the system. The
16726     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
16727     * to get metrics for the drag shadow, and then calls the object's
16728     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
16729     * <p>
16730     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
16731     *  drag events to all the View objects in your application that are currently visible. It does
16732     *  this either by calling the View object's drag listener (an implementation of
16733     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
16734     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
16735     *  Both are passed a {@link android.view.DragEvent} object that has a
16736     *  {@link android.view.DragEvent#getAction()} value of
16737     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
16738     * </p>
16739     * <p>
16740     * Your application can invoke startDrag() on any attached View object. The View object does not
16741     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
16742     * be related to the View the user selected for dragging.
16743     * </p>
16744     * @param data A {@link android.content.ClipData} object pointing to the data to be
16745     * transferred by the drag and drop operation.
16746     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
16747     * drag shadow.
16748     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
16749     * drop operation. This Object is put into every DragEvent object sent by the system during the
16750     * current drag.
16751     * <p>
16752     * myLocalState is a lightweight mechanism for the sending information from the dragged View
16753     * to the target Views. For example, it can contain flags that differentiate between a
16754     * a copy operation and a move operation.
16755     * </p>
16756     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
16757     * so the parameter should be set to 0.
16758     * @return {@code true} if the method completes successfully, or
16759     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
16760     * do a drag, and so no drag operation is in progress.
16761     */
16762    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
16763            Object myLocalState, int flags) {
16764        if (ViewDebug.DEBUG_DRAG) {
16765            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
16766        }
16767        boolean okay = false;
16768
16769        Point shadowSize = new Point();
16770        Point shadowTouchPoint = new Point();
16771        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
16772
16773        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
16774                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
16775            throw new IllegalStateException("Drag shadow dimensions must not be negative");
16776        }
16777
16778        if (ViewDebug.DEBUG_DRAG) {
16779            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
16780                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
16781        }
16782        Surface surface = new Surface();
16783        try {
16784            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
16785                    flags, shadowSize.x, shadowSize.y, surface);
16786            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
16787                    + " surface=" + surface);
16788            if (token != null) {
16789                Canvas canvas = surface.lockCanvas(null);
16790                try {
16791                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
16792                    shadowBuilder.onDrawShadow(canvas);
16793                } finally {
16794                    surface.unlockCanvasAndPost(canvas);
16795                }
16796
16797                final ViewRootImpl root = getViewRootImpl();
16798
16799                // Cache the local state object for delivery with DragEvents
16800                root.setLocalDragState(myLocalState);
16801
16802                // repurpose 'shadowSize' for the last touch point
16803                root.getLastTouchPoint(shadowSize);
16804
16805                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
16806                        shadowSize.x, shadowSize.y,
16807                        shadowTouchPoint.x, shadowTouchPoint.y, data);
16808                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
16809
16810                // Off and running!  Release our local surface instance; the drag
16811                // shadow surface is now managed by the system process.
16812                surface.release();
16813            }
16814        } catch (Exception e) {
16815            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
16816            surface.destroy();
16817        }
16818
16819        return okay;
16820    }
16821
16822    /**
16823     * Handles drag events sent by the system following a call to
16824     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
16825     *<p>
16826     * When the system calls this method, it passes a
16827     * {@link android.view.DragEvent} object. A call to
16828     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
16829     * in DragEvent. The method uses these to determine what is happening in the drag and drop
16830     * operation.
16831     * @param event The {@link android.view.DragEvent} sent by the system.
16832     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
16833     * in DragEvent, indicating the type of drag event represented by this object.
16834     * @return {@code true} if the method was successful, otherwise {@code false}.
16835     * <p>
16836     *  The method should return {@code true} in response to an action type of
16837     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
16838     *  operation.
16839     * </p>
16840     * <p>
16841     *  The method should also return {@code true} in response to an action type of
16842     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
16843     *  {@code false} if it didn't.
16844     * </p>
16845     */
16846    public boolean onDragEvent(DragEvent event) {
16847        return false;
16848    }
16849
16850    /**
16851     * Detects if this View is enabled and has a drag event listener.
16852     * If both are true, then it calls the drag event listener with the
16853     * {@link android.view.DragEvent} it received. If the drag event listener returns
16854     * {@code true}, then dispatchDragEvent() returns {@code true}.
16855     * <p>
16856     * For all other cases, the method calls the
16857     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
16858     * method and returns its result.
16859     * </p>
16860     * <p>
16861     * This ensures that a drag event is always consumed, even if the View does not have a drag
16862     * event listener. However, if the View has a listener and the listener returns true, then
16863     * onDragEvent() is not called.
16864     * </p>
16865     */
16866    public boolean dispatchDragEvent(DragEvent event) {
16867        ListenerInfo li = mListenerInfo;
16868        //noinspection SimplifiableIfStatement
16869        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
16870                && li.mOnDragListener.onDrag(this, event)) {
16871            return true;
16872        }
16873        return onDragEvent(event);
16874    }
16875
16876    boolean canAcceptDrag() {
16877        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
16878    }
16879
16880    /**
16881     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
16882     * it is ever exposed at all.
16883     * @hide
16884     */
16885    public void onCloseSystemDialogs(String reason) {
16886    }
16887
16888    /**
16889     * Given a Drawable whose bounds have been set to draw into this view,
16890     * update a Region being computed for
16891     * {@link #gatherTransparentRegion(android.graphics.Region)} so
16892     * that any non-transparent parts of the Drawable are removed from the
16893     * given transparent region.
16894     *
16895     * @param dr The Drawable whose transparency is to be applied to the region.
16896     * @param region A Region holding the current transparency information,
16897     * where any parts of the region that are set are considered to be
16898     * transparent.  On return, this region will be modified to have the
16899     * transparency information reduced by the corresponding parts of the
16900     * Drawable that are not transparent.
16901     * {@hide}
16902     */
16903    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
16904        if (DBG) {
16905            Log.i("View", "Getting transparent region for: " + this);
16906        }
16907        final Region r = dr.getTransparentRegion();
16908        final Rect db = dr.getBounds();
16909        final AttachInfo attachInfo = mAttachInfo;
16910        if (r != null && attachInfo != null) {
16911            final int w = getRight()-getLeft();
16912            final int h = getBottom()-getTop();
16913            if (db.left > 0) {
16914                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
16915                r.op(0, 0, db.left, h, Region.Op.UNION);
16916            }
16917            if (db.right < w) {
16918                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
16919                r.op(db.right, 0, w, h, Region.Op.UNION);
16920            }
16921            if (db.top > 0) {
16922                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
16923                r.op(0, 0, w, db.top, Region.Op.UNION);
16924            }
16925            if (db.bottom < h) {
16926                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
16927                r.op(0, db.bottom, w, h, Region.Op.UNION);
16928            }
16929            final int[] location = attachInfo.mTransparentLocation;
16930            getLocationInWindow(location);
16931            r.translate(location[0], location[1]);
16932            region.op(r, Region.Op.INTERSECT);
16933        } else {
16934            region.op(db, Region.Op.DIFFERENCE);
16935        }
16936    }
16937
16938    private void checkForLongClick(int delayOffset) {
16939        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
16940            mHasPerformedLongPress = false;
16941
16942            if (mPendingCheckForLongPress == null) {
16943                mPendingCheckForLongPress = new CheckForLongPress();
16944            }
16945            mPendingCheckForLongPress.rememberWindowAttachCount();
16946            postDelayed(mPendingCheckForLongPress,
16947                    ViewConfiguration.getLongPressTimeout() - delayOffset);
16948        }
16949    }
16950
16951    /**
16952     * Inflate a view from an XML resource.  This convenience method wraps the {@link
16953     * LayoutInflater} class, which provides a full range of options for view inflation.
16954     *
16955     * @param context The Context object for your activity or application.
16956     * @param resource The resource ID to inflate
16957     * @param root A view group that will be the parent.  Used to properly inflate the
16958     * layout_* parameters.
16959     * @see LayoutInflater
16960     */
16961    public static View inflate(Context context, int resource, ViewGroup root) {
16962        LayoutInflater factory = LayoutInflater.from(context);
16963        return factory.inflate(resource, root);
16964    }
16965
16966    /**
16967     * Scroll the view with standard behavior for scrolling beyond the normal
16968     * content boundaries. Views that call this method should override
16969     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
16970     * results of an over-scroll operation.
16971     *
16972     * Views can use this method to handle any touch or fling-based scrolling.
16973     *
16974     * @param deltaX Change in X in pixels
16975     * @param deltaY Change in Y in pixels
16976     * @param scrollX Current X scroll value in pixels before applying deltaX
16977     * @param scrollY Current Y scroll value in pixels before applying deltaY
16978     * @param scrollRangeX Maximum content scroll range along the X axis
16979     * @param scrollRangeY Maximum content scroll range along the Y axis
16980     * @param maxOverScrollX Number of pixels to overscroll by in either direction
16981     *          along the X axis.
16982     * @param maxOverScrollY Number of pixels to overscroll by in either direction
16983     *          along the Y axis.
16984     * @param isTouchEvent true if this scroll operation is the result of a touch event.
16985     * @return true if scrolling was clamped to an over-scroll boundary along either
16986     *          axis, false otherwise.
16987     */
16988    @SuppressWarnings({"UnusedParameters"})
16989    protected boolean overScrollBy(int deltaX, int deltaY,
16990            int scrollX, int scrollY,
16991            int scrollRangeX, int scrollRangeY,
16992            int maxOverScrollX, int maxOverScrollY,
16993            boolean isTouchEvent) {
16994        final int overScrollMode = mOverScrollMode;
16995        final boolean canScrollHorizontal =
16996                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
16997        final boolean canScrollVertical =
16998                computeVerticalScrollRange() > computeVerticalScrollExtent();
16999        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
17000                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
17001        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
17002                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
17003
17004        int newScrollX = scrollX + deltaX;
17005        if (!overScrollHorizontal) {
17006            maxOverScrollX = 0;
17007        }
17008
17009        int newScrollY = scrollY + deltaY;
17010        if (!overScrollVertical) {
17011            maxOverScrollY = 0;
17012        }
17013
17014        // Clamp values if at the limits and record
17015        final int left = -maxOverScrollX;
17016        final int right = maxOverScrollX + scrollRangeX;
17017        final int top = -maxOverScrollY;
17018        final int bottom = maxOverScrollY + scrollRangeY;
17019
17020        boolean clampedX = false;
17021        if (newScrollX > right) {
17022            newScrollX = right;
17023            clampedX = true;
17024        } else if (newScrollX < left) {
17025            newScrollX = left;
17026            clampedX = true;
17027        }
17028
17029        boolean clampedY = false;
17030        if (newScrollY > bottom) {
17031            newScrollY = bottom;
17032            clampedY = true;
17033        } else if (newScrollY < top) {
17034            newScrollY = top;
17035            clampedY = true;
17036        }
17037
17038        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
17039
17040        return clampedX || clampedY;
17041    }
17042
17043    /**
17044     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
17045     * respond to the results of an over-scroll operation.
17046     *
17047     * @param scrollX New X scroll value in pixels
17048     * @param scrollY New Y scroll value in pixels
17049     * @param clampedX True if scrollX was clamped to an over-scroll boundary
17050     * @param clampedY True if scrollY was clamped to an over-scroll boundary
17051     */
17052    protected void onOverScrolled(int scrollX, int scrollY,
17053            boolean clampedX, boolean clampedY) {
17054        // Intentionally empty.
17055    }
17056
17057    /**
17058     * Returns the over-scroll mode for this view. The result will be
17059     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
17060     * (allow over-scrolling only if the view content is larger than the container),
17061     * or {@link #OVER_SCROLL_NEVER}.
17062     *
17063     * @return This view's over-scroll mode.
17064     */
17065    public int getOverScrollMode() {
17066        return mOverScrollMode;
17067    }
17068
17069    /**
17070     * Set the over-scroll mode for this view. Valid over-scroll modes are
17071     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
17072     * (allow over-scrolling only if the view content is larger than the container),
17073     * or {@link #OVER_SCROLL_NEVER}.
17074     *
17075     * Setting the over-scroll mode of a view will have an effect only if the
17076     * view is capable of scrolling.
17077     *
17078     * @param overScrollMode The new over-scroll mode for this view.
17079     */
17080    public void setOverScrollMode(int overScrollMode) {
17081        if (overScrollMode != OVER_SCROLL_ALWAYS &&
17082                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
17083                overScrollMode != OVER_SCROLL_NEVER) {
17084            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
17085        }
17086        mOverScrollMode = overScrollMode;
17087    }
17088
17089    /**
17090     * Gets a scale factor that determines the distance the view should scroll
17091     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
17092     * @return The vertical scroll scale factor.
17093     * @hide
17094     */
17095    protected float getVerticalScrollFactor() {
17096        if (mVerticalScrollFactor == 0) {
17097            TypedValue outValue = new TypedValue();
17098            if (!mContext.getTheme().resolveAttribute(
17099                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
17100                throw new IllegalStateException(
17101                        "Expected theme to define listPreferredItemHeight.");
17102            }
17103            mVerticalScrollFactor = outValue.getDimension(
17104                    mContext.getResources().getDisplayMetrics());
17105        }
17106        return mVerticalScrollFactor;
17107    }
17108
17109    /**
17110     * Gets a scale factor that determines the distance the view should scroll
17111     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
17112     * @return The horizontal scroll scale factor.
17113     * @hide
17114     */
17115    protected float getHorizontalScrollFactor() {
17116        // TODO: Should use something else.
17117        return getVerticalScrollFactor();
17118    }
17119
17120    /**
17121     * Return the value specifying the text direction or policy that was set with
17122     * {@link #setTextDirection(int)}.
17123     *
17124     * @return the defined text direction. It can be one of:
17125     *
17126     * {@link #TEXT_DIRECTION_INHERIT},
17127     * {@link #TEXT_DIRECTION_FIRST_STRONG}
17128     * {@link #TEXT_DIRECTION_ANY_RTL},
17129     * {@link #TEXT_DIRECTION_LTR},
17130     * {@link #TEXT_DIRECTION_RTL},
17131     * {@link #TEXT_DIRECTION_LOCALE}
17132     *
17133     * @attr ref android.R.styleable#View_textDirection
17134     *
17135     * @hide
17136     */
17137    @ViewDebug.ExportedProperty(category = "text", mapping = {
17138            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
17139            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
17140            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
17141            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
17142            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
17143            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
17144    })
17145    public int getRawTextDirection() {
17146        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
17147    }
17148
17149    /**
17150     * Set the text direction.
17151     *
17152     * @param textDirection the direction to set. Should be one of:
17153     *
17154     * {@link #TEXT_DIRECTION_INHERIT},
17155     * {@link #TEXT_DIRECTION_FIRST_STRONG}
17156     * {@link #TEXT_DIRECTION_ANY_RTL},
17157     * {@link #TEXT_DIRECTION_LTR},
17158     * {@link #TEXT_DIRECTION_RTL},
17159     * {@link #TEXT_DIRECTION_LOCALE}
17160     *
17161     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
17162     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
17163     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
17164     *
17165     * @attr ref android.R.styleable#View_textDirection
17166     */
17167    public void setTextDirection(int textDirection) {
17168        if (getRawTextDirection() != textDirection) {
17169            // Reset the current text direction and the resolved one
17170            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
17171            resetResolvedTextDirection();
17172            // Set the new text direction
17173            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
17174            // Do resolution
17175            resolveTextDirection();
17176            // Notify change
17177            onRtlPropertiesChanged(getLayoutDirection());
17178            // Refresh
17179            requestLayout();
17180            invalidate(true);
17181        }
17182    }
17183
17184    /**
17185     * Return the resolved text direction.
17186     *
17187     * @return the resolved text direction. Returns one of:
17188     *
17189     * {@link #TEXT_DIRECTION_FIRST_STRONG}
17190     * {@link #TEXT_DIRECTION_ANY_RTL},
17191     * {@link #TEXT_DIRECTION_LTR},
17192     * {@link #TEXT_DIRECTION_RTL},
17193     * {@link #TEXT_DIRECTION_LOCALE}
17194     *
17195     * @attr ref android.R.styleable#View_textDirection
17196     */
17197    @ViewDebug.ExportedProperty(category = "text", mapping = {
17198            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
17199            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
17200            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
17201            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
17202            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
17203            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
17204    })
17205    public int getTextDirection() {
17206        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
17207    }
17208
17209    /**
17210     * Resolve the text direction.
17211     *
17212     * @return true if resolution has been done, false otherwise.
17213     *
17214     * @hide
17215     */
17216    public boolean resolveTextDirection() {
17217        // Reset any previous text direction resolution
17218        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
17219
17220        if (hasRtlSupport()) {
17221            // Set resolved text direction flag depending on text direction flag
17222            final int textDirection = getRawTextDirection();
17223            switch(textDirection) {
17224                case TEXT_DIRECTION_INHERIT:
17225                    if (!canResolveTextDirection()) {
17226                        // We cannot do the resolution if there is no parent, so use the default one
17227                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17228                        // Resolution will need to happen again later
17229                        return false;
17230                    }
17231
17232                    // Parent has not yet resolved, so we still return the default
17233                    try {
17234                        if (!mParent.isTextDirectionResolved()) {
17235                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17236                            // Resolution will need to happen again later
17237                            return false;
17238                        }
17239                    } catch (AbstractMethodError e) {
17240                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
17241                                " does not fully implement ViewParent", e);
17242                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED |
17243                                PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17244                        return true;
17245                    }
17246
17247                    // Set current resolved direction to the same value as the parent's one
17248                    int parentResolvedDirection;
17249                    try {
17250                        parentResolvedDirection = mParent.getTextDirection();
17251                    } catch (AbstractMethodError e) {
17252                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
17253                                " does not fully implement ViewParent", e);
17254                        parentResolvedDirection = TEXT_DIRECTION_LTR;
17255                    }
17256                    switch (parentResolvedDirection) {
17257                        case TEXT_DIRECTION_FIRST_STRONG:
17258                        case TEXT_DIRECTION_ANY_RTL:
17259                        case TEXT_DIRECTION_LTR:
17260                        case TEXT_DIRECTION_RTL:
17261                        case TEXT_DIRECTION_LOCALE:
17262                            mPrivateFlags2 |=
17263                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
17264                            break;
17265                        default:
17266                            // Default resolved direction is "first strong" heuristic
17267                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17268                    }
17269                    break;
17270                case TEXT_DIRECTION_FIRST_STRONG:
17271                case TEXT_DIRECTION_ANY_RTL:
17272                case TEXT_DIRECTION_LTR:
17273                case TEXT_DIRECTION_RTL:
17274                case TEXT_DIRECTION_LOCALE:
17275                    // Resolved direction is the same as text direction
17276                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
17277                    break;
17278                default:
17279                    // Default resolved direction is "first strong" heuristic
17280                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17281            }
17282        } else {
17283            // Default resolved direction is "first strong" heuristic
17284            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17285        }
17286
17287        // Set to resolved
17288        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
17289        return true;
17290    }
17291
17292    /**
17293     * Check if text direction resolution can be done.
17294     *
17295     * @return true if text direction resolution can be done otherwise return false.
17296     */
17297    public boolean canResolveTextDirection() {
17298        switch (getRawTextDirection()) {
17299            case TEXT_DIRECTION_INHERIT:
17300                if (mParent != null) {
17301                    try {
17302                        return mParent.canResolveTextDirection();
17303                    } catch (AbstractMethodError e) {
17304                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
17305                                " does not fully implement ViewParent", e);
17306                    }
17307                }
17308                return false;
17309
17310            default:
17311                return true;
17312        }
17313    }
17314
17315    /**
17316     * Reset resolved text direction. Text direction will be resolved during a call to
17317     * {@link #onMeasure(int, int)}.
17318     *
17319     * @hide
17320     */
17321    public void resetResolvedTextDirection() {
17322        // Reset any previous text direction resolution
17323        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
17324        // Set to default value
17325        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17326    }
17327
17328    /**
17329     * @return true if text direction is inherited.
17330     *
17331     * @hide
17332     */
17333    public boolean isTextDirectionInherited() {
17334        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
17335    }
17336
17337    /**
17338     * @return true if text direction is resolved.
17339     */
17340    public boolean isTextDirectionResolved() {
17341        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
17342    }
17343
17344    /**
17345     * Return the value specifying the text alignment or policy that was set with
17346     * {@link #setTextAlignment(int)}.
17347     *
17348     * @return the defined text alignment. It can be one of:
17349     *
17350     * {@link #TEXT_ALIGNMENT_INHERIT},
17351     * {@link #TEXT_ALIGNMENT_GRAVITY},
17352     * {@link #TEXT_ALIGNMENT_CENTER},
17353     * {@link #TEXT_ALIGNMENT_TEXT_START},
17354     * {@link #TEXT_ALIGNMENT_TEXT_END},
17355     * {@link #TEXT_ALIGNMENT_VIEW_START},
17356     * {@link #TEXT_ALIGNMENT_VIEW_END}
17357     *
17358     * @attr ref android.R.styleable#View_textAlignment
17359     *
17360     * @hide
17361     */
17362    @ViewDebug.ExportedProperty(category = "text", mapping = {
17363            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
17364            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
17365            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
17366            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
17367            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
17368            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
17369            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
17370    })
17371    public int getRawTextAlignment() {
17372        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
17373    }
17374
17375    /**
17376     * Set the text alignment.
17377     *
17378     * @param textAlignment The text alignment to set. Should be one of
17379     *
17380     * {@link #TEXT_ALIGNMENT_INHERIT},
17381     * {@link #TEXT_ALIGNMENT_GRAVITY},
17382     * {@link #TEXT_ALIGNMENT_CENTER},
17383     * {@link #TEXT_ALIGNMENT_TEXT_START},
17384     * {@link #TEXT_ALIGNMENT_TEXT_END},
17385     * {@link #TEXT_ALIGNMENT_VIEW_START},
17386     * {@link #TEXT_ALIGNMENT_VIEW_END}
17387     *
17388     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
17389     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
17390     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
17391     *
17392     * @attr ref android.R.styleable#View_textAlignment
17393     */
17394    public void setTextAlignment(int textAlignment) {
17395        if (textAlignment != getRawTextAlignment()) {
17396            // Reset the current and resolved text alignment
17397            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
17398            resetResolvedTextAlignment();
17399            // Set the new text alignment
17400            mPrivateFlags2 |=
17401                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
17402            // Do resolution
17403            resolveTextAlignment();
17404            // Notify change
17405            onRtlPropertiesChanged(getLayoutDirection());
17406            // Refresh
17407            requestLayout();
17408            invalidate(true);
17409        }
17410    }
17411
17412    /**
17413     * Return the resolved text alignment.
17414     *
17415     * @return the resolved text alignment. Returns one of:
17416     *
17417     * {@link #TEXT_ALIGNMENT_GRAVITY},
17418     * {@link #TEXT_ALIGNMENT_CENTER},
17419     * {@link #TEXT_ALIGNMENT_TEXT_START},
17420     * {@link #TEXT_ALIGNMENT_TEXT_END},
17421     * {@link #TEXT_ALIGNMENT_VIEW_START},
17422     * {@link #TEXT_ALIGNMENT_VIEW_END}
17423     *
17424     * @attr ref android.R.styleable#View_textAlignment
17425     */
17426    @ViewDebug.ExportedProperty(category = "text", mapping = {
17427            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
17428            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
17429            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
17430            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
17431            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
17432            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
17433            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
17434    })
17435    public int getTextAlignment() {
17436        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
17437                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
17438    }
17439
17440    /**
17441     * Resolve the text alignment.
17442     *
17443     * @return true if resolution has been done, false otherwise.
17444     *
17445     * @hide
17446     */
17447    public boolean resolveTextAlignment() {
17448        // Reset any previous text alignment resolution
17449        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
17450
17451        if (hasRtlSupport()) {
17452            // Set resolved text alignment flag depending on text alignment flag
17453            final int textAlignment = getRawTextAlignment();
17454            switch (textAlignment) {
17455                case TEXT_ALIGNMENT_INHERIT:
17456                    // Check if we can resolve the text alignment
17457                    if (!canResolveTextAlignment()) {
17458                        // We cannot do the resolution if there is no parent so use the default
17459                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17460                        // Resolution will need to happen again later
17461                        return false;
17462                    }
17463
17464                    // Parent has not yet resolved, so we still return the default
17465                    try {
17466                        if (!mParent.isTextAlignmentResolved()) {
17467                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17468                            // Resolution will need to happen again later
17469                            return false;
17470                        }
17471                    } catch (AbstractMethodError e) {
17472                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
17473                                " does not fully implement ViewParent", e);
17474                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED |
17475                                PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17476                        return true;
17477                    }
17478
17479                    int parentResolvedTextAlignment;
17480                    try {
17481                        parentResolvedTextAlignment = mParent.getTextAlignment();
17482                    } catch (AbstractMethodError e) {
17483                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
17484                                " does not fully implement ViewParent", e);
17485                        parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY;
17486                    }
17487                    switch (parentResolvedTextAlignment) {
17488                        case TEXT_ALIGNMENT_GRAVITY:
17489                        case TEXT_ALIGNMENT_TEXT_START:
17490                        case TEXT_ALIGNMENT_TEXT_END:
17491                        case TEXT_ALIGNMENT_CENTER:
17492                        case TEXT_ALIGNMENT_VIEW_START:
17493                        case TEXT_ALIGNMENT_VIEW_END:
17494                            // Resolved text alignment is the same as the parent resolved
17495                            // text alignment
17496                            mPrivateFlags2 |=
17497                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
17498                            break;
17499                        default:
17500                            // Use default resolved text alignment
17501                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17502                    }
17503                    break;
17504                case TEXT_ALIGNMENT_GRAVITY:
17505                case TEXT_ALIGNMENT_TEXT_START:
17506                case TEXT_ALIGNMENT_TEXT_END:
17507                case TEXT_ALIGNMENT_CENTER:
17508                case TEXT_ALIGNMENT_VIEW_START:
17509                case TEXT_ALIGNMENT_VIEW_END:
17510                    // Resolved text alignment is the same as text alignment
17511                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
17512                    break;
17513                default:
17514                    // Use default resolved text alignment
17515                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17516            }
17517        } else {
17518            // Use default resolved text alignment
17519            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17520        }
17521
17522        // Set the resolved
17523        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
17524        return true;
17525    }
17526
17527    /**
17528     * Check if text alignment resolution can be done.
17529     *
17530     * @return true if text alignment resolution can be done otherwise return false.
17531     */
17532    public boolean canResolveTextAlignment() {
17533        switch (getRawTextAlignment()) {
17534            case TEXT_DIRECTION_INHERIT:
17535                if (mParent != null) {
17536                    try {
17537                        return mParent.canResolveTextAlignment();
17538                    } catch (AbstractMethodError e) {
17539                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
17540                                " does not fully implement ViewParent", e);
17541                    }
17542                }
17543                return false;
17544
17545            default:
17546                return true;
17547        }
17548    }
17549
17550    /**
17551     * Reset resolved text alignment. Text alignment will be resolved during a call to
17552     * {@link #onMeasure(int, int)}.
17553     *
17554     * @hide
17555     */
17556    public void resetResolvedTextAlignment() {
17557        // Reset any previous text alignment resolution
17558        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
17559        // Set to default
17560        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17561    }
17562
17563    /**
17564     * @return true if text alignment is inherited.
17565     *
17566     * @hide
17567     */
17568    public boolean isTextAlignmentInherited() {
17569        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
17570    }
17571
17572    /**
17573     * @return true if text alignment is resolved.
17574     */
17575    public boolean isTextAlignmentResolved() {
17576        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
17577    }
17578
17579    /**
17580     * Generate a value suitable for use in {@link #setId(int)}.
17581     * This value will not collide with ID values generated at build time by aapt for R.id.
17582     *
17583     * @return a generated ID value
17584     */
17585    public static int generateViewId() {
17586        for (;;) {
17587            final int result = sNextGeneratedId.get();
17588            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
17589            int newValue = result + 1;
17590            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
17591            if (sNextGeneratedId.compareAndSet(result, newValue)) {
17592                return result;
17593            }
17594        }
17595    }
17596
17597    //
17598    // Properties
17599    //
17600    /**
17601     * A Property wrapper around the <code>alpha</code> functionality handled by the
17602     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
17603     */
17604    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
17605        @Override
17606        public void setValue(View object, float value) {
17607            object.setAlpha(value);
17608        }
17609
17610        @Override
17611        public Float get(View object) {
17612            return object.getAlpha();
17613        }
17614    };
17615
17616    /**
17617     * A Property wrapper around the <code>translationX</code> functionality handled by the
17618     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
17619     */
17620    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
17621        @Override
17622        public void setValue(View object, float value) {
17623            object.setTranslationX(value);
17624        }
17625
17626                @Override
17627        public Float get(View object) {
17628            return object.getTranslationX();
17629        }
17630    };
17631
17632    /**
17633     * A Property wrapper around the <code>translationY</code> functionality handled by the
17634     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
17635     */
17636    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
17637        @Override
17638        public void setValue(View object, float value) {
17639            object.setTranslationY(value);
17640        }
17641
17642        @Override
17643        public Float get(View object) {
17644            return object.getTranslationY();
17645        }
17646    };
17647
17648    /**
17649     * A Property wrapper around the <code>x</code> functionality handled by the
17650     * {@link View#setX(float)} and {@link View#getX()} methods.
17651     */
17652    public static final Property<View, Float> X = new FloatProperty<View>("x") {
17653        @Override
17654        public void setValue(View object, float value) {
17655            object.setX(value);
17656        }
17657
17658        @Override
17659        public Float get(View object) {
17660            return object.getX();
17661        }
17662    };
17663
17664    /**
17665     * A Property wrapper around the <code>y</code> functionality handled by the
17666     * {@link View#setY(float)} and {@link View#getY()} methods.
17667     */
17668    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
17669        @Override
17670        public void setValue(View object, float value) {
17671            object.setY(value);
17672        }
17673
17674        @Override
17675        public Float get(View object) {
17676            return object.getY();
17677        }
17678    };
17679
17680    /**
17681     * A Property wrapper around the <code>rotation</code> functionality handled by the
17682     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
17683     */
17684    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
17685        @Override
17686        public void setValue(View object, float value) {
17687            object.setRotation(value);
17688        }
17689
17690        @Override
17691        public Float get(View object) {
17692            return object.getRotation();
17693        }
17694    };
17695
17696    /**
17697     * A Property wrapper around the <code>rotationX</code> functionality handled by the
17698     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
17699     */
17700    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
17701        @Override
17702        public void setValue(View object, float value) {
17703            object.setRotationX(value);
17704        }
17705
17706        @Override
17707        public Float get(View object) {
17708            return object.getRotationX();
17709        }
17710    };
17711
17712    /**
17713     * A Property wrapper around the <code>rotationY</code> functionality handled by the
17714     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
17715     */
17716    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
17717        @Override
17718        public void setValue(View object, float value) {
17719            object.setRotationY(value);
17720        }
17721
17722        @Override
17723        public Float get(View object) {
17724            return object.getRotationY();
17725        }
17726    };
17727
17728    /**
17729     * A Property wrapper around the <code>scaleX</code> functionality handled by the
17730     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
17731     */
17732    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
17733        @Override
17734        public void setValue(View object, float value) {
17735            object.setScaleX(value);
17736        }
17737
17738        @Override
17739        public Float get(View object) {
17740            return object.getScaleX();
17741        }
17742    };
17743
17744    /**
17745     * A Property wrapper around the <code>scaleY</code> functionality handled by the
17746     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
17747     */
17748    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
17749        @Override
17750        public void setValue(View object, float value) {
17751            object.setScaleY(value);
17752        }
17753
17754        @Override
17755        public Float get(View object) {
17756            return object.getScaleY();
17757        }
17758    };
17759
17760    /**
17761     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
17762     * Each MeasureSpec represents a requirement for either the width or the height.
17763     * A MeasureSpec is comprised of a size and a mode. There are three possible
17764     * modes:
17765     * <dl>
17766     * <dt>UNSPECIFIED</dt>
17767     * <dd>
17768     * The parent has not imposed any constraint on the child. It can be whatever size
17769     * it wants.
17770     * </dd>
17771     *
17772     * <dt>EXACTLY</dt>
17773     * <dd>
17774     * The parent has determined an exact size for the child. The child is going to be
17775     * given those bounds regardless of how big it wants to be.
17776     * </dd>
17777     *
17778     * <dt>AT_MOST</dt>
17779     * <dd>
17780     * The child can be as large as it wants up to the specified size.
17781     * </dd>
17782     * </dl>
17783     *
17784     * MeasureSpecs are implemented as ints to reduce object allocation. This class
17785     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
17786     */
17787    public static class MeasureSpec {
17788        private static final int MODE_SHIFT = 30;
17789        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
17790
17791        /**
17792         * Measure specification mode: The parent has not imposed any constraint
17793         * on the child. It can be whatever size it wants.
17794         */
17795        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
17796
17797        /**
17798         * Measure specification mode: The parent has determined an exact size
17799         * for the child. The child is going to be given those bounds regardless
17800         * of how big it wants to be.
17801         */
17802        public static final int EXACTLY     = 1 << MODE_SHIFT;
17803
17804        /**
17805         * Measure specification mode: The child can be as large as it wants up
17806         * to the specified size.
17807         */
17808        public static final int AT_MOST     = 2 << MODE_SHIFT;
17809
17810        /**
17811         * Creates a measure specification based on the supplied size and mode.
17812         *
17813         * The mode must always be one of the following:
17814         * <ul>
17815         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
17816         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
17817         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
17818         * </ul>
17819         *
17820         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
17821         * implementation was such that the order of arguments did not matter
17822         * and overflow in either value could impact the resulting MeasureSpec.
17823         * {@link android.widget.RelativeLayout} was affected by this bug.
17824         * Apps targeting API levels greater than 17 will get the fixed, more strict
17825         * behavior.</p>
17826         *
17827         * @param size the size of the measure specification
17828         * @param mode the mode of the measure specification
17829         * @return the measure specification based on size and mode
17830         */
17831        public static int makeMeasureSpec(int size, int mode) {
17832            if (sUseBrokenMakeMeasureSpec) {
17833                return size + mode;
17834            } else {
17835                return (size & ~MODE_MASK) | (mode & MODE_MASK);
17836            }
17837        }
17838
17839        /**
17840         * Extracts the mode from the supplied measure specification.
17841         *
17842         * @param measureSpec the measure specification to extract the mode from
17843         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
17844         *         {@link android.view.View.MeasureSpec#AT_MOST} or
17845         *         {@link android.view.View.MeasureSpec#EXACTLY}
17846         */
17847        public static int getMode(int measureSpec) {
17848            return (measureSpec & MODE_MASK);
17849        }
17850
17851        /**
17852         * Extracts the size from the supplied measure specification.
17853         *
17854         * @param measureSpec the measure specification to extract the size from
17855         * @return the size in pixels defined in the supplied measure specification
17856         */
17857        public static int getSize(int measureSpec) {
17858            return (measureSpec & ~MODE_MASK);
17859        }
17860
17861        static int adjust(int measureSpec, int delta) {
17862            return makeMeasureSpec(getSize(measureSpec + delta), getMode(measureSpec));
17863        }
17864
17865        /**
17866         * Returns a String representation of the specified measure
17867         * specification.
17868         *
17869         * @param measureSpec the measure specification to convert to a String
17870         * @return a String with the following format: "MeasureSpec: MODE SIZE"
17871         */
17872        public static String toString(int measureSpec) {
17873            int mode = getMode(measureSpec);
17874            int size = getSize(measureSpec);
17875
17876            StringBuilder sb = new StringBuilder("MeasureSpec: ");
17877
17878            if (mode == UNSPECIFIED)
17879                sb.append("UNSPECIFIED ");
17880            else if (mode == EXACTLY)
17881                sb.append("EXACTLY ");
17882            else if (mode == AT_MOST)
17883                sb.append("AT_MOST ");
17884            else
17885                sb.append(mode).append(" ");
17886
17887            sb.append(size);
17888            return sb.toString();
17889        }
17890    }
17891
17892    class CheckForLongPress implements Runnable {
17893
17894        private int mOriginalWindowAttachCount;
17895
17896        public void run() {
17897            if (isPressed() && (mParent != null)
17898                    && mOriginalWindowAttachCount == mWindowAttachCount) {
17899                if (performLongClick()) {
17900                    mHasPerformedLongPress = true;
17901                }
17902            }
17903        }
17904
17905        public void rememberWindowAttachCount() {
17906            mOriginalWindowAttachCount = mWindowAttachCount;
17907        }
17908    }
17909
17910    private final class CheckForTap implements Runnable {
17911        public void run() {
17912            mPrivateFlags &= ~PFLAG_PREPRESSED;
17913            setPressed(true);
17914            checkForLongClick(ViewConfiguration.getTapTimeout());
17915        }
17916    }
17917
17918    private final class PerformClick implements Runnable {
17919        public void run() {
17920            performClick();
17921        }
17922    }
17923
17924    /** @hide */
17925    public void hackTurnOffWindowResizeAnim(boolean off) {
17926        mAttachInfo.mTurnOffWindowResizeAnim = off;
17927    }
17928
17929    /**
17930     * This method returns a ViewPropertyAnimator object, which can be used to animate
17931     * specific properties on this View.
17932     *
17933     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
17934     */
17935    public ViewPropertyAnimator animate() {
17936        if (mAnimator == null) {
17937            mAnimator = new ViewPropertyAnimator(this);
17938        }
17939        return mAnimator;
17940    }
17941
17942    /**
17943     * Set the current Scene that this view is in. The current scene is set only
17944     * on the root view of a scene, not for every view in that hierarchy. This
17945     * information is used by Scene to determine whether there is a previous
17946     * scene which should be exited before the new scene is entered.
17947     *
17948     * @param scene The new scene being set on the view
17949     *
17950     * @hide
17951     */
17952    public void setCurrentScene(Scene scene) {
17953        mCurrentScene = scene;
17954    }
17955
17956    /**
17957     * Gets the current {@link Scene} set on this view. A scene is set on a view
17958     * only if that view is the scene root.
17959     *
17960     * @return The current Scene set on this view. A value of null indicates that
17961     * no Scene is current set.
17962     */
17963    public Scene getCurrentScene() {
17964        return mCurrentScene;
17965    }
17966
17967    /**
17968     * Interface definition for a callback to be invoked when a hardware key event is
17969     * dispatched to this view. The callback will be invoked before the key event is
17970     * given to the view. This is only useful for hardware keyboards; a software input
17971     * method has no obligation to trigger this listener.
17972     */
17973    public interface OnKeyListener {
17974        /**
17975         * Called when a hardware key is dispatched to a view. This allows listeners to
17976         * get a chance to respond before the target view.
17977         * <p>Key presses in software keyboards will generally NOT trigger this method,
17978         * although some may elect to do so in some situations. Do not assume a
17979         * software input method has to be key-based; even if it is, it may use key presses
17980         * in a different way than you expect, so there is no way to reliably catch soft
17981         * input key presses.
17982         *
17983         * @param v The view the key has been dispatched to.
17984         * @param keyCode The code for the physical key that was pressed
17985         * @param event The KeyEvent object containing full information about
17986         *        the event.
17987         * @return True if the listener has consumed the event, false otherwise.
17988         */
17989        boolean onKey(View v, int keyCode, KeyEvent event);
17990    }
17991
17992    /**
17993     * Interface definition for a callback to be invoked when a touch event is
17994     * dispatched to this view. The callback will be invoked before the touch
17995     * event is given to the view.
17996     */
17997    public interface OnTouchListener {
17998        /**
17999         * Called when a touch event is dispatched to a view. This allows listeners to
18000         * get a chance to respond before the target view.
18001         *
18002         * @param v The view the touch event has been dispatched to.
18003         * @param event The MotionEvent object containing full information about
18004         *        the event.
18005         * @return True if the listener has consumed the event, false otherwise.
18006         */
18007        boolean onTouch(View v, MotionEvent event);
18008    }
18009
18010    /**
18011     * Interface definition for a callback to be invoked when a hover event is
18012     * dispatched to this view. The callback will be invoked before the hover
18013     * event is given to the view.
18014     */
18015    public interface OnHoverListener {
18016        /**
18017         * Called when a hover event is dispatched to a view. This allows listeners to
18018         * get a chance to respond before the target view.
18019         *
18020         * @param v The view the hover event has been dispatched to.
18021         * @param event The MotionEvent object containing full information about
18022         *        the event.
18023         * @return True if the listener has consumed the event, false otherwise.
18024         */
18025        boolean onHover(View v, MotionEvent event);
18026    }
18027
18028    /**
18029     * Interface definition for a callback to be invoked when a generic motion event is
18030     * dispatched to this view. The callback will be invoked before the generic motion
18031     * event is given to the view.
18032     */
18033    public interface OnGenericMotionListener {
18034        /**
18035         * Called when a generic motion event is dispatched to a view. This allows listeners to
18036         * get a chance to respond before the target view.
18037         *
18038         * @param v The view the generic motion event has been dispatched to.
18039         * @param event The MotionEvent object containing full information about
18040         *        the event.
18041         * @return True if the listener has consumed the event, false otherwise.
18042         */
18043        boolean onGenericMotion(View v, MotionEvent event);
18044    }
18045
18046    /**
18047     * Interface definition for a callback to be invoked when a view has been clicked and held.
18048     */
18049    public interface OnLongClickListener {
18050        /**
18051         * Called when a view has been clicked and held.
18052         *
18053         * @param v The view that was clicked and held.
18054         *
18055         * @return true if the callback consumed the long click, false otherwise.
18056         */
18057        boolean onLongClick(View v);
18058    }
18059
18060    /**
18061     * Interface definition for a callback to be invoked when a drag is being dispatched
18062     * to this view.  The callback will be invoked before the hosting view's own
18063     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
18064     * onDrag(event) behavior, it should return 'false' from this callback.
18065     *
18066     * <div class="special reference">
18067     * <h3>Developer Guides</h3>
18068     * <p>For a guide to implementing drag and drop features, read the
18069     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
18070     * </div>
18071     */
18072    public interface OnDragListener {
18073        /**
18074         * Called when a drag event is dispatched to a view. This allows listeners
18075         * to get a chance to override base View behavior.
18076         *
18077         * @param v The View that received the drag event.
18078         * @param event The {@link android.view.DragEvent} object for the drag event.
18079         * @return {@code true} if the drag event was handled successfully, or {@code false}
18080         * if the drag event was not handled. Note that {@code false} will trigger the View
18081         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
18082         */
18083        boolean onDrag(View v, DragEvent event);
18084    }
18085
18086    /**
18087     * Interface definition for a callback to be invoked when the focus state of
18088     * a view changed.
18089     */
18090    public interface OnFocusChangeListener {
18091        /**
18092         * Called when the focus state of a view has changed.
18093         *
18094         * @param v The view whose state has changed.
18095         * @param hasFocus The new focus state of v.
18096         */
18097        void onFocusChange(View v, boolean hasFocus);
18098    }
18099
18100    /**
18101     * Interface definition for a callback to be invoked when a view is clicked.
18102     */
18103    public interface OnClickListener {
18104        /**
18105         * Called when a view has been clicked.
18106         *
18107         * @param v The view that was clicked.
18108         */
18109        void onClick(View v);
18110    }
18111
18112    /**
18113     * Interface definition for a callback to be invoked when the context menu
18114     * for this view is being built.
18115     */
18116    public interface OnCreateContextMenuListener {
18117        /**
18118         * Called when the context menu for this view is being built. It is not
18119         * safe to hold onto the menu after this method returns.
18120         *
18121         * @param menu The context menu that is being built
18122         * @param v The view for which the context menu is being built
18123         * @param menuInfo Extra information about the item for which the
18124         *            context menu should be shown. This information will vary
18125         *            depending on the class of v.
18126         */
18127        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
18128    }
18129
18130    /**
18131     * Interface definition for a callback to be invoked when the status bar changes
18132     * visibility.  This reports <strong>global</strong> changes to the system UI
18133     * state, not what the application is requesting.
18134     *
18135     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
18136     */
18137    public interface OnSystemUiVisibilityChangeListener {
18138        /**
18139         * Called when the status bar changes visibility because of a call to
18140         * {@link View#setSystemUiVisibility(int)}.
18141         *
18142         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
18143         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
18144         * This tells you the <strong>global</strong> state of these UI visibility
18145         * flags, not what your app is currently applying.
18146         */
18147        public void onSystemUiVisibilityChange(int visibility);
18148    }
18149
18150    /**
18151     * Interface definition for a callback to be invoked when this view is attached
18152     * or detached from its window.
18153     */
18154    public interface OnAttachStateChangeListener {
18155        /**
18156         * Called when the view is attached to a window.
18157         * @param v The view that was attached
18158         */
18159        public void onViewAttachedToWindow(View v);
18160        /**
18161         * Called when the view is detached from a window.
18162         * @param v The view that was detached
18163         */
18164        public void onViewDetachedFromWindow(View v);
18165    }
18166
18167    private final class UnsetPressedState implements Runnable {
18168        public void run() {
18169            setPressed(false);
18170        }
18171    }
18172
18173    /**
18174     * Base class for derived classes that want to save and restore their own
18175     * state in {@link android.view.View#onSaveInstanceState()}.
18176     */
18177    public static class BaseSavedState extends AbsSavedState {
18178        /**
18179         * Constructor used when reading from a parcel. Reads the state of the superclass.
18180         *
18181         * @param source
18182         */
18183        public BaseSavedState(Parcel source) {
18184            super(source);
18185        }
18186
18187        /**
18188         * Constructor called by derived classes when creating their SavedState objects
18189         *
18190         * @param superState The state of the superclass of this view
18191         */
18192        public BaseSavedState(Parcelable superState) {
18193            super(superState);
18194        }
18195
18196        public static final Parcelable.Creator<BaseSavedState> CREATOR =
18197                new Parcelable.Creator<BaseSavedState>() {
18198            public BaseSavedState createFromParcel(Parcel in) {
18199                return new BaseSavedState(in);
18200            }
18201
18202            public BaseSavedState[] newArray(int size) {
18203                return new BaseSavedState[size];
18204            }
18205        };
18206    }
18207
18208    /**
18209     * A set of information given to a view when it is attached to its parent
18210     * window.
18211     */
18212    static class AttachInfo {
18213        interface Callbacks {
18214            void playSoundEffect(int effectId);
18215            boolean performHapticFeedback(int effectId, boolean always);
18216        }
18217
18218        /**
18219         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
18220         * to a Handler. This class contains the target (View) to invalidate and
18221         * the coordinates of the dirty rectangle.
18222         *
18223         * For performance purposes, this class also implements a pool of up to
18224         * POOL_LIMIT objects that get reused. This reduces memory allocations
18225         * whenever possible.
18226         */
18227        static class InvalidateInfo {
18228            private static final int POOL_LIMIT = 10;
18229
18230            private static final SynchronizedPool<InvalidateInfo> sPool =
18231                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
18232
18233            View target;
18234
18235            int left;
18236            int top;
18237            int right;
18238            int bottom;
18239
18240            public static InvalidateInfo obtain() {
18241                InvalidateInfo instance = sPool.acquire();
18242                return (instance != null) ? instance : new InvalidateInfo();
18243            }
18244
18245            public void recycle() {
18246                target = null;
18247                sPool.release(this);
18248            }
18249        }
18250
18251        final IWindowSession mSession;
18252
18253        final IWindow mWindow;
18254
18255        final IBinder mWindowToken;
18256
18257        final Display mDisplay;
18258
18259        final Callbacks mRootCallbacks;
18260
18261        HardwareCanvas mHardwareCanvas;
18262
18263        IWindowId mIWindowId;
18264        WindowId mWindowId;
18265
18266        /**
18267         * The top view of the hierarchy.
18268         */
18269        View mRootView;
18270
18271        IBinder mPanelParentWindowToken;
18272        Surface mSurface;
18273
18274        boolean mHardwareAccelerated;
18275        boolean mHardwareAccelerationRequested;
18276        HardwareRenderer mHardwareRenderer;
18277
18278        boolean mScreenOn;
18279
18280        /**
18281         * Scale factor used by the compatibility mode
18282         */
18283        float mApplicationScale;
18284
18285        /**
18286         * Indicates whether the application is in compatibility mode
18287         */
18288        boolean mScalingRequired;
18289
18290        /**
18291         * If set, ViewRootImpl doesn't use its lame animation for when the window resizes.
18292         */
18293        boolean mTurnOffWindowResizeAnim;
18294
18295        /**
18296         * Left position of this view's window
18297         */
18298        int mWindowLeft;
18299
18300        /**
18301         * Top position of this view's window
18302         */
18303        int mWindowTop;
18304
18305        /**
18306         * Indicates whether views need to use 32-bit drawing caches
18307         */
18308        boolean mUse32BitDrawingCache;
18309
18310        /**
18311         * For windows that are full-screen but using insets to layout inside
18312         * of the screen areas, these are the current insets to appear inside
18313         * the overscan area of the display.
18314         */
18315        final Rect mOverscanInsets = new Rect();
18316
18317        /**
18318         * For windows that are full-screen but using insets to layout inside
18319         * of the screen decorations, these are the current insets for the
18320         * content of the window.
18321         */
18322        final Rect mContentInsets = new Rect();
18323
18324        /**
18325         * For windows that are full-screen but using insets to layout inside
18326         * of the screen decorations, these are the current insets for the
18327         * actual visible parts of the window.
18328         */
18329        final Rect mVisibleInsets = new Rect();
18330
18331        /**
18332         * The internal insets given by this window.  This value is
18333         * supplied by the client (through
18334         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
18335         * be given to the window manager when changed to be used in laying
18336         * out windows behind it.
18337         */
18338        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
18339                = new ViewTreeObserver.InternalInsetsInfo();
18340
18341        /**
18342         * All views in the window's hierarchy that serve as scroll containers,
18343         * used to determine if the window can be resized or must be panned
18344         * to adjust for a soft input area.
18345         */
18346        final ArrayList<View> mScrollContainers = new ArrayList<View>();
18347
18348        final KeyEvent.DispatcherState mKeyDispatchState
18349                = new KeyEvent.DispatcherState();
18350
18351        /**
18352         * Indicates whether the view's window currently has the focus.
18353         */
18354        boolean mHasWindowFocus;
18355
18356        /**
18357         * The current visibility of the window.
18358         */
18359        int mWindowVisibility;
18360
18361        /**
18362         * Indicates the time at which drawing started to occur.
18363         */
18364        long mDrawingTime;
18365
18366        /**
18367         * Indicates whether or not ignoring the DIRTY_MASK flags.
18368         */
18369        boolean mIgnoreDirtyState;
18370
18371        /**
18372         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
18373         * to avoid clearing that flag prematurely.
18374         */
18375        boolean mSetIgnoreDirtyState = false;
18376
18377        /**
18378         * Indicates whether the view's window is currently in touch mode.
18379         */
18380        boolean mInTouchMode;
18381
18382        /**
18383         * Indicates that ViewAncestor should trigger a global layout change
18384         * the next time it performs a traversal
18385         */
18386        boolean mRecomputeGlobalAttributes;
18387
18388        /**
18389         * Always report new attributes at next traversal.
18390         */
18391        boolean mForceReportNewAttributes;
18392
18393        /**
18394         * Set during a traveral if any views want to keep the screen on.
18395         */
18396        boolean mKeepScreenOn;
18397
18398        /**
18399         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
18400         */
18401        int mSystemUiVisibility;
18402
18403        /**
18404         * Hack to force certain system UI visibility flags to be cleared.
18405         */
18406        int mDisabledSystemUiVisibility;
18407
18408        /**
18409         * Last global system UI visibility reported by the window manager.
18410         */
18411        int mGlobalSystemUiVisibility;
18412
18413        /**
18414         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
18415         * attached.
18416         */
18417        boolean mHasSystemUiListeners;
18418
18419        /**
18420         * Set if the window has requested to extend into the overscan region
18421         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
18422         */
18423        boolean mOverscanRequested;
18424
18425        /**
18426         * Set if the visibility of any views has changed.
18427         */
18428        boolean mViewVisibilityChanged;
18429
18430        /**
18431         * Set to true if a view has been scrolled.
18432         */
18433        boolean mViewScrollChanged;
18434
18435        /**
18436         * Global to the view hierarchy used as a temporary for dealing with
18437         * x/y points in the transparent region computations.
18438         */
18439        final int[] mTransparentLocation = new int[2];
18440
18441        /**
18442         * Global to the view hierarchy used as a temporary for dealing with
18443         * x/y points in the ViewGroup.invalidateChild implementation.
18444         */
18445        final int[] mInvalidateChildLocation = new int[2];
18446
18447
18448        /**
18449         * Global to the view hierarchy used as a temporary for dealing with
18450         * x/y location when view is transformed.
18451         */
18452        final float[] mTmpTransformLocation = new float[2];
18453
18454        /**
18455         * The view tree observer used to dispatch global events like
18456         * layout, pre-draw, touch mode change, etc.
18457         */
18458        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
18459
18460        /**
18461         * A Canvas used by the view hierarchy to perform bitmap caching.
18462         */
18463        Canvas mCanvas;
18464
18465        /**
18466         * The view root impl.
18467         */
18468        final ViewRootImpl mViewRootImpl;
18469
18470        /**
18471         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
18472         * handler can be used to pump events in the UI events queue.
18473         */
18474        final Handler mHandler;
18475
18476        /**
18477         * Temporary for use in computing invalidate rectangles while
18478         * calling up the hierarchy.
18479         */
18480        final Rect mTmpInvalRect = new Rect();
18481
18482        /**
18483         * Temporary for use in computing hit areas with transformed views
18484         */
18485        final RectF mTmpTransformRect = new RectF();
18486
18487        /**
18488         * Temporary for use in transforming invalidation rect
18489         */
18490        final Matrix mTmpMatrix = new Matrix();
18491
18492        /**
18493         * Temporary for use in transforming invalidation rect
18494         */
18495        final Transformation mTmpTransformation = new Transformation();
18496
18497        /**
18498         * Temporary list for use in collecting focusable descendents of a view.
18499         */
18500        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
18501
18502        /**
18503         * The id of the window for accessibility purposes.
18504         */
18505        int mAccessibilityWindowId = View.NO_ID;
18506
18507        /**
18508         * Flags related to accessibility processing.
18509         *
18510         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
18511         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
18512         */
18513        int mAccessibilityFetchFlags;
18514
18515        /**
18516         * The drawable for highlighting accessibility focus.
18517         */
18518        Drawable mAccessibilityFocusDrawable;
18519
18520        /**
18521         * Show where the margins, bounds and layout bounds are for each view.
18522         */
18523        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
18524
18525        /**
18526         * Point used to compute visible regions.
18527         */
18528        final Point mPoint = new Point();
18529
18530        /**
18531         * Used to track which View originated a requestLayout() call, used when
18532         * requestLayout() is called during layout.
18533         */
18534        View mViewRequestingLayout;
18535
18536        /**
18537         * Creates a new set of attachment information with the specified
18538         * events handler and thread.
18539         *
18540         * @param handler the events handler the view must use
18541         */
18542        AttachInfo(IWindowSession session, IWindow window, Display display,
18543                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
18544            mSession = session;
18545            mWindow = window;
18546            mWindowToken = window.asBinder();
18547            mDisplay = display;
18548            mViewRootImpl = viewRootImpl;
18549            mHandler = handler;
18550            mRootCallbacks = effectPlayer;
18551        }
18552    }
18553
18554    /**
18555     * <p>ScrollabilityCache holds various fields used by a View when scrolling
18556     * is supported. This avoids keeping too many unused fields in most
18557     * instances of View.</p>
18558     */
18559    private static class ScrollabilityCache implements Runnable {
18560
18561        /**
18562         * Scrollbars are not visible
18563         */
18564        public static final int OFF = 0;
18565
18566        /**
18567         * Scrollbars are visible
18568         */
18569        public static final int ON = 1;
18570
18571        /**
18572         * Scrollbars are fading away
18573         */
18574        public static final int FADING = 2;
18575
18576        public boolean fadeScrollBars;
18577
18578        public int fadingEdgeLength;
18579        public int scrollBarDefaultDelayBeforeFade;
18580        public int scrollBarFadeDuration;
18581
18582        public int scrollBarSize;
18583        public ScrollBarDrawable scrollBar;
18584        public float[] interpolatorValues;
18585        public View host;
18586
18587        public final Paint paint;
18588        public final Matrix matrix;
18589        public Shader shader;
18590
18591        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
18592
18593        private static final float[] OPAQUE = { 255 };
18594        private static final float[] TRANSPARENT = { 0.0f };
18595
18596        /**
18597         * When fading should start. This time moves into the future every time
18598         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
18599         */
18600        public long fadeStartTime;
18601
18602
18603        /**
18604         * The current state of the scrollbars: ON, OFF, or FADING
18605         */
18606        public int state = OFF;
18607
18608        private int mLastColor;
18609
18610        public ScrollabilityCache(ViewConfiguration configuration, View host) {
18611            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
18612            scrollBarSize = configuration.getScaledScrollBarSize();
18613            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
18614            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
18615
18616            paint = new Paint();
18617            matrix = new Matrix();
18618            // use use a height of 1, and then wack the matrix each time we
18619            // actually use it.
18620            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
18621            paint.setShader(shader);
18622            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
18623
18624            this.host = host;
18625        }
18626
18627        public void setFadeColor(int color) {
18628            if (color != mLastColor) {
18629                mLastColor = color;
18630
18631                if (color != 0) {
18632                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
18633                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
18634                    paint.setShader(shader);
18635                    // Restore the default transfer mode (src_over)
18636                    paint.setXfermode(null);
18637                } else {
18638                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
18639                    paint.setShader(shader);
18640                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
18641                }
18642            }
18643        }
18644
18645        public void run() {
18646            long now = AnimationUtils.currentAnimationTimeMillis();
18647            if (now >= fadeStartTime) {
18648
18649                // the animation fades the scrollbars out by changing
18650                // the opacity (alpha) from fully opaque to fully
18651                // transparent
18652                int nextFrame = (int) now;
18653                int framesCount = 0;
18654
18655                Interpolator interpolator = scrollBarInterpolator;
18656
18657                // Start opaque
18658                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
18659
18660                // End transparent
18661                nextFrame += scrollBarFadeDuration;
18662                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
18663
18664                state = FADING;
18665
18666                // Kick off the fade animation
18667                host.invalidate(true);
18668            }
18669        }
18670    }
18671
18672    /**
18673     * Resuable callback for sending
18674     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
18675     */
18676    private class SendViewScrolledAccessibilityEvent implements Runnable {
18677        public volatile boolean mIsPending;
18678
18679        public void run() {
18680            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
18681            mIsPending = false;
18682        }
18683    }
18684
18685    /**
18686     * <p>
18687     * This class represents a delegate that can be registered in a {@link View}
18688     * to enhance accessibility support via composition rather via inheritance.
18689     * It is specifically targeted to widget developers that extend basic View
18690     * classes i.e. classes in package android.view, that would like their
18691     * applications to be backwards compatible.
18692     * </p>
18693     * <div class="special reference">
18694     * <h3>Developer Guides</h3>
18695     * <p>For more information about making applications accessible, read the
18696     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
18697     * developer guide.</p>
18698     * </div>
18699     * <p>
18700     * A scenario in which a developer would like to use an accessibility delegate
18701     * is overriding a method introduced in a later API version then the minimal API
18702     * version supported by the application. For example, the method
18703     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
18704     * in API version 4 when the accessibility APIs were first introduced. If a
18705     * developer would like his application to run on API version 4 devices (assuming
18706     * all other APIs used by the application are version 4 or lower) and take advantage
18707     * of this method, instead of overriding the method which would break the application's
18708     * backwards compatibility, he can override the corresponding method in this
18709     * delegate and register the delegate in the target View if the API version of
18710     * the system is high enough i.e. the API version is same or higher to the API
18711     * version that introduced
18712     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
18713     * </p>
18714     * <p>
18715     * Here is an example implementation:
18716     * </p>
18717     * <code><pre><p>
18718     * if (Build.VERSION.SDK_INT >= 14) {
18719     *     // If the API version is equal of higher than the version in
18720     *     // which onInitializeAccessibilityNodeInfo was introduced we
18721     *     // register a delegate with a customized implementation.
18722     *     View view = findViewById(R.id.view_id);
18723     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
18724     *         public void onInitializeAccessibilityNodeInfo(View host,
18725     *                 AccessibilityNodeInfo info) {
18726     *             // Let the default implementation populate the info.
18727     *             super.onInitializeAccessibilityNodeInfo(host, info);
18728     *             // Set some other information.
18729     *             info.setEnabled(host.isEnabled());
18730     *         }
18731     *     });
18732     * }
18733     * </code></pre></p>
18734     * <p>
18735     * This delegate contains methods that correspond to the accessibility methods
18736     * in View. If a delegate has been specified the implementation in View hands
18737     * off handling to the corresponding method in this delegate. The default
18738     * implementation the delegate methods behaves exactly as the corresponding
18739     * method in View for the case of no accessibility delegate been set. Hence,
18740     * to customize the behavior of a View method, clients can override only the
18741     * corresponding delegate method without altering the behavior of the rest
18742     * accessibility related methods of the host view.
18743     * </p>
18744     */
18745    public static class AccessibilityDelegate {
18746
18747        /**
18748         * Sends an accessibility event of the given type. If accessibility is not
18749         * enabled this method has no effect.
18750         * <p>
18751         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
18752         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
18753         * been set.
18754         * </p>
18755         *
18756         * @param host The View hosting the delegate.
18757         * @param eventType The type of the event to send.
18758         *
18759         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
18760         */
18761        public void sendAccessibilityEvent(View host, int eventType) {
18762            host.sendAccessibilityEventInternal(eventType);
18763        }
18764
18765        /**
18766         * Performs the specified accessibility action on the view. For
18767         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
18768         * <p>
18769         * The default implementation behaves as
18770         * {@link View#performAccessibilityAction(int, Bundle)
18771         *  View#performAccessibilityAction(int, Bundle)} for the case of
18772         *  no accessibility delegate been set.
18773         * </p>
18774         *
18775         * @param action The action to perform.
18776         * @return Whether the action was performed.
18777         *
18778         * @see View#performAccessibilityAction(int, Bundle)
18779         *      View#performAccessibilityAction(int, Bundle)
18780         */
18781        public boolean performAccessibilityAction(View host, int action, Bundle args) {
18782            return host.performAccessibilityActionInternal(action, args);
18783        }
18784
18785        /**
18786         * Sends an accessibility event. This method behaves exactly as
18787         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
18788         * empty {@link AccessibilityEvent} and does not perform a check whether
18789         * accessibility is enabled.
18790         * <p>
18791         * The default implementation behaves as
18792         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
18793         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
18794         * the case of no accessibility delegate been set.
18795         * </p>
18796         *
18797         * @param host The View hosting the delegate.
18798         * @param event The event to send.
18799         *
18800         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
18801         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
18802         */
18803        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
18804            host.sendAccessibilityEventUncheckedInternal(event);
18805        }
18806
18807        /**
18808         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
18809         * to its children for adding their text content to the event.
18810         * <p>
18811         * The default implementation behaves as
18812         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
18813         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
18814         * the case of no accessibility delegate been set.
18815         * </p>
18816         *
18817         * @param host The View hosting the delegate.
18818         * @param event The event.
18819         * @return True if the event population was completed.
18820         *
18821         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
18822         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
18823         */
18824        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
18825            return host.dispatchPopulateAccessibilityEventInternal(event);
18826        }
18827
18828        /**
18829         * Gives a chance to the host View to populate the accessibility event with its
18830         * text content.
18831         * <p>
18832         * The default implementation behaves as
18833         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
18834         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
18835         * the case of no accessibility delegate been set.
18836         * </p>
18837         *
18838         * @param host The View hosting the delegate.
18839         * @param event The accessibility event which to populate.
18840         *
18841         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
18842         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
18843         */
18844        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
18845            host.onPopulateAccessibilityEventInternal(event);
18846        }
18847
18848        /**
18849         * Initializes an {@link AccessibilityEvent} with information about the
18850         * the host View which is the event source.
18851         * <p>
18852         * The default implementation behaves as
18853         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
18854         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
18855         * the case of no accessibility delegate been set.
18856         * </p>
18857         *
18858         * @param host The View hosting the delegate.
18859         * @param event The event to initialize.
18860         *
18861         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
18862         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
18863         */
18864        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
18865            host.onInitializeAccessibilityEventInternal(event);
18866        }
18867
18868        /**
18869         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
18870         * <p>
18871         * The default implementation behaves as
18872         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
18873         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
18874         * the case of no accessibility delegate been set.
18875         * </p>
18876         *
18877         * @param host The View hosting the delegate.
18878         * @param info The instance to initialize.
18879         *
18880         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
18881         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
18882         */
18883        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
18884            host.onInitializeAccessibilityNodeInfoInternal(info);
18885        }
18886
18887        /**
18888         * Called when a child of the host View has requested sending an
18889         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
18890         * to augment the event.
18891         * <p>
18892         * The default implementation behaves as
18893         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
18894         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
18895         * the case of no accessibility delegate been set.
18896         * </p>
18897         *
18898         * @param host The View hosting the delegate.
18899         * @param child The child which requests sending the event.
18900         * @param event The event to be sent.
18901         * @return True if the event should be sent
18902         *
18903         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
18904         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
18905         */
18906        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
18907                AccessibilityEvent event) {
18908            return host.onRequestSendAccessibilityEventInternal(child, event);
18909        }
18910
18911        /**
18912         * Gets the provider for managing a virtual view hierarchy rooted at this View
18913         * and reported to {@link android.accessibilityservice.AccessibilityService}s
18914         * that explore the window content.
18915         * <p>
18916         * The default implementation behaves as
18917         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
18918         * the case of no accessibility delegate been set.
18919         * </p>
18920         *
18921         * @return The provider.
18922         *
18923         * @see AccessibilityNodeProvider
18924         */
18925        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
18926            return null;
18927        }
18928
18929        /**
18930         * Returns an {@link AccessibilityNodeInfo} representing the host view from the
18931         * point of view of an {@link android.accessibilityservice.AccessibilityService}.
18932         * This method is responsible for obtaining an accessibility node info from a
18933         * pool of reusable instances and calling
18934         * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host
18935         * view to initialize the former.
18936         * <p>
18937         * <strong>Note:</strong> The client is responsible for recycling the obtained
18938         * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object
18939         * creation.
18940         * </p>
18941         * <p>
18942         * The default implementation behaves as
18943         * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for
18944         * the case of no accessibility delegate been set.
18945         * </p>
18946         * @return A populated {@link AccessibilityNodeInfo}.
18947         *
18948         * @see AccessibilityNodeInfo
18949         *
18950         * @hide
18951         */
18952        public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) {
18953            return host.createAccessibilityNodeInfoInternal();
18954        }
18955    }
18956
18957    private class MatchIdPredicate implements Predicate<View> {
18958        public int mId;
18959
18960        @Override
18961        public boolean apply(View view) {
18962            return (view.mID == mId);
18963        }
18964    }
18965
18966    private class MatchLabelForPredicate implements Predicate<View> {
18967        private int mLabeledId;
18968
18969        @Override
18970        public boolean apply(View view) {
18971            return (view.mLabelForId == mLabeledId);
18972        }
18973    }
18974
18975    private class SendViewStateChangedAccessibilityEvent implements Runnable {
18976        private boolean mPosted;
18977        private long mLastEventTimeMillis;
18978
18979        public void run() {
18980            mPosted = false;
18981            mLastEventTimeMillis = SystemClock.uptimeMillis();
18982            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
18983                AccessibilityEvent event = AccessibilityEvent.obtain();
18984                event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
18985                event.setContentChangeType(AccessibilityEvent.CONTENT_CHANGE_TYPE_NODE);
18986                sendAccessibilityEventUnchecked(event);
18987            }
18988        }
18989
18990        public void runOrPost() {
18991            if (mPosted) {
18992                return;
18993            }
18994            final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
18995            final long minEventIntevalMillis =
18996                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
18997            if (timeSinceLastMillis >= minEventIntevalMillis) {
18998                removeCallbacks(this);
18999                run();
19000            } else {
19001                postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
19002                mPosted = true;
19003            }
19004        }
19005    }
19006
19007    /**
19008     * Dump all private flags in readable format, useful for documentation and
19009     * sanity checking.
19010     */
19011    private static void dumpFlags() {
19012        final HashMap<String, String> found = Maps.newHashMap();
19013        try {
19014            for (Field field : View.class.getDeclaredFields()) {
19015                final int modifiers = field.getModifiers();
19016                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
19017                    if (field.getType().equals(int.class)) {
19018                        final int value = field.getInt(null);
19019                        dumpFlag(found, field.getName(), value);
19020                    } else if (field.getType().equals(int[].class)) {
19021                        final int[] values = (int[]) field.get(null);
19022                        for (int i = 0; i < values.length; i++) {
19023                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
19024                        }
19025                    }
19026                }
19027            }
19028        } catch (IllegalAccessException e) {
19029            throw new RuntimeException(e);
19030        }
19031
19032        final ArrayList<String> keys = Lists.newArrayList();
19033        keys.addAll(found.keySet());
19034        Collections.sort(keys);
19035        for (String key : keys) {
19036            Log.d(VIEW_LOG_TAG, found.get(key));
19037        }
19038    }
19039
19040    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
19041        // Sort flags by prefix, then by bits, always keeping unique keys
19042        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
19043        final int prefix = name.indexOf('_');
19044        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
19045        final String output = bits + " " + name;
19046        found.put(key, output);
19047    }
19048}
19049